diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f3cefdaa6a..caf936acda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -146,6 +146,18 @@ jobs: name: python-repository-tools-${{ github.run_attempt }} path: .artifacts/python/repository-tools/*.xml if-no-files-found: error + - name: TrailView tool unit tests + id: python-trailview + run: | + rm -rf .artifacts/python/trailview + uv run --locked --group trailview --group dev python -m xmlrunner discover -s tools/trailview/tests -v -o .artifacts/python/trailview + - name: Upload TrailView tool Python test results + if: ${{ !cancelled() && (steps.python-trailview.outcome == 'success' || steps.python-trailview.outcome == 'failure') }} + uses: actions/upload-artifact@v4 + with: + name: python-trailview-${{ github.run_attempt }} + path: .artifacts/python/trailview/*.xml + if-no-files-found: error - name: The job table and this workflow describe the same jobs run: uv run --locked --group dev python tools/test_plan.py validate-filters - name: Large fixture policy @@ -293,6 +305,10 @@ jobs: # is the same one `obc check test` runs. - name: cargo nextest (fast hermetic binaries) id: nextest + # The targets of a suite that owns some, such as the ground plan census, run only when the + # plan selects that suite. + env: + OBC_SELECTED_SUITES: ${{ join(fromJSON(needs.selection.outputs.plan).selected_suite_ids, ' ') }} run: bash tools/ci/test.sh nextest-fast - name: cargo nextest (captured fixture binaries) id: nextest-fixtures @@ -736,8 +752,9 @@ jobs: - name: cargo build -p obcm-assemble --lib (wasm32, engine only) run: cargo build -p obcm-assemble --lib --no-default-features --locked --target wasm32-unknown-unknown - # Build the shared core and its test-device feature variant. Gate production bytes before - # handing the same artifact to frontend tests and builds. The test device never ships. + # Build the shared core, its test-device feature variant and the ground plan bridge. Gate + # production bytes and run check 7 before handing the same artifacts to frontend tests and + # builds. The test device never ships. wasm-bridges: needs: selection if: contains(fromJSON(needs.selection.outputs.jobs), 'wasm-bridges') @@ -757,15 +774,28 @@ jobs: - uses: taiki-e/install-action@v2 with: tool: wasm-pack@0.15.0 - - name: Build builder core and test device + - uses: actions/setup-node@v4 + with: + node-version: "22" + - name: Build builder core, test device and ground plan bridge run: bash builder/build-wasm-bridges.sh - name: Builder core size budget run: python3 builder/wasm/wasm_size_guard.py + - name: Ground plan bridge size budget + run: python3 builder/wasm/wasm_size_guard.py --module ground-plan + # Every run: it writes the native digests that the browser jobs compare with the viewer's. + - name: Ground plan check 7, native and WASM bytes + run: bash builder/ground-plan-wasm/check-bytes.sh - uses: actions/upload-artifact@v4 with: name: obc-builder-bridge-pkg path: builder/web/src/lib/core/pkg retention-days: 1 + - uses: actions/upload-artifact@v4 + with: + name: obc-ground-plan-bridge-pkg + path: builder/web/src/lib/trailview/plan/pkg + retention-days: 1 # The test device. No size budget: it ships to nobody and only the `web` job downloads it. - uses: actions/upload-artifact@v4 with: @@ -1016,6 +1046,10 @@ jobs: with: name: obc-builder-bridge-pkg path: builder/web/src/lib/core/pkg + - uses: actions/download-artifact@v4 + with: + name: obc-ground-plan-bridge-pkg + path: builder/web/src/lib/trailview/plan/pkg # The device the USB suites run against. The shipped bundle must not contain this package. - uses: actions/download-artifact@v4 with: @@ -1083,6 +1117,10 @@ jobs: with: name: obc-builder-bridge-pkg path: builder/web/src/lib/core/pkg + - uses: actions/download-artifact@v4 + with: + name: obc-ground-plan-bridge-pkg + path: builder/web/src/lib/trailview/plan/pkg # The planner build of the browser tests holds the pretend device of `?fake-device`. - uses: actions/download-artifact@v4 with: diff --git a/.github/workflows/test-weekly.yml b/.github/workflows/test-weekly.yml index d7ee9180ab..6f7b133a98 100644 --- a/.github/workflows/test-weekly.yml +++ b/.github/workflows/test-weekly.yml @@ -32,36 +32,6 @@ jobs: name: ios-application-${{ github.run_attempt }} path: .artifacts/ios-application.xcresult if-no-files-found: error - trailview: - runs-on: ubuntu-24.04 - timeout-minutes: 60 - steps: - - uses: actions/checkout@v4 - with: - persist-credentials: false - - uses: actions/setup-node@v4 - with: - node-version: "22" - cache: npm - cache-dependency-path: builder/web/package-lock.json - - name: Install the builder's build dependencies - working-directory: builder/web - run: npm ci - - name: Install builder browser runner - working-directory: builder/web/tests/browser - run: | - npm ci - npx playwright install --with-deps chromium --only-shell - - name: Run registered weekly TrailView suites - id: test - run: npm run test:trailview --prefix builder/web/tests/browser - - name: Upload TrailView browser results - if: ${{ !cancelled() && (steps.test.outcome == 'success' || steps.test.outcome == 'failure') }} - uses: actions/upload-artifact@v4 - with: - name: trailview-weekly-${{ github.run_attempt }} - path: .artifacts/web-builder/ - if-no-files-found: error storage: runs-on: ubuntu-24.04 timeout-minutes: 10 diff --git a/.gitignore b/.gitignore index e6e80c7fb6..05a1dc13dc 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,7 @@ user_config.json # Generated builder core and test-device bindings. builder/web/src/lib/core/pkg/ builder/web/test-support/flat-device/pkg/ +builder/web/src/lib/trailview/plan/pkg/ # `obc` dev-task tooling (in tools/): personal defaults + the web builder's # virtualenv + the optional local maps drop. The tooling itself (everything in # tools/ except obc.local) is committed. @@ -80,13 +81,9 @@ builder/web/.env.local # mounts); the static-web host into builder/web/dist/web/. Both entries must keep matching vite.config.ts's outDirs: when they # drifted apart, `npm run build` wrote to an unignored path and 640 KB of bundle # got committed by accident (and the server mounted nothing). -builder/web/node_modules/ -builder/web/tests/browser/node_modules/ -builder/web/tests/device-smoke/node_modules/ -sim/web-demo/tests/browser/node_modules/ +node_modules/ builder/web/dist/ planner/tiles/dist/ -planner/tiles/node_modules/ planner/tiles/.wrangler/ builder/server/static/dist/ # The static tier's data files (#900): the Geofabrik index is ~1.7 MB of diff --git a/AGENTS.md b/AGENTS.md index a6c4d9869d..b894ea03a4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ and test them from their own directories. The nearest README has the surface's s ``` - Run a command that no task covers with `obc exec`: a raw shell lacks the tools of `obc.local`, - GEOS and the shared Cargo target. `obc suites prepare` installs the npm projects and the wasm + GEOS and the Cargo target of the checkout. `obc suites prepare` installs the npm projects and the wasm bridges of a new worktree; `obc test affected` installs the ones its suites need. - `obc test fixtures -p ` is for captured external data only. For a non-Rust surface, run diff --git a/Cargo.lock b/Cargo.lock index cc15dc520c..44103dfbb3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -151,6 +151,12 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + [[package]] name = "alsa" version = "0.11.0" @@ -2194,7 +2200,7 @@ dependencies = [ "float_next_after", "geo-types", "geographiclib-rs", - "i_overlay", + "i_overlay 4.0.7", "log", "num-traits", "robust", @@ -2491,6 +2497,8 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" dependencies = [ + "allocator-api2", + "equivalent", "foldhash 0.2.0", ] @@ -2709,22 +2717,49 @@ dependencies = [ "libm", ] +[[package]] +name = "i_float" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ecaff1ce29bcacd72cdf581ba6fce636ef4c4e0b2da7e7846dd0137d98141e2" +dependencies = [ + "libm", +] + [[package]] name = "i_key_sort" version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9190f86706ca38ac8add223b2aed8b1330002b5cdbbce28fb58b10914d38fc27" +[[package]] +name = "i_key_sort" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14269ee362009550495e20650ff3c2bca14a8147fe251e216760381ffed90b6f" + [[package]] name = "i_overlay" version = "4.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "413183068e6e0289e18d7d0a1f661b81546e6918d5453a44570b9ab30cbed1b3" dependencies = [ - "i_float", - "i_key_sort", - "i_shape", - "i_tree", + "i_float 1.15.0", + "i_key_sort 0.6.0", + "i_shape 1.14.0", + "i_tree 0.16.0", +] + +[[package]] +name = "i_overlay" +version = "9.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913fd692c02408adc76cead636f8e7e07c705f8b995a8b54b454b995e8e197d5" +dependencies = [ + "i_float 5.0.0", + "i_key_sort 0.12.0", + "i_shape 5.0.0", + "i_tree 0.20.0", ] [[package]] @@ -2733,7 +2768,16 @@ version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ea154b742f7d43dae2897fcd5ead86bc7b5eefcedd305a7ebf9f69d44d61082" dependencies = [ - "i_float", + "i_float 1.15.0", +] + +[[package]] +name = "i_shape" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa1878f91ef7921feaf1b2346253ebc5e661878b22d5715195c1d5dcf0f20ae5" +dependencies = [ + "i_float 5.0.0", ] [[package]] @@ -2742,6 +2786,12 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35e6d558e6d4c7b82bc51d9c771e7a927862a161a7d87bf2b0541450e0e20915" +[[package]] +name = "i_tree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048af31de955890c62a8506fec511335a5089e91e1c516537add16f96c507d84" + [[package]] name = "icu_collections" version = "2.2.0" @@ -3829,6 +3879,29 @@ dependencies = [ "obc-ports", ] +[[package]] +name = "obc-ground-plan" +version = "0.1.0" +dependencies = [ + "flate2", + "i_overlay 9.1.0", + "image", + "libm", + "serde_json", + "spade", + "tiny-skia", +] + +[[package]] +name = "obc-ground-plan-bridge" +version = "0.1.0" +dependencies = [ + "console_error_panic_hook", + "obc-ground-plan", + "serde_json", + "wasm-bindgen", +] + [[package]] name = "obc-host-core" version = "0.1.0" @@ -4170,6 +4243,7 @@ dependencies = [ "flate2", "image", "obc-data", + "obc-ground-plan", "rayon", "rstar", "rusqlite", @@ -5929,6 +6003,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spade" +version = "2.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9699399fd9349b00b184f5635b074f9ec93afffef30c853f8c875b32c0f8c7fa" +dependencies = [ + "hashbrown 0.16.1", + "num-traits", + "robust", + "smallvec", +] + [[package]] name = "spin" version = "0.9.9" diff --git a/Cargo.toml b/Cargo.toml index f452ccabab..e5229db09a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ members = [ "host/obc-mkimage", "host/obc-vectors", "host/obc-trailview-features", + "host/obc-ground-plan", "host/obc-tree-walk", "host/obcm-assemble", "host/obcm-testkit", @@ -59,6 +60,7 @@ members = [ # Product bridges. "planner/service", "builder/wasm", + "builder/ground-plan-wasm", ] # obc-fw-nrf54l is a standalone board crate (own target + .cargo/config.toml, own empty # [workspace]); it's built on its own, not as part of this host workspace (which builds its @@ -75,6 +77,7 @@ obc-elevation = { path = "firmware/obc-elevation" } obc-fixtures = { path = "host/obc-fixtures" } obc-flat-device = { path = "sim/flat-device" } obc-formats = { path = "firmware/obc-formats" } +obc-ground-plan = { path = "host/obc-ground-plan", default-features = false } obc-link = { path = "firmware/obc-link" } obc-map-scene = { path = "firmware/obc-map-scene" } obc-pack = { path = "host/obc-pack" } @@ -146,3 +149,11 @@ opt-level = 2 # Tool identities hash large compiler and sysroot files. [profile.dev.package.sha2] opt-level = 3 + +# The ground plan's fixture tests build and mesh every fixture cell. +[profile.dev.package.obc-ground-plan] +opt-level = 3 +[profile.dev.package.spade] +opt-level = 2 +[profile.dev.package.i_overlay] +opt-level = 2 diff --git a/builder/build-wasm-bridges.sh b/builder/build-wasm-bridges.sh index 3f74708cf1..ee92bcee69 100644 --- a/builder/build-wasm-bridges.sh +++ b/builder/build-wasm-bridges.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -repo_dir="$(cd "$(dirname "$0")/.." && pwd)" +repo_dir="$(cd "$(dirname "$0")/.." && pwd -P)" cd "$repo_dir" wasm-pack build builder/wasm --release --target web \ @@ -14,3 +14,8 @@ wasm-pack build builder/wasm --release --target web \ wasm-pack build builder/wasm --release --target web \ --out-dir ../web/test-support/flat-device/pkg \ --out-name obc_builder_bridge --features test-device + +# The TrailView ground plan: the cell build in the viewer's plan worker, the timing page and check 7. +wasm-pack build builder/ground-plan-wasm --release --target web \ + --out-dir ../web/src/lib/trailview/plan/pkg \ + --out-name obc_ground_plan_bridge diff --git a/builder/ground-plan-wasm/Cargo.toml b/builder/ground-plan-wasm/Cargo.toml new file mode 100644 index 0000000000..5c4e17b8f7 --- /dev/null +++ b/builder/ground-plan-wasm/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "obc-ground-plan-bridge" +version = "0.1.0" +edition = "2021" +publish = false +license = "GPL-3.0-only" +description = "The TrailView ground plan in the browser: the cell build of obc-ground-plan behind wasm-bindgen" + +[lib] +crate-type = ["cdylib", "rlib"] + +# The storeys over the ground (decks), which the viewer draws. Without it the package links none of their faces, +# records and shells. +[features] +default = ["storeys"] +storeys = ["obc-ground-plan/storeys"] + +[dependencies] +obc-ground-plan = { workspace = true } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +wasm-bindgen = { workspace = true } +console_error_panic_hook = { workspace = true } + +# The cell build time on a phone is the first risk of the ground plan; the file loads once and stays +# in the cache, so speed comes before size. +[package.metadata.wasm-pack.profile.release] +wasm-opt = ['-O3'] + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/builder/ground-plan-wasm/README.md b/builder/ground-plan-wasm/README.md new file mode 100644 index 0000000000..58f1049107 --- /dev/null +++ b/builder/ground-plan-wasm/README.md @@ -0,0 +1,75 @@ +# Ground plan bridge + +`obc-ground-plan-bridge`: the cell build of [`obc-ground-plan`](../../host/obc-ground-plan/README.md) +behind `wasm-bindgen`, for the TrailView plan worker and the timing page. The viewer loads it only +with `ground=plan` in the address. + +## Build and test + +```sh +obc exec bash builder/build-wasm-bridges.sh # all bridges; this one goes to builder/web/src/lib/trailview/plan/pkg +python3 builder/wasm/wasm_size_guard.py --module ground-plan +obc test -p obc-ground-plan-bridge +obc exec cargo clippy -p obc-ground-plan-bridge --all-targets -- -D warnings +obc exec cargo clippy -p obc-ground-plan-bridge --target wasm32-unknown-unknown -- -D warnings +``` + +The feature `storeys` (on) builds the storeys over the ground too: `MeshInput.storeys()` gives their meshes' +bytes and `CellPlan.storey_time()` their stages' milliseconds. Without it the package links none of it. + +## Check 7: native and WASM bytes + +```sh +obc exec bash builder/ground-plan-wasm/check-bytes.sh +``` + +It writes the requests of every fixture cell into a temporary folder, builds each in Node with +the package, and fails on a plan digest or a far block that differs from the native one; a refused +far block counts as `refused: …` on both sides. The native `requests` fails where a cell's far-only +build gives another far block than its full build, or its far block breaks the crate's check. + +| File | What it holds | +| --- | --- | +| `check.mjs DIR` | Builds each request of `DIR/index.json` in WASM; prints `cell digest native-ms wasm-ms` | +| `check-bytes.sh` | `requests --all --runs 1`, then `check.mjs` | + +## Timing page + +```sh +obc exec cargo run --release -p obc-ground-plan --example debug -- \ + requests --places v06,v12,v17,i07-hairpin,b45-bridge-junction --out .artifacts/ground-plan/requests +cd builder/web && obc exec npm run dev -- --host +``` + +The `requests` command prints the address. Open +`http://:5173/plan-timing.html?requests=/@fs//.artifacts/ground-plan/requests/`. + +| Parameter | Value | +| --- | --- | +| `requests` | The folder that holds `index.json` (required) | +| `runs` | Runs per cell after the cold run, 1 to 50 (default 5) | +| `cells` | `x-y` names, separated by commas (default: all) | + +On an iPhone: join the home Wi-Fi of the PC, open the address with the PC's LAN address as +`` in Safari, and wait for the summary line. The text area then holds the result as JSON; +select it to copy. The copy button works only in a secure context, such as `localhost`. + +| Column | What it holds | +| --- | --- | +| `first` | The first run of the cell; only the first row runs on a cold instance | +| `mean` | All later runs over their count; use it where the clock is coarse (Safari: 1 ms) | +| `prepare` | Gunzip and WebP decode of the cell's fixture files in the worker, with its tile cache | +| ` median`, `p95` | Per stage of the bridge, over the later runs | + +## Pitfalls + +- A `CellRequest` and a `CellPlan` hold WASM memory until `free()`. `build` and `far` take their + request: a `free()` after them throws. +- `far(request)` gives a cell's far block alone, without faces, records or rim: the + `CellPlan.far()` of a `build` of the same request. `CellPlan.far()` throws where the crate + refused the far block; the records and the rim of that plan are good. +- An instance keeps a few feature tiles parsed. A later request names such a tile (`name_tile`). + `missing()` lists the named tiles that the instance let go: give their bytes, or the build fails. +- `CellPlan.digest()` costs about as much as the build of the graph: the viewer asks for it only + with the debug draw. It fails on a NaN, whose text hides its bits. +- WASM memory never shrinks. The viewer starts a new worker when the heap passes its limit. diff --git a/builder/ground-plan-wasm/check-bytes.sh b/builder/ground-plan-wasm/check-bytes.sh new file mode 100755 index 0000000000..98a66505c1 --- /dev/null +++ b/builder/ground-plan-wasm/check-bytes.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Check 7: every fixture cell gives the same plan digest natively and in WASM. +# Needs the package of builder/build-wasm-bridges.sh. +set -euo pipefail + +repo_dir="$(cd "$(dirname "$0")/../.." && pwd -P)" +cd "$repo_dir" +# The requests of every fixture cell: about 320 cells at the largest request. +limit_mib=512 + +dir="$(mktemp -d)" +trap 'rm -rf "$dir"' EXIT +cargo run --locked --release -p obc-ground-plan --example debug -- requests --all --runs 1 --out "$dir" +size_mib=$(du -sm "$dir" | cut -f1) +echo "requests: ${size_mib} MiB" +if [ "$size_mib" -gt "$limit_mib" ]; then + echo "::error::the fixture's requests take ${size_mib} MiB, more than ${limit_mib} MiB" + exit 1 +fi +node builder/ground-plan-wasm/check.mjs "$dir" diff --git a/builder/ground-plan-wasm/check.mjs b/builder/ground-plan-wasm/check.mjs new file mode 100644 index 0000000000..9fe9cf68e4 --- /dev/null +++ b/builder/ground-plan-wasm/check.mjs @@ -0,0 +1,48 @@ +// Check 7: the WASM build gives the native digest and far block for every request of a `requests` folder. +// +// node builder/ground-plan-wasm/check.mjs DIR +// +// Prints `cell digest native-ms wasm-ms` per request; exits 1 on a different digest or far block, or an error. + +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { build_bytes, initSync } from '../web/src/lib/trailview/plan/pkg/obc_ground_plan_bridge.js'; + +const dir = process.argv[2]; +if (!dir) throw new Error('usage: node check.mjs DIR'); +initSync({ module: readFileSync(new URL('../web/src/lib/trailview/plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url)) }); +const index = JSON.parse(readFileSync(join(dir, 'index.json'), 'utf8')); +/** The FNV-1a hex of words' little-endian bytes, as `transport::fnv` of the crate. */ +const fnv = words => { + let h = 0xcbf29ce484222325n; + for (const b of new Uint8Array(words.buffer, words.byteOffset, words.byteLength)) h = BigInt.asUintN(64, (h ^ BigInt(b)) * 0x100000001b3n); + return h.toString(16).padStart(16, '0'); +}; +/** A plan's far block as `requests` writes it: its FNV, or the crate's refusal. */ +const farOf = plan => { + try { + return fnv(plan.far()); + } catch (error) { + return `refused: ${error instanceof Error ? error.message : error}`; + } +}; +let failed = 0; +for (const entry of index) { + const name = entry.cell.join('-'); + try { + const start = performance.now(); + const plan = build_bytes(readFileSync(join(dir, entry.file))); + const ms = performance.now() - start; + const digest = plan.digest(), far = farOf(plan); + plan.free(); + const same = digest === entry.digest && far === entry.far; + if (!same) failed++; + const differ = digest === entry.digest ? ` far ${far} != native ${entry.far}` : ` != native ${entry.digest}`; + console.log(`${name} ${digest}${same ? '' : differ} ${entry.native.total.toFixed(2)} ${ms.toFixed(2)}`); + } catch (error) { + failed++; + console.log(`${name} error: ${error instanceof Error ? error.message : error}`); + } +} +console.log(`${index.length - failed} of ${index.length} cells give the native digest and far block`); +process.exit(failed ? 1 : 0); diff --git a/builder/ground-plan-wasm/src/lib.rs b/builder/ground-plan-wasm/src/lib.rs new file mode 100644 index 0000000000..082f004261 --- /dev/null +++ b/builder/ground-plan-wasm/src/lib.rs @@ -0,0 +1,436 @@ +//! The TrailView ground plan in the browser: the request codec and the cell build of `obc-ground-plan` +//! behind `wasm-bindgen`. The same functions build natively, so the tests run them without a browser. +//! +//! wasm-bindgen objects hold WASM memory until `free()`: a caller frees each `CellRequest`, +//! `CellPlan` and `MeshInput`. + +use std::cell::{OnceCell, RefCell}; + +use obc_ground_plan::cell::{build_cell, build_request, build_storeys, far_request, CellBuild}; +use obc_ground_plan::faces::{FacePlan, Rules}; +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::mesh::{mesh_cell, Reads, Rim}; +use obc_ground_plan::terrain::{StoredPage, PAGE}; +use obc_ground_plan::tile::TileCache; +use obc_ground_plan::transport::{self, fnv, FeatureTile, Flat, Request}; + +#[cfg(target_arch = "wasm32")] +use wasm_bindgen::prelude::*; + +#[cfg(target_arch = "wasm32")] +pub type Error = JsError; +#[cfg(not(target_arch = "wasm32"))] +pub type Error = String; + +#[cfg(target_arch = "wasm32")] +fn error(text: String) -> Error { + JsError::new(&text) +} +#[cfg(not(target_arch = "wasm32"))] +fn error(text: String) -> Error { + text +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen] +extern "C" { + /// Workers and Node both have `performance`. + #[wasm_bindgen(js_namespace = performance)] + fn now() -> f64; +} +#[cfg(not(target_arch = "wasm32"))] +fn now() -> f64 { + use std::sync::OnceLock; + use std::time::Instant; + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_secs_f64() * 1e3 +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen(start)] +pub fn start() { + console_error_panic_hook::set_once(); +} + +/// The names and colours of the codes of a `CellPlan`, and its stages, as JSON. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub fn vocabulary() -> String { + transport::vocabulary() +} + +/// The pages that cell (x, y) of zoom 16 reads, `words.wanted` of the vocabulary per page: level, +/// page x, page y, then the stored tile that holds it (z, x, y) and its quadrant. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub fn wanted(x: u32, y: u32) -> Vec { + transport::wanted_words(CellKey { x, y }) +} + +/// The zoom-13 feature tiles that cell (x, y) of zoom 16 reads, as column, row pairs: one to four. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub fn feature_tiles(x: u32, y: u32) -> Vec { + CellKey { x, y }.feature_tiles().into_iter().flat_map(|(column, row)| [column, row]).collect() +} + +/// The inputs of one cell as a caller collects them, in any order. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub struct CellRequest { + request: Request, + /// The feature tiles that exist and that the instance holds parsed, without their bytes. + named: Vec<(u32, u32)>, +} + +/// The named tiles that `tiles` does not hold; each held one counts as used now. +fn unheld(named: &[(u32, u32)], tiles: &mut TileCache) -> Vec<(u32, u32)> { + named.iter().copied().filter(|&(column, row)| !tiles.touch(column, row)).collect() +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +impl CellRequest { + #[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))] + pub fn new(x: u32, y: u32) -> CellRequest { + CellRequest { + request: Request { key: CellKey { x, y }, tiles: Vec::new(), pages: Vec::new() }, + named: Vec::new(), + } + } + + /// The plain bytes (after gzip) of zoom-13 feature tile (column, row). The build parses them once + /// per instance; later requests can name the tile. + pub fn add_tile(&mut self, column: u32, row: u32, bytes: Vec) { + self.request.tiles.push(FeatureTile { column, row, bytes }); + } + + /// Zoom-13 feature tile (column, row), which exists and whose bytes an earlier request of this + /// instance held. + pub fn name_tile(&mut self, column: u32, row: u32) { + self.named.push((column, row)); + } + + /// A stored page: 65,536 codes, row by row from north; a height is `offset + code × scale`. + pub fn add_page( + &mut self, + level: u8, + x: u32, + y: u32, + offset: f32, + scale: f32, + codes: Vec, + ) -> Result<(), Error> { + if codes.len() != PAGE * PAGE { + return Err(error(format!("page {level}/{x}/{y} has {} codes, not {}", codes.len(), PAGE * PAGE))); + } + self.request.pages.push(StoredPage { level, x, y, offset, scale, codes }); + Ok(()) + } + + /// The named tiles that the instance no longer holds, as column, row pairs: the caller gives + /// their bytes. A build right after an empty answer finds every named tile. + pub fn missing(&self) -> Vec { + PARSED + .with_borrow_mut(|tiles| unheld(&self.named, tiles)) + .into_iter() + .flat_map(|(column, row)| [column, row]) + .collect() + } + + /// The canonical request bytes; an error where a tile is only named. + pub fn to_bytes(&self) -> Result, Error> { + match self.named.first() { + Some((column, row)) => Err(error(format!("tile 13/{column}/{row} is named without its bytes"))), + None => Ok(self.request.encode()), + } + } +} + +/// A built cell: the flat plan, its stats and digest, and the time of each stage. The flat plan is made at the +/// first call that reads it: the records' builds read only the rim and the mesh input. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub struct CellPlan { + flat: OnceCell, + built: CellBuild, +} + +impl CellPlan { + fn flat(&self) -> &Flat { + self.flat.get_or_init(|| Flat::of(&self.built)) + } +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +impl CellPlan { + pub fn samples(&self) -> Vec { + self.flat().samples.clone() + } + + pub fn ways(&self) -> Vec { + self.flat().ways.clone() + } + + pub fn points(&self) -> Vec { + self.flat().points.clone() + } + + pub fn crossings(&self) -> Vec { + self.flat().crossings.clone() + } + + /// The faces of level 0: x, y per vertex. + pub fn vertices(&self) -> Vec { + self.flat().faces.vertices.clone() + } + + /// `words.face` of the vocabulary per face. + pub fn faces(&self) -> Vec { + self.flat().faces.faces.clone() + } + + /// `words.ring` per ring: first index into `ring_vertices`, count; a face's first ring is its outer ring. + pub fn rings(&self) -> Vec { + self.flat().faces.rings.clone() + } + + pub fn ring_vertices(&self) -> Vec { + self.flat().faces.ring_vertices.clone() + } + + /// `words.edge` per edge. + pub fn edges(&self) -> Vec { + self.flat().faces.edges.clone() + } + + pub fn stats(&self) -> String { + self.flat().stats.clone() + } + + /// Milliseconds per stage, in the order of the vocabulary's `stages`. + pub fn times(&self) -> Vec { + self.built.times.clone() + } + + /// The digest of the plan, or an error where it holds a NaN: it costs about as much as the build of the graph. + pub fn digest(&self) -> Result { + self.flat().digest(&self.built).map_err(error) + } + + /// What the neighbours' meshes read of this cell: `Rim::to_words`. + pub fn rim(&self) -> Vec { + Rim::of(&self.built.faces).to_words() + } + + /// What the cell's mesh reads, kept apart so the plan can go while the mesh waits for its + /// neighbours' rims. + pub fn mesh_input(&self) -> MeshInput { + MeshInput { + plan: self.built.faces.clone(), + records: self.built.records.clone(), + last: None, + #[cfg(feature = "storeys")] + storeys: self.built.storeys.clone(), + } + } + + /// The milliseconds of the storeys' faces and records. + #[cfg(feature = "storeys")] + pub fn storey_time(&self) -> f64 { + self.built.storey_time + } + + /// The far block of the records' lines (`records::far` of obc-ground-plan), or why the crate + /// refused it: the records stand either way. + pub fn far(&self) -> Result, Error> { + self.built.far.clone().map_err(error) + } +} + +/// A cell's faces and near records, for its mesh. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub struct MeshInput { + plan: FacePlan, + records: Vec, + /// What the last mesh read of the rims. + last: Option, + #[cfg(feature = "storeys")] + storeys: obc_ground_plan::faces::Storeys, +} + +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +impl MeshInput { + /// The near records: the block whose labels the mesh's corners name, for the GPU. + pub fn records(&self) -> Vec { + self.records.clone() + } + + /// The bytes of the cell's near mesh (`CellMesh::to_bytes`) from the rims of the cell and its eight + /// neighbours, one after another in any order; a missing neighbour counts as one with no sharp + /// face. None when the mesh reads the same of them as the last call did (that call's mesh or error + /// stands), so a caller may call it at every change of a rim. + pub fn mesh(&mut self, rims: &[u32]) -> Result>, Error> { + let rims = Rim::from_words(rims).map_err(error)?; + let reads = Reads::of(&self.plan, &rims); + if self.last.as_ref() == Some(&reads) { + return Ok(None); + } + let mesh = mesh_cell(&self.plan, &self.records, &reads, &mut now); + self.last = Some(reads); + Ok(Some(mesh.map_err(|e| error(format!("{e:?}")))?.to_bytes())) + } + + /// The bytes of the meshes of the cell's storeys over the ground (`StoreyMesh::to_bytes`). + #[cfg(feature = "storeys")] + pub fn storeys(&self) -> Result, Error> { + let rules = Rules::embedded(); + obc_ground_plan::mesh::shell::mesh_storeys(self.plan.cell, &self.storeys, &self.records, &rules.structures) + .map(|m| m.to_bytes()) + .map_err(|e| error(format!("{e:?}"))) + } +} + +/// The zoom-13 tiles that an instance keeps parsed: a worker builds the cells about the eye, which +/// share their tiles. A town tile takes about 2 MB of the heap. +const TILES: usize = 6; +// A cell reads up to 4 tiles, and `build` marks its named tiles used first: the build's own parses +// then never let one of them go. +const _: () = assert!(TILES >= 4); + +thread_local! { + static PARSED: RefCell = RefCell::new(TileCache::new(TILES)); +} + +/// `f` of a request's inputs with the instance's parsed tiles, once it holds every named tile: a named +/// tile that is not held would build as an absent one. +fn held(request: CellRequest, f: impl FnOnce(Request, &mut TileCache) -> Result) -> Result { + let CellRequest { request, named } = request; + PARSED + .with_borrow_mut(|tiles| match unheld(&named, tiles).first() { + Some((column, row)) => Err(format!("tile 13/{column}/{row} is named, and the instance no longer holds it")), + None => f(request, tiles), + }) + .map_err(error) +} + +/// Builds a cell from a request and takes its inputs; the request meets the checks of `build_bytes`. +/// Each tile parses once per instance, so an instance serves one feature archive. With `digest` the +/// stats hold the digest of the canonical bytes, as `build_bytes` gives it, and no tile is only named. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub fn build(request: CellRequest, digest: bool) -> Result { + let digest = if digest { Some(fnv(&request.to_bytes()?)) } else { None }; + let named = request.named.len(); + let mut built = held(request, build_of)?; + built.request = digest; + built.tiles += named; + Ok(CellPlan { flat: OnceCell::new(), built }) +} + +/// The far block of a request's cell alone (`cell::far_request`), the `far` of its `build`; it takes +/// the request as `build` does. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub fn far(request: CellRequest) -> Result, Error> { + held(request, |inputs, tiles| far_request(inputs, tiles, Rules::embedded())) +} + +/// Builds a cell from canonical request bytes, with the embedded rule tables. +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub fn build_bytes(bytes: &[u8]) -> Result { + let built = if cfg!(feature = "storeys") { + let built = Request::decode(bytes).and_then(|r| build_of(r, &mut TileCache::new(4))); + built.map(|b| CellBuild { request: Some(fnv(bytes)), ..b }) + } else { + build_cell(bytes, Rules::embedded(), &mut now) + }; + Ok(CellPlan { flat: OnceCell::new(), built: built.map_err(error)? }) +} + +/// The cell build of a request: with the feature `storeys`, its storeys over the ground too. +fn build_of(request: Request, tiles: &mut TileCache) -> Result { + let build = if cfg!(feature = "storeys") { build_storeys } else { build_request }; + build(request, tiles, Rules::embedded(), &mut now) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn features() -> Vec { + std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../../specs/vectors/trailview-features.bin")).unwrap() + } + + /// The north-west cell of zoom-13 tile 4286/2888, the tile of the vector: its roads with heights lie there. + const CELL: (u32, u32) = (4286 * 8, 2888 * 8); + + #[test] + fn wanted_names_pages_of_levels_13_and_14_with_their_stored_tiles() { + let words = wanted(CELL.0, CELL.1); + assert!(!words.is_empty() && words.len().is_multiple_of(transport::WANTED_WORDS)); + for page in words.chunks(transport::WANTED_WORDS) { + assert!(page[0] == 13 || page[0] == 14, "{page:?}"); + assert_eq!(page[3..6], [page[0] - 1, page[1] >> 1, page[2] >> 1]); + } + } + + #[test] + fn a_request_in_any_order_gives_one_plan_and_one_far_block() { + // Flat ground at 500 m on every wanted page, added in two orders. + let pages: Vec<[u32; transport::WANTED_WORDS]> = + wanted(CELL.0, CELL.1).chunks(transport::WANTED_WORDS).map(|p| p.try_into().unwrap()).collect(); + let request = |pages: &mut dyn Iterator| { + let mut request = CellRequest::new(CELL.0, CELL.1); + for p in pages { + request.add_page(p[0] as u8, p[1], p[2], 500.0, 0.01, vec![0; 256 * 256]).unwrap(); + } + request + }; + let (mut a, mut b) = (request(&mut pages.iter()), request(&mut pages.iter().rev())); + a.add_tile(4286, 2888, features()); + b.add_tile(4286, 2888, features()); + let bytes = b.to_bytes().unwrap(); + assert_eq!(a.to_bytes().unwrap(), bytes); + let plan = build(a, true).unwrap(); + let stats: serde_json::Value = serde_json::from_str(&plan.stats()).unwrap(); + assert_eq!(stats["inputs"]["pages"].as_u64(), Some(pages.len() as u64)); + assert_eq!(stats["inputs"]["tiles"].as_u64(), Some(1)); + assert!(!plan.ways().is_empty(), "{stats}"); + let samples = plan.samples().len() as u32 / 2; + for way in plan.ways().chunks(transport::WAY_WORDS) { + assert!(way[4] + way[5] <= samples, "a way's samples lie inside the samples"); + } + let vertices = plan.vertices().len() as u32 / 2; + let (rings, ring_vertices) = (plan.rings(), plan.ring_vertices()); + assert!(!plan.faces().is_empty() && ring_vertices.iter().all(|&v| v < vertices)); + for ring in rings.chunks(transport::RING_WORDS) { + assert!(ring[0] + ring[1] <= ring_vertices.len() as u32); + } + assert!(plan.edges().chunks(transport::EDGE_WORDS).all(|e| e[0] < vertices && e[1] < vertices)); + assert_eq!(plan.times().len(), obc_ground_plan::cell::STAGES.len()); + assert_eq!(build_bytes(&bytes).unwrap().digest(), plan.digest()); + assert!(build_bytes(&bytes[..40]).is_err()); + let mut input = plan.mesh_input(); + let mesh = input.mesh(&plan.rim()).unwrap().unwrap(); + assert_eq!(u32::from_le_bytes(mesh[..4].try_into().unwrap()), obc_ground_plan::mesh::MAGIC); + assert_eq!(input.mesh(&plan.rim()).unwrap(), None); + // The instance holds the tile now: a request that names it builds the same records, rim and mesh. + let mut named = request(&mut pages.iter()); + named.name_tile(4286, 2888); + assert!(named.missing().is_empty() && named.to_bytes().is_err()); + let again = build(named, false).unwrap(); + assert_eq!((again.mesh_input().records(), again.rim()), (input.records(), plan.rim())); + assert_eq!(again.mesh_input().mesh(&plan.rim()).unwrap().unwrap(), mesh); + // A full build, one from the bytes, a far-only build and one by the named tile give one far block. + let block = plan.far().unwrap(); + assert!(block[3] > 0, "the cell's roads reach it"); + assert_eq!((again.far().unwrap(), build_bytes(&bytes).unwrap().far().unwrap()), (block.clone(), block.clone())); + let mut alone = request(&mut pages.iter()); + alone.add_tile(4286, 2888, features()); + let mut named = request(&mut pages.iter()); + named.name_tile(4286, 2888); + assert_eq!((far(alone).unwrap(), far(named).unwrap()), (block.clone(), block)); + // A tile never given is missing, and the builds refuse it instead of building without it. + let unknown = || { + let mut r = request(&mut pages.iter()); + r.name_tile(4286, 2887); + r + }; + assert_eq!(unknown().missing(), [4286, 2887]); + assert!(build(unknown(), false).is_err() && far(unknown()).is_err()); + assert!(CellRequest::new(CELL.0, CELL.1).add_page(14, 0, 0, 0.0, 1.0, vec![0; 100]).is_err()); + } +} diff --git a/builder/wasm/wasm_size_guard.py b/builder/wasm/wasm_size_guard.py index 4f07717e0c..0ddbb8bd40 100644 --- a/builder/wasm/wasm_size_guard.py +++ b/builder/wasm/wasm_size_guard.py @@ -1,12 +1,13 @@ #!/usr/bin/env python3 -"""Gate the production builder core on raw WASM and gzipped WASM plus glue. +"""Gate each production wasm bridge on raw WASM and gzipped WASM plus glue. The test-device variant is measured but does not ship. Raising a cap needs a reason in the PR. +The ground-plan budget is its recorded CI size plus the owner's margin; both parts print. """ from __future__ import annotations -GOVERNS = ['builder/wasm/**', 'host/obcm-assemble/**'] +GOVERNS = ['builder/wasm/**', 'host/obcm-assemble/**', 'builder/ground-plan-wasm/**', 'host/obc-ground-plan/**'] RULE = 'A wasm bridge stays inside its recorded gzip and raw size budgets.' import argparse @@ -15,22 +16,44 @@ from pathlib import Path -# Preserve the sum of the conversion, assembly and preview caps. Consolidation does not -# increase the permitted production download or raw WASM size. +# Measured in CI on the build with the outline's turns, the levels that the tiles carry, the faces' tile-line +# vertices, the decks' ceilings and end faces, the shared water level and curve of the feature bake, line water +# and its culverts with their mouths, the classifier's ford rule, and the storeys over the ground with their open +# junction ends, their ends on the stubs' points, what each deck is made of, the junctions that lie on the +# ground, and a building passage of an older bake on the ground (the crate's feature `storeys` on, stable 1.100.0). +# The owner allows about 60 kB of code growth for the crossing block, stated in its pull request and recorded here. +GROUND_PLAN_MEASURED = {"gzipped": 808_099, "raw_wasm": 2_090_936} +# The owner's margin: compiler and dependency updates move the size by a few kilobytes and must not fail +# unrelated pull requests; real growth past the margin still fails. Raw gets the same fraction as gzipped. +# A pull request that changes the bridge's code records its own CI size here; the margin is only for toolchain +# and dependency noise. +GROUND_PLAN_MARGIN_GZIPPED = 8 * 1024 +GROUND_PLAN_MARGIN = { + "gzipped": GROUND_PLAN_MARGIN_GZIPPED, + "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * GROUND_PLAN_MEASURED["raw_wasm"] / GROUND_PLAN_MEASURED["gzipped"]), +} + BUDGETS = { + # Preserve the sum of the conversion, assembly and preview caps. Consolidation does not + # increase the permitted production download or raw WASM size. "builder": {"gzipped": (62 + 352 + 128) * 1024, "raw_wasm": (112 + 944 + 272) * 1024}, + "ground-plan": {key: GROUND_PLAN_MEASURED[key] + GROUND_PLAN_MARGIN[key] for key in GROUND_PLAN_MEASURED}, } +# A budget made of a measured size and a margin prints both, so a reviewer sees growth inside the margin. +BUDGET_PARTS = {"ground-plan": (GROUND_PLAN_MEASURED, GROUND_PLAN_MARGIN)} ADVICE = { "builder": ( "Check the production dependency graph with cargo tree -p obc-builder-bridge" " --target wasm32-unknown-unknown. GEOS, obc-pack and the test device must stay out." ), + "ground-plan": "Check the dependency graph with cargo tree -p obc-ground-plan-bridge --target wasm32-unknown-unknown.", } PKG_DIRS = { "builder": Path("builder/web/src/lib/core/pkg"), "flat-device": Path("builder/web/test-support/flat-device/pkg"), + "ground-plan": Path("builder/web/src/lib/trailview/plan/pkg"), } UNBUDGETED = {"flat-device"} @@ -91,13 +114,21 @@ def main() -> int: failed = False budgets = BUDGETS[args.module] - for label, measured, budget in ( - ("gzipped wasm + glue", total_gzipped, budgets["gzipped"]), - ("raw wasm", raw_wasm, budgets["raw_wasm"]), + parts = BUDGET_PARTS.get(args.module) + for key, label, measured in ( + ("gzipped", "gzipped wasm + glue", total_gzipped), + ("raw_wasm", "raw wasm", raw_wasm), ): + budget = budgets[key] pct = 100 * measured / budget status = "over" if measured > budget else "ok" print(f"{label}: {measured:,} B / {budget:,} B budget ({pct:.0f}%) — {status}") + if parts: + recorded, margin = parts + print( + f" budget = {recorded[key]:,} B recorded + {margin[key]:,} B margin;" + f" {measured - recorded[key]:+,} B against the recorded size" + ) if measured > budget: print( f"::error::obc-{args.module}-bridge {label} is {measured:,} B, over the {budget:,} B budget." diff --git a/builder/web/plan-timing.html b/builder/web/plan-timing.html new file mode 100644 index 0000000000..750e9099c7 --- /dev/null +++ b/builder/web/plan-timing.html @@ -0,0 +1,26 @@ + + + + + + OpenBikeComputer · ground plan timing + + + +
Loading…
+
+

+        
+        
+        
+    
+
diff --git a/builder/web/scripts/check-wgsl.mjs b/builder/web/scripts/check-wgsl.mjs
index d3bc794a90..3298fd6039 100644
--- a/builder/web/scripts/check-wgsl.mjs
+++ b/builder/web/scripts/check-wgsl.mjs
@@ -1,22 +1,29 @@
-// Validates every WGSL file of TrailView with naga, composed with its includes as the engine does it.
+// Validates every WGSL file of TrailView with naga, composed with its includes, and the declarations that the
+// entry points of a file reach, as the engine makes its modules.
 //
 //   npm run check:wgsl          # cargo install naga-cli --version 30.0.1 --locked
 import { execFileSync } from 'node:child_process';
 import { readdirSync, readFileSync } from 'node:fs';
-import { CLIP_DISTANCES, include } from '../src/lib/trailview/gpu/include.ts';
+import { CLIP_DISTANCES, include, MOUTH, reached } from '../src/lib/trailview/gpu/include.ts';
 
 const root = new URL('../src/lib/trailview/', import.meta.url).pathname;
 const files = readdirSync(root, { recursive: true }).filter(file => file.endsWith('.wgsl')).sort();
 let failed = 0;
 const check = (file, swap = {}) => {
-    process.stdout.write(`${file}${swap === CLIP_DISTANCES ? ' with clip distances' : ''}: `);
-    try {
-        execFileSync('naga', ['--stdin-file-path', file], { input: include(file, path => readFileSync(root + (swap[path] ?? path), 'utf8')), stdio: ['pipe', 'inherit', 'inherit'] });
-    } catch {
-        failed++;
+    const composed = include(file, path => readFileSync(root + (swap[path] ?? path), 'utf8')), name = `${file}${swap === CLIP_DISTANCES ? ' with clip distances' : swap === MOUTH ? ' with the mouth' : ''}`;
+    for (const [label, input] of [[name, composed], ...(/@(vertex|fragment|compute)\b/.test(composed) ? [[`${name}, reached`, reached(composed)]] : [])]) {
+        process.stdout.write(`${label}: `);
+        try {
+            execFileSync('naga', ['--stdin-file-path', file], { input, stdio: ['pipe', 'inherit', 'inherit'] });
+        } catch {
+            failed++;
+        }
     }
 };
-files.forEach(file => check(file));
+// A file that takes another's place checks in the composition that swaps it in.
+const swapped = new Set(Object.values(MOUTH));
+files.filter(file => !swapped.has(file)).forEach(file => check(file));
+check('plan/piece.wgsl', MOUTH);
 check('terrain/terrain.wgsl', CLIP_DISTANCES);
 check('terrain/water.wgsl', CLIP_DISTANCES);
 process.exit(failed ? 1 : 0);
diff --git a/builder/web/scripts/road-census.ts b/builder/web/scripts/road-census.ts
index fd16788880..d323829203 100644
--- a/builder/web/scripts/road-census.ts
+++ b/builder/web/scripts/road-census.ts
@@ -1,6 +1,7 @@
 // The CPU half of the TrailView fault census: prints the counts of gaps, objects on ways, short sidewalks and
 // torn faces over the fixture, one JSON line each, the worst places of each kind of torn face with a view
-// link, and writes the face and the water samples that census.mjs probes.
+// link, and writes the face and the water samples that census.mjs probes. It exits with an error when a
+// count is over its gate or the torn faces differ from census-baseline.json.
 //
 //   npx vite-node scripts/road-census.ts DIR    # writes DIR/faces.bin and DIR/water.bin, float64 rows
 import { mkdirSync, writeFileSync } from 'node:fs';
@@ -9,7 +10,10 @@ import { latitudeAt } from '../src/lib/planner/layers/mercator';
 import { UNITS } from '../src/lib/trailview/frame/space';
 import { metresPerUnit } from '../src/lib/trailview/terrain/bins';
 import { countLine, faceSamples, fixtureTiles, gaps, objectsOnWays, placeOf, shortSidewalks, tornFaces, waterSamples } from '../test-support/trailview/census';
+import baseline from '../test-support/trailview/census-baseline.json' with { type: 'json' };
 
+/** The gates of the counts on the fixture. A face of no area covers no gap sample; most short sidewalks are beside tight bends. */
+const GATES = { gaps: 20600, 'objects-on-ways': 0, 'short-sidewalks': 119 };
 /** Worst places printed per kind of torn face. */
 const WORST = 20;
 /** The view of a place: from this many metres south and up, looking north and down on it. */
@@ -20,10 +24,19 @@ if (!out) throw new Error('usage: npx vite-node scripts/road-census.ts DIR');
 const start = performance.now(), tiles = fixtureTiles();
 mkdirSync(out, { recursive: true });
 for (const [name, rows] of [['faces', faceSamples(tiles)], ['water', waterSamples(tiles)]] as const) writeFileSync(join(out, `${name}.bin`), rows);
-console.log(countLine('gaps', gaps(tiles)));
-console.log(countLine('objects-on-ways', objectsOnWays(tiles)));
-console.log(countLine('short-sidewalks', shortSidewalks(tiles)));
-for (const [kind, points] of Object.entries(tornFaces(tiles.flatMap(({ meshes }) => meshes.flatMap(({ pieces }) => pieces))))) {
+const faults: string[] = [];
+for (const [count, points] of [['gaps', gaps(tiles)], ['objects-on-ways', objectsOnWays(tiles)], ['short-sidewalks', shortSidewalks(tiles)]] as const) {
+    console.log(countLine(count, points));
+    if (points.length / 2 > GATES[count]) faults.push(`${count}: ${points.length / 2} samples, the gate is ${GATES[count]}`);
+}
+const torn = tornFaces(tiles.flatMap(({ meshes }) => meshes.flatMap(({ pieces }) => pieces)));
+for (const kind of Object.keys(torn)) if (!(kind in baseline)) faults.push(`torn-${kind}: not in census-baseline.json`);
+for (const [kind, most] of Object.entries(baseline)) {
+    const count = (torn[kind as keyof typeof torn]?.length ?? 0) / 2;
+    // A lower count lowers the baseline in the same commit, so that it cannot hide a new torn face.
+    if (count !== most) faults.push(`torn-${kind}: ${count}, census-baseline.json holds ${most}: ${count > most ? 'fix the faces, do not raise the baseline' : 'lower the baseline'}`);
+}
+for (const [kind, points] of Object.entries(torn)) {
     console.log(countLine(`torn-${kind}`, points));
     const seen = new Set();
     for (let i = 0; i < points.length && seen.size < WORST; i += 2) {
@@ -35,3 +48,5 @@ for (const [kind, points] of Object.entries(tornFaces(tiles.flatMap(({ meshes })
     }
 }
 console.error(`${((performance.now() - start) / 1000).toFixed(0)} s`);
+for (const fault of faults) console.error(fault);
+if (faults.length) process.exitCode = 1;
diff --git a/builder/web/scripts/trailview-stamps.mjs b/builder/web/scripts/trailview-stamps.mjs
new file mode 100644
index 0000000000..38c532ac13
--- /dev/null
+++ b/builder/web/scripts/trailview-stamps.mjs
@@ -0,0 +1,62 @@
+// The stamp process of the `obc data` step `planner/trailview-stamps` (host/obc-trailview-features/src/stamps.rs).
+// All numbers are little-endian. It writes the stamp version first: a u32 length and its UTF-8. Then it reads
+// feature tiles until standard input ends, each a u8 zoom, u32 x, u32 y, u32 length and the tile body, and writes
+// for each the u32 count of its baked nodes, each a u8 level, u32 x, u32 y, u32 length and the node bytes.
+//
+//   node builder/web/scripts/trailview-stamps.mjs < tiles > nodes
+
+// The bundle module is TypeScript, which Node runs from 22.18 on.
+const [major, minor] = process.versions.node.split('.').map(Number);
+if (major < 22 || (major === 22 && minor < 18)) {
+    console.error(`trailview-stamps: Node ${process.versions.node} runs no TypeScript module; it needs 22.18 or newer`);
+    process.exit(1);
+}
+const { stampBundle } = await import('../vite/stamp-bundle.ts').catch(error => {
+    console.error(`trailview-stamps: ${error.message}; run \`npm ci --prefix builder/web\` first`);
+    process.exit(1);
+});
+const { code, version } = await stampBundle();
+// The stamp worker sets `self.onmessage`. Standard output holds the frames, so the stamp code logs to standard error.
+globalThis.self = globalThis;
+console.log = console.info = console.debug = console.error;
+const { bakeTile } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
+
+const write = chunk => new Promise((resolve, reject) => process.stdout.write(chunk, error => (error ? reject(error) : resolve())));
+const u32 = value => {
+    const out = Buffer.alloc(4);
+    out.writeUInt32LE(value);
+    return out;
+};
+const place = (z, x, y, length) => {
+    const out = Buffer.alloc(13);
+    out.writeUInt8(z, 0);
+    out.writeUInt32LE(x, 1);
+    out.writeUInt32LE(y, 5);
+    out.writeUInt32LE(length, 9);
+    return out;
+};
+
+/** The next `n` bytes of standard input; null at its end where `last` allows it. */
+const input = process.stdin[Symbol.asyncIterator]();
+let held = Buffer.alloc(0);
+async function read(n, last = false) {
+    while (held.length < n) {
+        const { value, done } = await input.next();
+        if (done) {
+            if (last && !held.length) return null;
+            throw new Error(`standard input ends inside a tile: ${held.length} of ${n} bytes`);
+        }
+        held = Buffer.concat([held, value]);
+    }
+    const out = held.subarray(0, n);
+    held = held.subarray(n);
+    return out;
+}
+
+await write(Buffer.concat([u32(Buffer.byteLength(version)), Buffer.from(version)]));
+for (let head; (head = await read(13, true)); ) {
+    const tile = { level: head.readUInt8(0), x: head.readUInt32LE(1), y: head.readUInt32LE(5) };
+    const body = await read(head.readUInt32LE(9));
+    const nodes = await bakeTile(tile, body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength));
+    await write(Buffer.concat([u32(nodes.length), ...nodes.flatMap(([node, bytes]) => [place(node.level, node.x, node.y, bytes.byteLength), bytes])]));
+}
diff --git a/builder/web/src/lib/covers/job.test.ts b/builder/web/src/lib/covers/job.test.ts
index d55a8dad8e..ed8f3c79bf 100644
--- a/builder/web/src/lib/covers/job.test.ts
+++ b/builder/web/src/lib/covers/job.test.ts
@@ -26,7 +26,7 @@ function fake() {
     let open = false;
     const renderer: Renderer = {
         canRender: async () => true,
-        view: async (_, when) => ({ lat: 46.8, lon: 8.4, heading: 0, pitch: -30, mode: 'fly', height: 3000, debug: 'off', ...when }),
+        view: async (_, when) => ({ lat: 46.8, lon: 8.4, heading: 0, pitch: -30, mode: 'fly', height: 3000, debug: 'off', plan: 'off', ...when }),
         still: (job, signal) => new Promise((resolve, reject) => {
             stills.push({ job, resolve, reject });
             signal.addEventListener('abort', () => reject(failure('aborted')));
diff --git a/builder/web/src/lib/trailview/README.md b/builder/web/src/lib/trailview/README.md
index 1de1270e0b..2b91bc2051 100644
--- a/builder/web/src/lib/trailview/README.md
+++ b/builder/web/src/lib/trailview/README.md
@@ -43,6 +43,7 @@ the palette of the `world` region.
 | `dressing/` | The herds of the packs on the materials that they graze, and rocks on rough and rocky ground, placed each frame (`dressing.wgsl`); the rocks' density and placement, which the ground also paints past their instances (`rocks.wgsl`) |
 | `light/` | The light keys and weather presets, the look at the eye, `shade.wgsl` (toon bands, haze, `finish()`), the sky with the moon, the stars and the Milky Way, and a solar eclipse where the moon covers the sun (`celestial.ts`, `eclipse.ts`, `night.ts`; `tools/trailview/sky.py` makes `milkyway.webp`, `stars.bin` and `moon.webp`), the object shadow maps near and far from the eye (`shadow.ts`) |
 | `resolve/` | The render targets, the jitter, TAA and `finish()` |
+| `plan/` | The ground plan with `ground=plan`: the cells about the eye and their inputs (`plan.ts`, `inputs.ts`), the build in the bridge of [`builder/ground-plan-wasm`](../../../../ground-plan-wasm/README.md), one copy per page (`bridge.ts`, `plan-worker.ts`, `pkg/`), the debug draw over the canvas (`debug.ts`, `draw.ts`, `debug.wgsl`) |
 | `rules/` | The regions of `rules.json`, resolved |
 | `view.ts` | The view in the address |
 | `hud.ts` | The HUD |
@@ -59,6 +60,8 @@ the palette of the `world` region.
 | `weather` | `sunny`, `cloudy` or `rainy` |
 | `debug` | `normals`, `lod`, `cracks` (red clear colour), `surface` (red where drawnHeight leaves the mesh by 5 cm), the ground codes `material`, `lithology`, `region`, `snow` (white where snow lies on the date), `albedo` (the ground colour without light), or `mask` (the features of the mask, flat, as `mask_view` in `terrain.wgsl` colours them) |
 | `scale` | The render scale per axis, 0.25 to 0.75 (default 0.7); debug views draw at 1, with the nodes of the scale |
+| `ground` | `plan`: a worker builds the ground plan of each cell near the eye; the HUD shows its line. Read once, as `scale` is |
+| `plan` | With `ground=plan`: `faces` draws the plan over the view in the debug tool's colours (default `off`) |
 | `still` | No engine starts. A headless script calls `window.trailviewStill.still(job, options)`, `coverView(line, when)`, `canRenderStills(options)`, `view(search)`, the view of a query string, and reads `release`, the id of the release; `still.test.js` and `home-views.mjs` show how |
 
 The HUD lists the keys; Ctrl+C and Ctrl+V copy and paste the view as an address.
@@ -69,13 +72,15 @@ From `builder/web/tests/browser`:
 
 ```sh
 npm run pretest:trailview                  # the page against the fixture
-node trailview/shoot.mjs [--views FILE] [--out DIR] [--width PX] [--height PX] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--hud] [--gpu] [--audit] [--pages N]
+node trailview/shoot.mjs [--views FILE] [--out DIR] [--width PX] [--height PX] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--hud] [--gpu] [--audit] [--pages N] [--query Q]
 node trailview/shoot.mjs --gpu --views trailview/road-views.json --width 1920 --height 960  # these views need this size: the default is 1280 × 800
-node trailview/flight.mjs --gpu [--flights FILE] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--cracks N] [--audit N] [--resolve MS]
+node trailview/flight.mjs --gpu [--flights FILE] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--cracks N] [--audit N] [--resolve MS] [--query Q]
+flock /tmp/trailview-gpu.lock node trailview/shoot.mjs --gpu --views trailview/road-views-top.json --width 1920 --height 960 --query 'ground=plan&plan=faces'  # Q is appended to each view
 node trailview/skyline.mjs [--tiles FILE] [--gpu]
 trailview/box.sh [view | flight ARGS]       # bake the Engelberg box without obc data; open it; time it
 node trailview/network.mjs [--view V] [--mbit 25] [--rtt 40] [--web DIR]  # a cold view of the bake on a shaped link
 npm run test:trailview                     # every browser test; CI adds -- --grep-invert @gpu
+OBC_TRAILVIEW_GPU=1 flock /tmp/trailview-gpu.lock npm run test:trailview -- --grep @gpu  # @gpu tests on the GPU
 (cd ../.. && npx vite-node scripts/road-census.ts .artifacts/census)  # the census's CPU counts and samples
 flock /tmp/trailview-gpu.lock node trailview/census.mjs --gpu ../../.artifacts/census --ground DIR  # its GPU counts
 ```
@@ -95,8 +100,8 @@ The fault census counts over the fixture, 70 m inside its bounds. Each count pri
 | `torn-slivers` | a face is under 2 cm wide in plan and steps over 3 cm across |
 | `torn-twists` | a quad's two faces turn 30° to 100° apart |
 
-Tears and lifts compare with the drawn mesh everywhere, and leave out decks. `mesh.test.ts` gates the
-first three at their values on develop, and the torn faces at `census-baseline.json`.
+Tears and lifts compare with the drawn mesh everywhere, and leave out decks. `road-census.ts` gates the
+first three and the torn faces (`census-baseline.json`): it fails past a gate.
 
 `shoot.mjs` writes one PNG per view after `waitForIdle()`, `--pages` views at once (3 with `--gpu`,
 else 1); lines come as views finish. Two runs can differ in a few pixels by a few levels: compare
@@ -150,7 +155,7 @@ uv run --locked --group planner-maps python FIX features features.pmtiles
 - A GPU lowers its clock when a frame has time to spare, so a pass measures long;
   `flight.mjs --gpu` keeps the clock high.
 - Tag a browser test that draws for minutes on SwiftShader `{ tag: '@gpu' }`: pull requests skip
-  it, `test-weekly.yml` runs it each Monday.
+  it; `web.trailview-gpu` runs it on a GPU.
 - Headless Chromium on Linux with no GPU shows a WebGPU canvas only with
   `--use-vulkan=swiftshader` (`SWIFTSHADER` in `harness.js`). Else the device is lost: "A valid
   external Instance reference no longer exists".
diff --git a/builder/web/src/lib/trailview/engine.ts b/builder/web/src/lib/trailview/engine.ts
index 6df561fccc..d6dafc6b45 100644
--- a/builder/web/src/lib/trailview/engine.ts
+++ b/builder/web/src/lib/trailview/engine.ts
@@ -23,21 +23,28 @@ import { EYE, Instances, SUN, type InstanceStats, type LastFrame } from './insta
 import { GroundSource } from './stream/ground';
 import { eyeTiles, pageDecoder, type EyeTiles } from './stream/terrain';
 import { Terrain, terrainPipelines, type Audit, type TerrainStats } from './terrain/terrain';
+import { piecePipelines } from './plan/pieces';
+import HOUSE_VERSION from 'virtual:house-version';
+import PLAN_VERSION from 'virtual:plan-version';
+import STAMP_VERSION from 'virtual:stamp-version';
+import TREE_VERSION from 'virtual:tree-version';
+import { FINEST, NEAR_M } from './terrain/lod';
 import { Houses, type HouseStats } from './structures/houses';
 import { Forest } from './vegetation/forest';
-import { TreeModels } from './vegetation/tree-models';
+import { TREE_REACH_M, TreeModels, type Reach } from './vegetation/tree-models';
 import { Plants } from './vegetation/plants';
 import { Rows } from './vegetation/rows';
 import { Dressing } from './dressing/dressing';
 import { KindPoints } from './structures/kind-points';
 import { LightPools } from './structures/light-pools';
 import { Route, type RoutePin } from './route/route';
+import type { PlanStats } from './plan/plan';
 import { sampleDistances, terrainHides } from './sight';
 import { Pacer } from './pacer';
 import type { StillPoints } from './still';
 import { DEBUG_VIEWS, TIME_ZONE, type View } from './view';
 
-const PASSES = ['terrain', 'ground', 'stamp', 'houses', 'vegetation', 'casters', 'shadow', 'far-casters', 'far-shadow', 'mips', 'resolve'];
+const PASSES = ['terrain', 'ground', 'stamp', 'houses', 'vegetation', 'casters', 'shadow', 'far-casters', 'far-shadow', 'mips', 'resolve', 'pieces', 'cliff'];
 /** Metres to a view that is at another place. */
 const NEW_PLACE = 1000;
 /** A step of the footing this small no longer moves the view about the eye: `eyeReady` counts it as settled. */
@@ -54,6 +61,8 @@ const RAD = Math.PI / 180;
 const STEP_M = 1, HEADROOM_M = 2;
 /** A flying eye under the terrain is in a tunnel when a floor lies at most this far below it. */
 const BORE_M = 6;
+/** The regions in reach are read this much wider and again only when the eye moves farther or the ground pages change. */
+const REACH_MARGIN_M = 250;
 /** The lift of the ribbon of route.wgsl above the surface. */
 const LIFT_M = 0.3;
 
@@ -80,15 +89,24 @@ export interface Stats {
     ground: GroundStats;
     houses: HouseStats;
     instances: InstanceStats;
+    /** The ground plan, only with `ground=plan`. */
+    plan?: PlanStats;
 }
 
 /**
- * The pipelines of the first frame: the terrain and its compute, the ground pages, the sky and the
- * resolve. The other passes compile theirs at their attach, after the first frame.
+ * The pipelines of the first frames: the terrain and its compute, the ground pages, the sky and the resolve, and with the
+ * records (`plan`) the meshes, which draw the view about the eye. The other passes compile theirs at their attach, once
+ * the view about the eye is drawn: a compile holds the GPU process, which the first frames' stamps and corners need.
  */
-const FIRST: ((gpu: Gpu) => Promise)[] = [terrainPipelines, groundPipelines, skyPipeline, resolvePipeline];
-/** The longest that the other passes wait for the first frame: a view whose eye has no ground draws none. */
-const REST_WAIT_MS = 2000;
+const first = (plan: boolean): ((gpu: Gpu) => Promise)[] => [terrainPipelines(plan), groundPipelines, skyPipeline, resolvePipeline, ...(plan ? [piecePipelines] : [])];
+/**
+ * The longest from the attach that the other passes wait for the view about the eye: a view whose eye has no ground
+ * draws none. Their compile, which takes about a second on a desktop, would stall the view about the eye.
+ */
+const REST_WAIT_MS = 5000;
+
+/** The options of `TrailView.start`. */
+interface StartOptions { plan?: boolean; finest?: number; pool?: number; size?: [number, number] }
 
 /** Where the eye stands: a height, and whether it lies in a tunnel. */
 interface Feet { z: number; tunnel: boolean; floor: boolean }
@@ -112,6 +130,8 @@ export class TrailView {
     private readonly houses: Houses;
     private readonly instances = new Instances();
     private readonly trees: TreeModels;
+    /** The last regions in reach, where they were read from and at which change of the ground pages. */
+    private reached?: Reach & { east: number; north: number; changes: number };
     private readonly forest: Forest;
     private readonly plants: Plants;
     private readonly rows: Rows;
@@ -126,7 +146,7 @@ export class TrailView {
     private readonly controls?: Controls;
     private destroyed = false;
     private pose: Pose;
-    private extras: Pick;
+    private extras: Pick;
     private gpuState!: { gpu: Gpu; uniform: GPUBuffer; look: GPUBuffer; times: PassTimes; targets: Targets };
     /** The ground under the eye, on the plane of the last probe; a new view forgets it. */
     private footing?: Footing;
@@ -135,9 +155,9 @@ export class TrailView {
     private ready = false;
     /** No frame draws before `start` lets it: a frame asks for every tile, and the tiles under the eye come first. */
     private held = true;
-    /** The attach of the other passes, which starts at the first drawn frame (`firstDrawn`); it rejects when one fails. */
+    /** The attach of the other passes, which starts once a frame draws the view about the eye (`eyeDrawn`); it rejects when one fails. */
     private rest: Promise = Promise.resolve();
-    private firstDrawn?: () => void;
+    private eyeDrawn?: () => void;
     /** Whether every pass is attached; `completed` until a frame draws them all. */
     private complete = false;
     private completed = false;
@@ -165,25 +185,27 @@ export class TrailView {
      */
     private skyMagnitude = DARK_SKY;
 
-    private constructor(private readonly canvas: HTMLCanvasElement, config: PlannerConfig, view: View, ground: GroundSource | undefined, tiles: EyeTiles, private readonly stop: AbortController, private readonly scale: number, private readonly size?: [number, number]) {
+    private constructor(private readonly canvas: HTMLCanvasElement, config: PlannerConfig, view: View, ground: GroundSource | undefined, tiles: EyeTiles, private readonly stop: AbortController, private readonly scale: number, readonly groundPlan: boolean, finest: number, pool: number, private readonly output?: [number, number]) {
         // `destroy()` aborts it: it ends the tile requests, the workers and the listeners.
         const { signal } = stop;
         this.context = canvas.getContext('webgpu')!;
         this.frame = frameAt(view.lon, view.lat);
         this.pose = this.poseOf(view);
-        this.extras = { date: view.date, time: view.time, weather: view.weather, debug: view.debug };
+        this.extras = { date: view.date, time: view.time, weather: view.weather, debug: view.debug, plan: view.plan };
         const { features } = tiles;
-        this.terrain = new Terrain(this.frame, { fetch: tiles.terrain, decode: pageDecoder(signal) }, features, config.bounds, () => this.request(), signal);
+        // The release ID, and the tile URLs for a config without one.
+        const release = JSON.stringify([config.id, config.manifest, config.terrain, config.layers]);
+        this.terrain = new Terrain(this.frame, { fetch: tiles.terrain, decode: pageDecoder(signal) }, features, config.bounds, () => this.request(), signal, groundPlan, finest, tiles.stamps, { release, version: STAMP_VERSION, plan: PLAN_VERSION }, pool);
         this.groundLook = new Ground(ground, () => this.request());
-        this.houses = new Houses(this.frame, features, this.groundLook.rules, () => this.request(), signal);
-        this.trees = new TreeModels(this.instances, () => this.request(), () => this.treesNear(), signal);
+        this.houses = new Houses(this.frame, features, this.groundLook.rules, () => this.request(), signal, { release, version: HOUSE_VERSION });
+        this.trees = new TreeModels(this.instances, () => this.request(), () => this.treesNear(), signal, TREE_VERSION);
         this.forest = new Forest(config, this.groundLook.rules, this.trees, this.instances, () => this.request(), signal);
         this.plants = new Plants(this.groundLook.rules, this.trees, this.instances, () => this.request(), signal);
         this.rows = new Rows(this.groundLook.rules, this.trees, this.plants, this.instances);
         this.kindPoints = new KindPoints(this.instances);
         this.dressing = new Dressing(this.groundLook.rules, this.instances);
         // A still has a size of its own and no input: the controls listen for keys on the whole window.
-        if (size) return;
+        if (output) return;
         this.controls = new Controls(canvas, {
             pose: () => this.pose,
             moved: pose => { this.pose = pose; this.moved = true; this.request(); },
@@ -195,27 +217,30 @@ export class TrailView {
     }
 
     /**
-     * Compiles the pipelines of the first frame on a device, without a view and without pools: on a cold
+     * Compiles the pipelines of the first frames on a device, without a view and without pools: on a cold
      * shader cache that takes seconds. Call it as soon as a view is likely, such as when a drag toward one
      * starts; `start` on the same device takes what it compiled, also while it still compiles.
      */
-    static prepare(gpu: Gpu): Promise {
-        return Promise.all(FIRST.map(make => gpu.once(make))).then(() => {});
+    static prepare(gpu: Gpu, plan = false): Promise {
+        return Promise.all(first(plan).map(make => gpu.once(make))).then(() => {});
     }
 
     /**
      * Starts the terrain and feature tiles under the eye, reads the ruleset and opens the ground layers,
      * attaches what the first frame draws, then starts the other tile loads once the tiles under the eye
      * are in, or after EYE_WAIT_MS: on a slow link the other loads would share it with them. The other
-     * passes draw once they attach after the first frame. `scale` is the render scale. `size` is the
-     * output in pixels, in place of the element's size on the screen.
+     * passes draw once they attach after the view about the eye. `scale` is the render scale; `plan` builds the
+     * ground plan beside the old ground (`ground=plan`); `finest` caps the terrain's finest level (`finest=`), and `pool`
+     * scales its page pools (`pool=`). `size` is the output of a still in pixels, in place of the element's size on the
+     * screen. All but the attach run while `gpu` comes: the frames before it ask for the view's records and stamps.
      */
-    static async start(canvas: HTMLCanvasElement, gpu: Gpu, config: PlannerConfig, view: View, scale: number, size?: [number, number]): Promise {
+    static async start(canvas: HTMLCanvasElement, gpu: Gpu | Promise, config: PlannerConfig, view: View, scale: number, { plan = false, finest = FINEST, pool = 1, size }: StartOptions = {}): Promise {
         const stop = new AbortController(), tiles = eyeTiles(config, [view.lon, view.lat], stop.signal);
         const ground = await GroundSource.open(config, stop.signal).catch(error => void console.warn(`TrailView draws no ground: ${error instanceof Error ? error.message : error}`));
-        const engine = new TrailView(canvas, config, view, ground ?? undefined, tiles, stop, scale, size);
+        const engine = new TrailView(canvas, config, view, ground ?? undefined, tiles, stop, scale, plan, finest, pool, size);
+        engine.request();
         // No caller holds an engine whose start fails, so it ends itself: its workers and listeners run already.
-        await engine.attach(gpu).catch(error => {
+        await Promise.resolve(gpu).then(device => engine.attach(device)).catch(error => {
             engine.destroy();
             throw error;
         });
@@ -246,7 +271,7 @@ export class TrailView {
             this.lastFrame = undefined;
         }
         this.pose = pose;
-        this.extras = { date: view.date, time: view.time, weather: view.weather, debug: view.debug };
+        this.extras = { date: view.date, time: view.time, weather: view.weather, debug: view.debug, plan: view.plan };
         this.moved = true;
         this.request();
     }
@@ -266,6 +291,7 @@ export class TrailView {
             adapter: gpu.adapter, gpu: { ...times.ms }, timed: times.tag, cpu: this.cpu, pools: new Map(gpu.pools),
             requests: pages.requests + ground.requests + forest.requests, bytes: pages.bytes + ground.bytes + forest.bytes, failed: pages.failed + ground.failed + forest.failed + this.terrain.failed,
             drawn: this.drawn, scale: this.scaleNow, resident: terrain.resident.stored + terrain.resident.synth, recoveries: this.recoveries, terrain, ground, houses: this.houses.stats, instances: this.instances.stats,
+            ...(this.terrain.plan ? { plan: this.terrain.plan.stats } : {}),
         };
     }
 
@@ -345,6 +371,11 @@ export class TrailView {
         return this.terrain.audit();
     }
 
+    /** The determinism check's hashes of the drawn terrain (Terrain.hashes), with the state of the last frame: call it after `waitForIdle()`. */
+    hashes(): Promise> {
+        return this.terrain.hashes();
+    }
+
     /**
      * Ends the engine: no frame draws, no tile loads, no worker runs, and the buffers and textures that
      * it made are destroyed. The device stays for the next engine. The waits for a frame resolve.
@@ -434,25 +465,25 @@ export class TrailView {
     }
 
     private near(): boolean {
-        return this.drawing && this.complete && this.terrain.near && this.settled() && this.groundLook.nearIdle && this.houses.nearIdle && this.trees.idle && this.forest.idle
-            && this.plants.idle && this.instances.idle && this.shadow.nearDrawn;
+        return this.drawing && this.complete && this.terrain.near && this.settled() && this.groundLook.nearIdle && this.houses.nearIdle && this.trees.nearIdle && this.forest.idle
+            && this.plants.nearIdle && this.instances.idle && this.shadow.nearDrawn;
     }
 
     /**
-     * Resolves when the first frame can draw. The other passes attach at the first drawn frame, or after
-     * REST_WAIT_MS: their compiles would share the compiler and the CPU with the first frame. The engine's
+     * Resolves when the first frame can draw. The other passes attach once the view about the eye is drawn, or
+     * after REST_WAIT_MS: their compiles would share the compiler and the CPU with that view. The engine's
      * buffers and textures are made in a scope of the device, which `destroy()` releases.
      */
     private async attach(base: Gpu): Promise {
         const gpu = base.scope();
         // The passes' attaches report a failed compile.
-        TrailView.prepare(gpu).catch(() => {});
+        TrailView.prepare(gpu, this.groundPlan).catch(() => {});
         this.complete = false;
         // A still copies the canvas.
-        this.context.configure({ device: gpu.device, format: gpu.format, alphaMode: 'opaque', usage: GPUTextureUsage.RENDER_ATTACHMENT | (this.size ? GPUTextureUsage.COPY_SRC : 0) });
+        this.context.configure({ device: gpu.device, format: gpu.format, alphaMode: 'opaque', usage: GPUTextureUsage.RENDER_ATTACHMENT | (this.output ? GPUTextureUsage.COPY_SRC : 0) });
         const uniform = gpu.buffer('uniforms', FRAME_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);
         const look = gpu.buffer('uniforms', LOOK_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
-        const targets = new Targets(gpu, !!this.size);
+        const targets = new Targets(gpu, !!this.output);
         this.gpuState = { gpu, uniform, look, times: new PassTimes(gpu, PASSES, { resolve: 'terrain' }), targets };
         this.temporal.reset();
         // The maps at once: the ground's group binds them.
@@ -461,7 +492,7 @@ export class TrailView {
         const surface = this.terrain.surface!, features = this.terrain.features!;
         await Promise.all([this.groundLook.attach(gpu, look, surface, this.shadow.entries()), this.sky.attach(gpu), this.resolve.attach(gpu)]);
         const drawn = new Promise(resolve => {
-            this.firstDrawn = resolve;
+            this.eyeDrawn = resolve;
             setTimeout(resolve, REST_WAIT_MS);
         });
         // A device lost before the first frame leaves the other passes to the next attach.
@@ -474,7 +505,7 @@ export class TrailView {
             });
             // A destroy during these attaches released the scope before they made their buffers, also when one fails.
             try {
-                await Promise.all([shadow, this.terrain.attachParts(frames), this.houses.attach(gpu, frames, surface, features), this.instances.attach(gpu, frames, { surface, features }), this.lightPools.attach(gpu, uniform), this.route.attach(gpu, uniform)]);
+                await Promise.all([shadow, this.terrain.attachParts(frames), this.houses.attach(gpu, frames, surface, features), this.instances.attach(gpu, frames, { surface, features }), this.lightPools.attach(gpu, uniform), this.route.attach(gpu, uniform), this.terrain.plan?.draw.attach(gpu, uniform)]);
             } finally {
                 if (this.destroyed) gpu.release();
             }
@@ -498,7 +529,7 @@ export class TrailView {
             }
             if (this.destroyed) return;
             // The other passes attach before the next frame: until they do, they hold the lost device's resources.
-            this.firstDrawn?.();
+            this.eyeDrawn?.();
             this.recoveries++;
             this.request();
         });
@@ -574,6 +605,18 @@ export class TrailView {
         return near;
     }
 
+    /**
+     * The regions where trees and plants can stand about the eye, and those of the near field, each read REACH_MARGIN_M
+     * wider: the last answer holds until the pages change or the eye moves past that margin.
+     */
+    private reach(): Reach {
+        const { east, north } = this.pose, last = this.reached, changes = this.groundLook.changes;
+        if (last && last.changes === changes && Math.abs(east - last.east) <= REACH_MARGIN_M && Math.abs(north - last.north) <= REACH_MARGIN_M) return last;
+        const [lon, lat] = this.frame.lonLat(east, north), wider = (metres: number) => this.groundLook.regionsNear(lon, lat, metres + REACH_MARGIN_M);
+        this.reached = { east, north, changes, reach: wider(TREE_REACH_M), near: wider(NEAR_M) };
+        return this.reached;
+    }
+
     /** Degrees clockwise from the frame's north to true north at a point. */
     private convergence(east: number, north: number): number {
         const [lon, lat] = this.frame.lonLat(east, north), [e, n] = this.frame.local(lon, lat + 1e-4);
@@ -587,7 +630,11 @@ export class TrailView {
 
     private render(now: number): void {
         this.pending = false;
-        if (!this.ready || this.held) return;
+        if (!this.ready) {
+            if (!this.destroyed) this.ask();
+            return;
+        }
+        if (this.held) return;
         if (!this.pacer.due(now)) return this.request();
         const start = performance.now();
         const steer = this.controls?.steer(), dt = this.last ? Math.min(0.1, (now - this.last) / 1000) : 0;
@@ -612,15 +659,17 @@ export class TrailView {
         const viewProj = viewProjection(this.pose.heading, this.pose.pitch, aspect);
         const lonLat = this.frame.lonLat(place.east, place.north);
         // The shipping render scale selects the nodes, also for a debug view: it shows the LOD that ships.
-        this.terrain.update({ lonLat, above: place.above, z: eye?.z, viewProj, pixels: targets.viewport(this.scale)[1] }, this.groundLook.reads);
+        if (this.terrain.plan) this.terrain.plan.debug = this.extras.plan === 'faces';
+        this.terrain.update({ lonLat, above: place.above, z: eye?.z, viewProj, pixels: targets.viewport(this.scale)[1], ahead: ahead(this.pose) }, this.groundLook.reads);
         this.kindPoints.update(this.terrain.kindPoints);
         this.lightPools.set(this.kindPoints.lights);
         const { drawn, wanted, arrived, origins } = this.terrain.selected;
         this.groundLook.update(drawn, wanted, arrived, origins, this.extras.date, lonLat, this.forest.regionPages(lonLat));
         this.houses.update(lonLat, eye && { viewProj, eye: [eye.east, eye.north, eye.z] });
-        this.trees.update(this.extras.date);
+        const reach = this.reach();
+        this.trees.update(this.extras.date, reach);
         this.forest.update(lonLat);
-        this.plants.update(lonLat, this.extras.date, place.above);
+        this.plants.update(lonLat, this.extras.date, place.above, reach);
         this.rows.update(lonLat);
         this.dressing.update(lonLat);
         const group = this.groundLook.group;
@@ -688,17 +737,22 @@ export class TrailView {
                 timestampWrites: times.writes('terrain'),
             });
             pass.setViewport(0, 0, width, height, 0, 1);
-            // Before the terrain: the ground that the trees hide fails the depth test.
-            this.instances.draw(pass, group);
-            this.terrain.draw(pass, group);
-            this.houses.draw(pass, group);
-            if (this.extras.debug !== 'cracks') this.sky.draw(pass, group);
+            // Before the terrain: the ground that the trees hide fails the depth test. The owned view draws the meshes and the terrain only.
+            const owned = this.extras.debug === 'owned';
+            if (!owned) this.instances.draw(pass, group);
+            this.terrain.draw(pass, group, owned);
+            if (!owned) this.houses.draw(pass, group);
+            if (this.extras.debug !== 'cracks' && !owned) this.sky.draw(pass, group);
             // After the sky, which draws where nothing did: the route and its pins write no depth.
-            if (this.terrain.surface && this.terrain.features) this.route.draw(pass, this.terrain.surface, this.terrain.features);
+            if (!owned && this.terrain.surface && this.terrain.features) this.route.draw(pass, this.terrain.surface, this.terrain.features);
             pass.end();
             if (this.terrain.surface && this.terrain.features) this.lightPools.encode(encoder, targets.scene!, targets.depth!, [width, height], this.terrain.surface, group, this.terrain.features);
-            this.resolve.encode(encoder, targets, this.context.getCurrentTexture().createView(), group,
+            const canvas = this.context.getCurrentTexture().createView();
+            this.resolve.encode(encoder, targets, canvas, group,
                 { viewProj, eye: [eye.east, eye.north, eye.z], render: [width, height], jitter: offset }, { weight: step.weight, clip: step.clip, copy: debug }, times.writes('resolve'));
+            if (this.extras.plan === 'faces' && this.terrain.plan && this.terrain.surface && this.terrain.features) {
+                this.terrain.plan.draw.encode(encoder, canvas, targets.depth!, [width / targets.width, height / targets.height], this.terrain.surface, this.terrain.features);
+            }
             targets.swap();
             this.lastFrame = { depth: targets.depth!, pixels: [width, height], viewProj: jittered(viewProj, ndc), eye: [eye.east, eye.north, eye.z] };
             if (this.grab && !this.converging) grabbed = this.copy(encoder, { viewProj, eye: [eye.east, eye.north, eye.z], pixel });
@@ -709,7 +763,7 @@ export class TrailView {
             this.grab!.resolve(grabbed);
             this.grab = undefined;
         }
-        if (step) this.firstDrawn?.();
+        if (step && this.eyeFinal()) this.eyeDrawn?.();
         read();
         probed();
         counted();
@@ -717,6 +771,8 @@ export class TrailView {
         cast();
         this.cpu = performance.now() - start;
         this.drawn = eye ? this.terrain.drawn : 0;
+        // The tree models that the workers built go to the device cache once the view is idle, so a load never waits for the writes.
+        if (this.trees.unsaved && this.idle()) this.trees.save();
         // Frames go on while the eye moves or settles on the ground, while the terrain or the ground has
         // work that no load waits for, and until a still view has all its jittered frames.
         if (steer || !settled || this.terrain.working || this.groundLook.working || this.houses.working || this.shadow.pending || this.converging) this.request();
@@ -767,6 +823,22 @@ export class TrailView {
         return this.houses.readCasters(encoder);
     }
 
+    /**
+     * A frame before the device draws: it selects the view's nodes only for the records and the meshes' stamps, so that
+     * their workers start before the pipelines are compiled.
+     */
+    private ask(): void {
+        const place = this.place(), [width, height] = this.size();
+        this.terrain.update({ lonLat: this.frame.lonLat(place.east, place.north), above: place.above, viewProj: viewProjection(this.pose.heading, this.pose.pitch, width / height), pixels: Math.max(1, Math.round(height * this.scale)), ahead: ahead(this.pose) });
+    }
+
+    /** The canvas's size in pixels: the size of `start`, or the element's size on the screen. */
+    private size(): [number, number] {
+        if (this.output) return this.output;
+        const ratio = Math.min(devicePixelRatio, MAX_PIXEL_RATIO);
+        return [Math.max(1, Math.round(this.canvas.clientWidth * ratio)), Math.max(1, Math.round(this.canvas.clientHeight * ratio))];
+    }
+
     /** Encodes the copy of the canvas, in rows of a multiple of 256 bytes. */
     private copy(encoder: GPUCommandEncoder, camera: Omit): Grabbed {
         const canvas = this.context.getCurrentTexture(), row = Math.ceil(4 * canvas.width / 256) * 256;
@@ -775,10 +847,9 @@ export class TrailView {
         return { ...camera, colour, row, output: [canvas.width, canvas.height] };
     }
 
-    /** Fits the canvas and the targets to the element, or to the size of `start`; true when the targets are new. */
+    /** Fits the canvas and the targets to `size()`; true when the targets are new. */
     private fit(): boolean {
-        const ratio = Math.min(devicePixelRatio, MAX_PIXEL_RATIO);
-        const [width, height] = this.size ?? [this.canvas.clientWidth, this.canvas.clientHeight].map(side => Math.max(1, Math.round(side * ratio)));
+        const [width, height] = this.size();
         if (!this.gpuState.targets.fit(width, height, Math.max(this.scaleNow, MAX_SCALE))) return false;
         this.canvas.width = width;
         this.canvas.height = height;
@@ -884,6 +955,12 @@ interface Lights {
     seed: number;
 }
 
+/** The horizontal view direction in world units (x east, y south), undefined within about 6° of straight down or up. */
+function ahead({ heading, pitch }: Pose): [number, number] | undefined {
+    if (Math.cos(pitch * RAD) < 0.1) return undefined;
+    return [Math.sin(heading * RAD), -Math.cos(heading * RAD)];
+}
+
 /** The copies of the last frame of a capture, and its camera. */
 interface Grabbed {
     /** The canvas, in rows of `row` bytes. */
diff --git a/builder/web/src/lib/trailview/gpu/hashes.ts b/builder/web/src/lib/trailview/gpu/hashes.ts
new file mode 100644
index 0000000000..661bf37517
--- /dev/null
+++ b/builder/web/src/lib/trailview/gpu/hashes.ts
@@ -0,0 +1,62 @@
+// The determinism check's reads (tests/browser/trailview/determinism.mjs): a hash of named GPU regions,
+// so that two runs of one view compare their drawn state region by region.
+
+/** A texture rectangle of one layer, or a buffer range; regions of the same name hash together, in order. */
+export type Region = { name: string } & (
+    | { texture: GPUTexture; origin: [number, number, number]; size: [number, number]; texelBytes: number }
+    | { buffer: GPUBuffer; offset: number; bytes: number });
+
+/** Bytes that one staging buffer takes at most. */
+const STAGING = 32 * 2 ** 20;
+
+const bytesOf = (region: Region) => ('texture' in region ? align(region.size[0] * region.texelBytes) * region.size[1] : region.bytes);
+const align = (bytes: number) => Math.ceil(bytes / 256) * 256;
+
+/** Per name, two 32-bit FNV-1a-like hashes of the regions' bytes (a texture's rows without their padding), as 16 hex digits. */
+export async function hashRegions(device: GPUDevice, regions: Region[]): Promise> {
+    const state = new Map();
+    for (let first = 0; first < regions.length;) {
+        let bytes = 0, last = first;
+        while (last < regions.length && (last === first || bytes + bytesOf(regions[last]) <= STAGING)) bytes += bytesOf(regions[last++]);
+        const staging = device.createBuffer({ size: bytes, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
+        const encoder = device.createCommandEncoder();
+        let at = 0;
+        for (const region of regions.slice(first, last)) {
+            if ('texture' in region) encoder.copyTextureToBuffer({ texture: region.texture, origin: region.origin }, { buffer: staging, offset: at, bytesPerRow: align(region.size[0] * region.texelBytes) }, [...region.size, 1]);
+            else encoder.copyBufferToBuffer(region.buffer, region.offset, staging, at, region.bytes);
+            at += bytesOf(region);
+        }
+        device.queue.submit([encoder.finish()]);
+        await staging.mapAsync(GPUMapMode.READ);
+        const words = new Uint32Array(staging.getMappedRange());
+        at = 0;
+        for (const region of regions.slice(first, last)) {
+            const h = state.get(region.name) ?? start();
+            const [row, rows] = 'texture' in region ? [align(region.size[0] * region.texelBytes), region.size[1]] : [region.bytes, 1];
+            const used = 'texture' in region ? region.size[0] * region.texelBytes : region.bytes;
+            for (let r = 0; r < rows; r++) for (let w = (at + r * row) / 4, end = w + used / 4; w < end; w++) mix(h, words[w]);
+            state.set(region.name, h);
+            at += bytesOf(region);
+        }
+        staging.unmap();
+        staging.destroy();
+        first = last;
+    }
+    return Object.fromEntries([...state].map(([name, h]) => [name, hex(h)]));
+}
+
+/** The same hash of the bytes of arrays on the CPU, in order. */
+export function hashBytes(arrays: ArrayBufferView[]): string {
+    const h = start();
+    for (const array of arrays) for (const byte of new Uint8Array(array.buffer, array.byteOffset, array.byteLength)) mix(h, byte);
+    return hex(h);
+}
+
+const start = (): [number, number] => [0x811c9dc5, 0x9e3779b9];
+
+function mix(h: [number, number], word: number): void {
+    h[0] = Math.imul(h[0] ^ word, 16777619);
+    h[1] = (Math.imul(h[1] ^ word, 0x01000193) + 0x7f4a7c15) | 0;
+}
+
+const hex = ([a, b]: [number, number]) => (a >>> 0).toString(16).padStart(8, '0') + (b >>> 0).toString(16).padStart(8, '0');
diff --git a/builder/web/src/lib/trailview/gpu/include.test.ts b/builder/web/src/lib/trailview/gpu/include.test.ts
new file mode 100644
index 0000000000..418c080616
--- /dev/null
+++ b/builder/web/src/lib/trailview/gpu/include.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import { reached } from './include';
+
+describe('the declarations that a shader reaches', () => {
+    it('keeps what the entry points use, the directives and the overrides, and drops the rest and the comments', () => {
+        const source = `enable clip_distances;
+// A comment with /* and a fn unused() { } in it.
+/* A block comment /* nested */ that spans
+   lines. */
+override SHOWN: f32 = 1.0;
+const HALF = 0.5;
+const UNUSED = 2.0;
+struct Out { @builtin(position) at: vec4f, shade: f32 }
+@group(0) @binding(0) var frame: vec4f;
+@group(0) @binding(1) var spare: array;
+fn half(x: f32) -> f32 { return x * HALF; }
+fn unused(x: f32) -> f32 { return half(x) + UNUSED + spare[0]; }
+@vertex
+fn main(@builtin(vertex_index) v: u32) -> Out {
+    var out: Out;
+    out.at = frame;
+    out.shade = half(f32(v)) * SHOWN;
+    return out;
+}`;
+        expect(reached(source).split('\n')).toEqual([
+            'enable clip_distances;',
+            'override SHOWN: f32 = 1.0;',
+            'const HALF = 0.5;',
+            'struct Out { @builtin(position) at: vec4f, shade: f32 }',
+            '@group(0) @binding(0) var frame: vec4f;',
+            'fn half(x: f32) -> f32 { return x * HALF; }',
+            '@vertex',
+            'fn main(@builtin(vertex_index) v: u32) -> Out {',
+            '    var out: Out;',
+            '    out.at = frame;',
+            '    out.shade = half(f32(v)) * SHOWN;',
+            '    return out;',
+            '}',
+        ]);
+    });
+});
diff --git a/builder/web/src/lib/trailview/gpu/include.ts b/builder/web/src/lib/trailview/gpu/include.ts
index 79bfe93829..dea36b0e0d 100644
--- a/builder/web/src/lib/trailview/gpu/include.ts
+++ b/builder/web/src/lib/trailview/gpu/include.ts
@@ -13,6 +13,76 @@ export function include(path: string, read: (path: string) => string): string {
     return compose(path);
 }
 
+/**
+ * The declarations of a composed shader that its entry points reach, without comments. A browser parses
+ * and validates all text of a shader module when it creates the module, on the one thread that also runs
+ * every GPU command of the page; the includes bring in many more functions than a module calls. The
+ * directives, the assertions and the overrides stay: a pipeline sets an override by its name.
+ */
+export function reached(source: string): string {
+    const declarations = split(uncommented(source)), named = new Map();
+    for (const declaration of declarations) if (declaration.name) named.set(declaration.name, declaration);
+    const kept = new Set(declarations.filter(declaration => declaration.root)), next = [...kept];
+    for (let declaration = next.pop(); declaration; declaration = next.pop()) {
+        for (const [word] of declaration.text.matchAll(/[A-Za-z_]\w*/g)) {
+            const used = named.get(word);
+            if (used && !kept.has(used)) {
+                kept.add(used);
+                next.push(used);
+            }
+        }
+    }
+    return declarations.filter(declaration => kept.has(declaration)).map(declaration => declaration.text).join('\n');
+}
+
+interface Declaration { text: string; name?: string; root: boolean }
+
+/** A module-scope declaration's attributes, kind and name; no name for a directive or a `const_assert`. */
+const NAME = /^((?:@\w+\s*(?:\([^)]*\))?\s*)*)(fn|struct|alias|const|override|var)\b(?:\s*<[^>]*>)?\s+([A-Za-z_]\w*)/;
+
+/** The module-scope declarations: each ends at a `;` outside brackets, or a function or struct at its closing brace. */
+function split(code: string): Declaration[] {
+    const declarations: Declaration[] = [];
+    let start = 0, depth = 0;
+    const end = (until: number) => {
+        const text = code.slice(start, until).trim();
+        start = until;
+        if (!text || text === ';') return;
+        const [, attributes = '', kind, name] = NAME.exec(text) ?? [];
+        declarations.push({ text, name, root: !name || kind === 'override' || /@(?:vertex|fragment|compute)\b/.test(attributes) });
+    };
+    for (let at = 0; at < code.length; at++) {
+        const c = code[at];
+        if (c === '{' || c === '(' || c === '[') depth++;
+        else if (c === ')' || c === ']') depth--;
+        else if (c === '}' ? --depth === 0 && /\b(?:fn|struct)\b/.test(code.slice(start, code.indexOf('{', start))) : c === ';' && depth === 0) end(at + 1);
+    }
+    end(code.length);
+    return declarations;
+}
+
+/** The code without its line comments and its block comments, which nest in WGSL. */
+function uncommented(source: string): string {
+    const comment = /\/\/|\/\*/g;
+    let code = '', at = 0;
+    for (let found = comment.exec(source); found; found = comment.exec(source)) {
+        code += source.slice(at, found.index);
+        if (found[0] === '//') {
+            const newline = source.indexOf('\n', found.index);
+            at = newline < 0 ? source.length : newline;
+        } else {
+            let depth = 1;
+            for (at = found.index + 2; depth > 0 && at < source.length;) {
+                if (source.startsWith('/*', at)) (depth++, (at += 2));
+                else if (source.startsWith('*/', at)) (depth--, (at += 2));
+                else at++;
+            }
+        }
+        comment.lastIndex = at;
+    }
+    return code + source.slice(at);
+}
+
 /** A path without `..` parts: `ground/../light/shade.wgsl` is `light/shade.wgsl`. */
 function normal(path: string): string {
     const parts: string[] = [];
@@ -23,5 +93,8 @@ function normal(path: string): string {
     return parts.join('/');
 }
 
+/** The includes of the pieces of a junction with a stop arm: their pixels find the mouth (plan/mouth-in.wgsl). */
+export const MOUTH: Record = { 'roads/corridor-in.wgsl': 'plan/mouth-in.wgsl' };
+
 /** The includes that a device with `clip-distances` reads in place of the default ones. */
 export const CLIP_DISTANCES: Record = { 'terrain/unknown.wgsl': 'terrain/unknown-clip.wgsl', 'terrain/water-cut.wgsl': 'terrain/water-cut-clip.wgsl' };
diff --git a/builder/web/src/lib/trailview/gpu/layouts.ts b/builder/web/src/lib/trailview/gpu/layouts.ts
index ab0d446479..58b1b8cf14 100644
--- a/builder/web/src/lib/trailview/gpu/layouts.ts
+++ b/builder/web/src/lib/trailview/gpu/layouts.ts
@@ -31,7 +31,8 @@ export function layouts({ device }: Gpu): Layouts {
             [all, { buffer: { type: 'uniform' } }], [all, { buffer: read }], [all, array('uint')],
             [all, { buffer: read }], [all, { sampler: { type: 'non-filtering' } }],
         ]),
-        features: layout([[all, { buffer: read }], [all, array('float')], [all, array('uint')]]),
+        // The mask, the snaps, and with `ground=plan` the records' paint, the move of their heights and the cliff share.
+        features: layout([[all, { buffer: read }], [all, array('float')], [all, array('uint')], [all, array('float')], [all, array('float')], [all, array('float')]]),
         // The compute writes the cache: its bind group does not hold it for sampling. The producers of
         // instances read the snow in it.
         ground: device.createBindGroupLayout({ entries: [
diff --git a/builder/web/src/lib/trailview/gpu/shader-functions.ts b/builder/web/src/lib/trailview/gpu/shader-functions.ts
index 59f634cf1c..04a7ea6df5 100644
--- a/builder/web/src/lib/trailview/gpu/shader-functions.ts
+++ b/builder/web/src/lib/trailview/gpu/shader-functions.ts
@@ -8,12 +8,13 @@ export function functionOf(source: string, name: string): string {
     return source.slice(open + 1, at - 1);
 }
 
-/** Functions of a shader in JavaScript, as written there, with its constants. */
+/** Functions of a shader in JavaScript, as written there, with its constants and its private variables' first values. */
 export function shaderFunctions(source: string, names: string[]): T {
     const constants = [...source.matchAll(/^const (\w+): [fu]32 = ([^;]+);/gm)].map(([, name, value]) => `const ${name} = ${value.replace(/\b(0x[0-9a-f]+|\d+)u\b/g, '$1')};`);
+    constants.push(...[...source.matchAll(/^var (\w+): \w+ = ([^;]+);/gm)].map(([, name, value]) => `let ${name} = ${value};`));
     const functions = names.map(name => {
         const args = /\(([^)]*)\)/.exec(source.slice(source.indexOf(`fn ${name}(`)))![1];
-        const body = functionOf(source, name).replace(/\blet\b/g, 'const').replace(/\bvar\b/g, 'let').replace(/\b(max|min|abs|round)\(/g, 'Math.$1(').replace(/\b[fu]32\(/g, '(').replace(/(\d)u\b/g, '$1');
+        const body = functionOf(source, name).replace(/\blet\b/g, 'const').replace(/\bvar\b/g, 'let').replace(/\b(max|min|abs|round)\(/g, 'Math.$1(').replace(/\b[fu]32\(/g, '(').replace(/\b(0x[0-9a-f]+|\d+)u\b/g, '$1');
         return `function ${name}(${args.replace(/: \w+/g, '')}) {${body}}`;
     });
     const smoothstep = 'function smoothstep(a, b, x) { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); }\nfunction select(a, b, c) { return c ? b : a; }';
diff --git a/builder/web/src/lib/trailview/gpu/wgsl.ts b/builder/web/src/lib/trailview/gpu/wgsl.ts
index 82e6e53c51..ef9c047ce5 100644
--- a/builder/web/src/lib/trailview/gpu/wgsl.ts
+++ b/builder/web/src/lib/trailview/gpu/wgsl.ts
@@ -1,6 +1,14 @@
-import { include } from './include';
+import { include, reached } from './include';
 
 const SOURCES = import.meta.glob('../**/*.wgsl', { query: '?raw', import: 'default', eager: true }) as Record;
+const composed = new Map();
 
-/** The engine's WGSL file at a path such as `terrain/terrain.wgsl`, with its includes; `swap` reads another file for an include. */
-export const wgsl = (path: string, swap: Record = {}) => include(path, file => SOURCES[`../${swap[file] ?? file}`]);
+/**
+ * The engine's WGSL file at a path such as `terrain/terrain.wgsl`, with its includes, as the declarations
+ * that its entry points reach; `swap` reads another file for an include.
+ */
+export function wgsl(path: string, swap: Record = {}): string {
+    const key = `${path} ${JSON.stringify(swap)}`;
+    if (!composed.has(key)) composed.set(key, reached(include(path, file => SOURCES[`../${swap[file] ?? file}`])));
+    return composed.get(key)!;
+}
diff --git a/builder/web/src/lib/trailview/ground/ground.ts b/builder/web/src/lib/trailview/ground/ground.ts
index 5a303cc468..fb4948059b 100644
--- a/builder/web/src/lib/trailview/ground/ground.ts
+++ b/builder/web/src/lib/trailview/ground/ground.ts
@@ -252,6 +252,16 @@ export class Ground {
         this.jobs = [];
     }
 
+    /** Counts the changes of the resident pages. */
+    get changes(): number {
+        return this.pages.changes;
+    }
+
+    /** The regions of the resident pages within `metres` of a point, across or along. */
+    regionsNear(lon: number, lat: number, metres: number): Set {
+        return this.pages.regionsNear(lon, lat, metres);
+    }
+
     /** The regions about a point and their weights, which sum to 1. */
     regionsAt(lon: number, lat: number): Map {
         return this.pages.regionsAt(lon, lat);
diff --git a/builder/web/src/lib/trailview/ground/ground.wgsl b/builder/web/src/lib/trailview/ground/ground.wgsl
index 3fdbc5d71e..23dfa284f1 100644
--- a/builder/web/src/lib/trailview/ground/ground.wgsl
+++ b/builder/web/src/lib/trailview/ground/ground.wgsl
@@ -69,7 +69,7 @@ fn open_of(job: Job, t: vec2i) -> f32 {
 fn coarse_of(job: Job, u: vec2i) -> vec3f {
     // The finest ground pages also draw the nodes finer than them, near the eye, whose LOD is higher.
     let coarse = max(job.level, COARSEST + 2u) - select(2u, 1u, job.level == look.codes.x);
-    let n = level_normal(lod_space(vec2f(u - surface.anchor)), coarse);
+    let n = level_normal(lod_space(vec2f(u - surface.anchor)), coarse).xy;
     let step = WIDE << (22u - coarse);
     let coarse_open = openness(units_height(u, coarse), vec4f(units_height(u + vec2i(step, 0), coarse), units_height(u - vec2i(step, 0), coarse),
         units_height(u + vec2i(0, step), coarse), units_height(u - vec2i(0, step), coarse)), f32(WIDE << (job.level - coarse)) * job.metres);
diff --git a/builder/web/src/lib/trailview/ground/look.wgsl b/builder/web/src/lib/trailview/ground/look.wgsl
index f3ed583835..75748dbcb0 100644
--- a/builder/web/src/lib/trailview/ground/look.wgsl
+++ b/builder/web/src/lib/trailview/ground/look.wgsl
@@ -38,6 +38,42 @@
 override DETAIL: bool = true;
 // A corridor's band: the ground beside a road, shaped by it, under no paint and with facets of its own.
 override BAND: bool = false;
+// With the one road model (MODEL, `ground=plan`), a road's cut or fill steeper than 60° is rock, as a cliff (all rock
+// below CUT_ROCK_ALL of its fine normal's z, none above CUT_ROCK_NONE: 66° to 60°), where the coarse normal that the
+// cliffs take is also steep: soil faces to about 55° hold grass, and a steep cut on a gentle hillside is no cliff. The
+// terrain and the ground plan's mesh take it alike, from the share that a road shaped and the drawn normal, so a mesh
+// face meets the terrain beside it in one look. The old roads keep their look.
+const CUT_ROCK_ALL: f32 = 0.407;
+const CUT_ROCK_NONE: f32 = 0.5;
+// How steep the land is a few texels across, by the z of its coarse normal: a face past CUT_ROCK_NONE is rock only
+// where this is.
+fn coarse_steep_of(z: f32) -> f32 {
+    return 1.0 - smoothstep(0.85, 0.95, z);
+}
+
+// How far ground is rock as ground_colour draws a face of the plan's mesh, by the z of its fine and of its coarse
+// normal and the share that a road shaped it: a shaped face past the cut-rock slope, ground that no road shaped (or a
+// barren face) past its bare slope, at the slope that ground_colour turns toward the coarse normal (cliff_of); only
+// where the land is steep, and none under trees.
+fn rock_share(g: Ground, fine_z: f32, coarse_z: f32, shaped: f32) -> f32 {
+    let towards = cliff_of(fine_z, 0.0);
+    let land = coarse_steep_of(coarse_z);
+    let bare = bare_rock(g, mix(fine_z, coarse_z, towards)) * land * (1.0 - shaped * (1.0 - g.barren));
+    let cut = shaped * land * (1.0 - smoothstep(CUT_ROCK_ALL, CUT_ROCK_NONE, fine_z));
+    return max(bare, cut) * (1.0 - g.tree);
+}
+
+// How far ground turns toward the coarse normal as a cliff, by the z of its fine normal and how far that turns per texel:
+// a cliff spans few texels across and many metres up, so its fine slopes would streak down the face.
+fn cliff_of(fine_z: f32, spread: f32) -> f32 {
+    return 1.0 - spread_step(0.4, 0.7, fine_z, spread);
+}
+
+// How far ground of slope `z` (normal z) is bare rock: from its bare slope on, all of it a little steeper; on variegated
+// clays from 37°.
+fn bare_rock(g: Ground, z: f32) -> f32 {
+    return 1.0 - smoothstep(mix(g.bare_from, 0.8, g.banded), mix(g.bare_from + 0.043, 0.88, g.banded), z);
+}
 
 const COVER_TREE: u32 = 0u;
 const COVER_SHRUB: u32 = 1u;
@@ -93,6 +129,11 @@ struct Ground {
     p: vec2f,
 }
 
+// The ground of a band: shaped by its way, and a path's bench (`bench` 1) as flat as the path.
+fn band_road(bench: f32) -> Road {
+    return Road(vec3f(0.0), 0.0, 0.0, 0.0, 1.0, bench);
+}
+
 // Dave Hoskins' hash.
 fn hash(q: vec2f) -> f32 {
     var p3 = fract(q.xyx * 0.1031);
@@ -495,11 +536,26 @@ fn coarse_at(g: Ground) -> vec4f {
     if (g.page < 0) {
         return vec4f(0.0, 0.0, 1.0, 1.0);
     }
-    let r = coarse_read(g.level, g.page, g.base, g.p);
+    return coarse_texel(coarse_read(g.level, g.page, g.base, g.p));
+}
+
+// The coarse normal and openness of a texel of `relief_coarse`.
+fn coarse_texel(r: vec3f) -> vec4f {
     let m = r.xy * 2.0 - 1.0;
     return vec4f(render_normal(vec3f(m, sqrt(max(1.0 - dot(m, m), 1e-4)))), 0.6 + 0.55 * r.z);
 }
 
+// The z of the coarse normal at a point of a node of `level`, as coarse_at reads it for the ground there but for the
+// wobble, without the rest of that ground: a piece's wall reads it on each pixel.
+fn coarse_z_at(level: u32, s: vec2f) -> f32 {
+    let held = held_at(s, level);
+    if (held.page < 0) {
+        return 1.0;
+    }
+    let base = (held.t.whole + vec2i(held.t.part >= vec2f(0.5))) & vec2i(~255);
+    return coarse_texel(coarse_read(held.level, held.page, base, vec2f(held.t.whole - base) + held.t.part)).z;
+}
+
 // Voronoi cells about `size` metres across: the nearest cell's hash, the gap to the next cell's edge in
 // cell units, and a second hash for its shade.
 fn voronoi(p: vec2f, size: f32) -> vec3f {
@@ -602,16 +658,50 @@ fn crag(p: vec2f, size: f32) -> vec3f {
     return vec3f(facing, abs(2.0 * noise(q * 1.4 + 7.0) - 1.0));
 }
 
-// A road's cut or fill shows its detail this far from the eye: each pixel of it pays for two noises.
-const CUT_DETAIL_M: f32 = 90.0;
+// A near rock face shows blocks about NEAR_BLOCK_M across, wider than high, split by dark joints, in the plane of the
+// face (rock_near). They fade to their mean from half of NEAR_ROCK_M to NEAR_ROCK_M from the eye, alike on faces of every
+// turn, so two faces that meet in a crease fade alike: farther, blocks this size read as paving, and the crags take over.
+const NEAR_BLOCK_M: f32 = 2.4;
+const NEAR_ROCK_M: f32 = 40.0;
+// The mean shade of the joints, to which they fade once a pixel spans them.
+const JOINT_MEAN: f32 = 0.97;
+
+// The share of a face's plane that runs along the world's x, by its normal: 0 or 1 but within about 6° of 45°, where
+// two world planes cross-fade, as one plane would stretch or seam where the face turns.
+fn face_east(n: vec3f) -> f32 {
+    return smoothstep(-0.1, 0.1, (abs(n.y) - abs(n.x)) / (abs(n.x) + abs(n.y) + 1e-6));
+}
+
+// A near rock face lit by the normal `n`, for a pixel `w` metres wide on it: the tilt of its block across and up the
+// face, each block a flat facet, and the shade of the block's tone and of the joints. In the world plane nearest the
+// face: a vertical one (face_east), or the level one on a face gentler than about 45°, cross-faded between, so a face
+// that `n` holds stretches its blocks by at most about √2. A steep face lit by the cliffs' coarse normal (ground_colour)
+// stretches them farther where it turns away from that normal, as the crags.
+fn rock_near(world: vec2f, altitude: f32, n: vec3f, w: f32) -> vec3f {
+    let level = smoothstep(0.65, 0.75, n.z);
+    var k = vec3f(0.0);
+    if (level < 1.0) {
+        let east = face_east(n);
+        if (east < 1.0) {
+            k = rock_blocks(vec2f(world.y, altitude), w);
+        }
+        if (east > 0.0) {
+            k = mix(k, rock_blocks(vec2f(world.x, altitude), w), east);
+        }
+    }
+    if (level > 0.0) {
+        k = mix(k, rock_blocks(world, w), level);
+    }
+    return k;
+}
 
-// A road's cut or fill at `q` metres in the plane of its face, seen by a pixel `w` metres wide: tufts of the
-// `ground` and bare `earth`, longer along the face than up it. The grain fades to its mean once a pixel spans it.
-fn cut_face(ground: vec3f, earth: vec3f, q: vec2f, w: f32) -> vec3f {
-    let p = q * vec2f(1.0, 1.8);
-    let tuft = noise(p / 0.8);
-    let grain = mix(0.5, noise(p / 0.17), 1.0 - smoothstep(0.05, 0.25, w));
-    return mix(ground * (0.86 + 0.28 * tuft), mix(earth, ground, 0.45) * (0.8 + 0.4 * tuft), smoothstep(0.56, 0.64, tuft)) * (0.82 + 0.36 * grain);
+// rock_near in one plane at `q` metres. The joints fade to their mean shade once a pixel spans a few centimetres, and the
+// blocks once it spans a tenth of one: a face seen edge-on keeps its mean, with no dark band.
+fn rock_blocks(q: vec2f, w: f32) -> vec3f {
+    let c = voronoi(q * vec2f(1.0, 1.6), NEAR_BLOCK_M);
+    let joint = mix(JOINT_MEAN, mix(0.6, 1.0, smoothstep(0.0, 0.06, c.y)), 1.0 - smoothstep(0.04, 0.12, w));
+    let block = 1.0 - smoothstep(0.12, 0.3, w);
+    return vec3f((c.xz - 0.5) * 1.2 * block, (1.0 + 0.32 * (c.x - 0.5) * block) * joint);
 }
 
 // A distinct colour for each code, by the golden angle round the hue circle.
@@ -642,12 +732,18 @@ fn ground_debug(view: u32, level: u32, s: vec2f, g: Ground) -> vec3f {
     return mix(vec3f(0.45, 0.45, 0.6), vec3f(1.0), g.snow);
 }
 
+// The z of the fine normal below which ground_colour reads the coarse one; flatter ground, but for a skirt or a bench,
+// keeps its fine normal.
+const SLOPED: f32 = 0.95;
+
 // The colour of the ground at a point: `s` in LOD space, `relative` in render space about the eye,
 // `altitude` above sea level, on a node of `level`, in linear light with the haze, at the screen's `pixel`.
 // The sizes of a pixel are those of an output pixel, so the detail follows the canvas at any render scale.
-// `bench` is 1 on a path's band, which reads no mask. `d` holds the screen derivatives of `relative`, which the caller reads
-// outside any branch that differs by the pixel.
-fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u32, pixel: vec2f, bench: f32) -> vec3f {
+// With BAND, `band` is what the ways did to this ground (`band_road`), which reads no mask. `drawn` is the
+// surface's normal in LOD-space axes, the terrain's own or a mesh's, and in w how far the terrain's normal turns from
+// one texel to the next there (`drawn_relief`): each threshold on the normal is at least that soft (spread_step). `d`
+// holds the screen derivatives of `relative`, which the caller reads outside any branch that differs by the pixel.
+fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u32, pixel: vec2f, band: Road, drawn: vec4f) -> vec3f {
     let world = look.place.xy + relative.xy;
     let scale = look.screen.z;
     let dx = d[0].xy * scale;
@@ -659,17 +755,18 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
     let surface_size = max(length(d[0]), length(d[1])) * scale;
     var facet = normalize(cross(d[0], d[1]));
     facet *= sign(facet.z);
-    let drawn = drawn_normal(s);
-    var n = render_normal(drawn);
+    var n = render_normal(drawn.xyz);
+    let fine_z = n.z;
+    var spread = drawn.w;
     // Where the mesh slopes far more steeply than the ground's normals, it is a slope the mesh
     // smoothed out of detail finer than its triangles: it is cliff, lit like the cliff beside it.
     var skirt = select(smoothstep(0.25, 0.5, n.z - facet.z), 0.0, BAND);
-    let sloped = n.z < 0.95 || skirt > 0.0;
+    let sloped = n.z < SLOPED || skirt > 0.0;
     let g = ground_at(level, s, world, footprint);
     var open = g.open;
     let region = g.region;
     // The road paint first, so that only the Road stays live through the rest.
-    var road = Road(vec3f(0.0), 0.0, 0.0, 0.0, 1.0, 1.0 - bench, bench);
+    var road = band;
     if (!BAND) {
         road = road_at(s, mat2x2f(dpdx(s), dpdy(s)) * scale, world, footprint, length(relative.xy), region, pixel, facet.z);
     }
@@ -678,29 +775,38 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
         skirt *= 1.0 - road.shaped;
     }
     // A road's retaining wall, but for a cut in bare rock, and in woodland, as rock walls.
-    let masoned = road.wall * (1.0 - road.cover) * (1.0 - g.barren) * (1.0 - g.tree);
+    // On the plan path, `road.wall` marks a piece's wall that stands as rock (wall_rock of corridor.wgsl): it is all rock,
+    // as a vertical face holds no soil, snow or ground detail, whose texels vary along a wall and not up it.
+    let masoned = select(road.wall, 0.0, MODEL) * (1.0 - road.cover) * (1.0 - g.barren) * (1.0 - g.tree);
     // The masonry runs along the world axis nearer to the wall, cross-faded within about 6° of 45°. By
     // the fine normal: the coarse one that a cliff takes below does not see a road's wall.
-    let east = smoothstep(-0.1, 0.1, (abs(n.y) - abs(n.x)) / (abs(n.x) + abs(n.y) + 1e-6));
-    // A cliff spans few texels across and many metres up, so its fine slopes would streak down the
-    // face; it takes its normal from coarser levels instead.
-    let cliff = 1.0 - smoothstep(0.4, 0.7, n.z);
-    // Within a road's reach a slope past the 40° of its cut and fill is one of them, and its plan's texels stretch up it.
-    var face = 0.0;
+    let east = face_east(n);
     // How steep the land is a few texels across: a road cutting or a bank is steep only at the finest
     // level, and stays vegetated.
     var broad = 0.0;
+    var coarse_steep = 0.0;
     // A path's bench is flatter than its hillside, and lit as itself would show as a pale strip beside the tread.
     if (sloped || road.bench > 0.0) {
-        face = road.cuts * (1.0 - smoothstep(0.62, 0.84, n.z));
         let coarse = coarse_at(g);
-        broad = max(1.0 - smoothstep(0.85, 0.95, coarse.z), skirt);
+        coarse_steep = coarse_steep_of(coarse.z);
+        broad = max(coarse_steep, skirt);
         // A slope that a road shaped is a cut or a fill: it stays as the satellite sees it, rock only
         // where that is bare.
         broad *= 1.0 - road.shaped * (1.0 - g.barren);
-        let towards = max(max(cliff, skirt), max(face, road.bench));
+        var cliff = cliff_of(n.z, spread);
+        // The plan's creases are sharper than a texel, and this key would flip from texel to texel along them: the
+        // pages with masks hold it filtered (cliff_at), faded out before the mask pool's reach as the paint is
+        // (model_reach). A wall's face is no terrain normal. The filter carries the share onto flatter ground than
+        // SLOPED, where this block does not run: it fades out before SLOPED, or it would end there in a hard edge.
+        let held = select(0.0, model_reach(lod(s), length(relative.xy)) * (1.0 - smoothstep(SLOPED - 0.05, SLOPED, fine_z)), MODEL && road.wall == 0.0);
+        if (held > 0.0) {
+            cliff = mix(cliff, cliff_at(s, cliff), held);
+        }
+        let towards = max(max(cliff, skirt), road.bench);
         n = normalize(mix(n, coarse.xyz, towards));
         open = mix(open, coarse.w, towards);
+        // The coarse normal turns little from one texel to the next.
+        spread *= 1.0 - towards;
     }
     let banded = g.banded;
     let slope = n.z;
@@ -727,16 +833,6 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
     }
     let mottle = 0.14 * (n15 - 0.5) * (1.0 - smoothstep(4.0, 16.0, footprint)) + (0.22 * n25 + 0.12 * n08 - 0.17) * (1.0 - smoothstep(0.3, 2.0, footprint));
     var albedo = g.albedo * (1.0 + mottle);
-    if (face > 0.0 && r < CUT_DETAIL_M) {
-        var earth = albedo;
-        // Grass holds a bank up to about 55°; past that it stands bare, as rock where the ground is barren.
-        if (n.z < 0.62) {
-            let bare = mix(rule(region, slot_roads() + i32(CODE_DIRT) - 1).rgb, rule(region, slot_lithologies() + i32(g.lithology)).rgb, g.barren);
-            earth = mix(bare, albedo, smoothstep(0.45, 0.62, n.z));
-        }
-        let cut = cut_face(albedo, earth, vec2f(select(world.x, world.y, abs(n.x) > abs(n.y)), altitude), surface_size);
-        albedo = mix(albedo, cut, face * (1.0 - smoothstep(0.6 * CUT_DETAIL_M, CUT_DETAIL_M, r)));
-    }
     // Tussocks and low shrubs, more in some stretches about 60 m across than in others: tufts about 1 m,
     // shrubs about 3 m and thickets about 15 m across on the mottle's highs, and bushes 1 to 5 m long,
     // each darker and more olive than the sward. Each fades to its mean once a pixel spans it. The ground
@@ -845,7 +941,8 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
     let bare_from = g.bare_from;
     // Rock breaks into crags about 26 m across, in the plane of the face.
     // A crag that faces up holds turf where the satellite sees green.
-    let rock = skirt > 0.0 || (broad > 0.0 && slope < mix(bare_from + 0.12, 0.95, banded));
+    let cut_rock = select(0.0, road.shaped * coarse_steep * (1.0 - spread_step(CUT_ROCK_ALL, CUT_ROCK_NONE, fine_z, drawn.w)), MODEL);
+    let rock = skirt > 0.0 || cut_rock > 0.0 || (broad > 0.0 && slope < mix(bare_from + 0.12, 0.95, banded)) || (MODEL && road.wall > 0.0);
     let on_face = vec2f(select(world.x, world.y, abs(n.x) > abs(n.y)), altitude);
     let big = select(0.0, 1.0 - smoothstep(4.0, 12.0, surface_size), rock);
     // Gullies and buttresses tens of metres wide and a hundred tall bend the crags.
@@ -860,7 +957,7 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
     }
     let top = smoothstep(0.65, 0.85, crags.y) * big;
     let stepped = slope + 0.07 * (top - 0.25 * big);
-    let steep = max((1.0 - smoothstep(mix(bare_from, 0.8, banded), mix(bare_from + 0.043, 0.88, banded), stepped)) * broad, skirt);
+    let steep = max(max(bare_rock(g, stepped) * broad, skirt), cut_rock);
     let view = look.modes.x;
     if (view == 9u) {
         // The albedo without light: a seam in it is a seam of the ground pages.
@@ -869,7 +966,7 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
     if (view >= 5u) {
         return ground_debug(view, level, s, g) * (0.45 + 0.55 * max(dot(n, vec3f(-0.4, 0.4, 0.82)), 0.0));
     }
-    let walled = steep * (1.0 - g.tree) * (1.0 - road.cover) * (1.0 - masoned);
+    let walled = max(steep * (1.0 - g.tree) * (1.0 - road.cover) * (1.0 - masoned), select(0.0, road.wall, MODEL));
     if (walled > 0.0) {
         // Variegated clays erode into badlands, so their beds show on gentler slopes: red, white and
         // green-grey, streaked by gullies.
@@ -881,7 +978,7 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
             stone = mix(stone, beds, banded);
         }
         let wall = rule(region, slot_cliff());
-        var face = mix(mix(stone, wall.rgb, wall.a), g.albedo, g.barren * smoothstep(0.68, 0.8, n.z));
+        var face = mix(mix(stone, wall.rgb, wall.a), g.albedo, g.barren * smoothstep(0.68, 0.8, n.z) * (1.0 - select(0.0, road.wall, MODEL)));
         // Lit and weathered stretches of the wall, tens of metres across.
         let stain = noise(world / 70.0 + altitude / 50.0);
         // Each crag faces a little across the face and up or down it; the gullies and buttresses tilt
@@ -915,20 +1012,31 @@ fn ground_colour(s: vec2f, relative: vec3f, d: mat2x3f, altitude: f32, level: u3
         let bed = hash(vec2f(floor(dot(vec3f(world, altitude), rule(region, slot_cliff() + 4).xyz) / 11.0), 3.0));
         tone *= 1.0 + 0.08 * (bed - 0.5) * (1.0 - smoothstep(0.4, 0.6, stain)) * (1.0 - smoothstep(3.0, 10.0, surface_size));
         face *= tone * bulge * (0.85 + 0.3 * stain) * mix(0.75, 1.25, gully) * (1.0 + 0.04 * sheer);
-        face = mix(face, albedo, top * smoothstep(0.35, 0.6, plain.z) * g.green);
+        face = mix(face, albedo, top * smoothstep(0.35, 0.6, plain.z) * g.green * (1.0 - select(0.0, road.wall, MODEL)));
         if (altitude < 16.0) {
             face *= 1.0 - 0.45 * (1.0 - smoothstep(1.0, 4.0, altitude));
             face = mix(face, vec3f(0.42, 0.2, 0.06), 0.28 * smoothstep(3.0, 6.0, altitude) * (1.0 - smoothstep(10.0, 16.0, altitude))
                 * smoothstep(0.45, 0.7, noise(world / 3.0 + altitude / 2.0)));
         }
+        // On the plan path a near face breaks into blocks (rock_near), each lit as a facet as the crags are: the crags
+        // are tens of metres across and calm close by, so a near face showed none. Read last, and only by the near
+        // pipeline (DETAIL): a value kept live through the face costs every pixel of the terrain.
+        if (MODEL && DETAIL && far < NEAR_ROCK_M) {
+            // In the plane of the face as it is lit (plain): the fine normal kept live to here cost every pixel 0.1 ms,
+            // and a wall's own plane passed in 0.09 ms.
+            let k = rock_near(world, altitude, plain, surface_size);
+            let side = normalize(vec3f(-plain.y, plain.x, 0.0) + 1e-6);
+            let lit = 1.0 + 0.9 * dot(side * k.x + cross(plain, side) * k.y, look.sun.xyz) * smoothstep(-0.2, 0.1, dot(plain, look.sun.xyz)) * g.sun;
+            face *= mix(1.0, k.z * lit, 1.0 - smoothstep(0.5 * NEAR_ROCK_M, NEAR_ROCK_M, far));
+        }
         albedo = mix(albedo, face, walled);
     }
     // The snow under the trees stays at every distance; past their reach the crowns that no longer stand
     // hide a share of it. Snow slides off walls, which the data's texels are too wide to see.
     let crowns = g.tree * CROWN_SHARE * smoothstep(0.8 * TREE_REACH_M, TREE_REACH_M, length(relative.xy));
-    let snow = g.snow * (1.0 - crowns) * smoothstep(0.4, 0.6, n.z);
+    let snow = g.snow * (1.0 - crowns) * smoothstep(0.4, 0.6, n.z) * (1.0 - select(0.0, road.wall, MODEL));
     albedo = mix(albedo, rule(region, i32(COVER_SNOW) * 3).rgb, snow) * (1.0 - 0.3 * look.light.w * (1.0 - snow));
     // Rock shows its relief in the smooth light: the bands would light every face toward the sun alike.
-    let c = light_up(albedo, n, sun_share(g.sun, relative, n, LIFT_GROUND), open, mix(look.horizon.w, 0.5, walled));
+    let c = light_spread(albedo, n, sun_share(g.sun, relative, n, LIFT_GROUND), open, mix(look.horizon.w, 0.5, walled), spread);
     return atmosphere(c, relative, altitude);
 }
diff --git a/builder/web/src/lib/trailview/ground/pages.ts b/builder/web/src/lib/trailview/ground/pages.ts
index 198ee23462..d5ca0f18a9 100644
--- a/builder/web/src/lib/trailview/ground/pages.ts
+++ b/builder/web/src/lib/trailview/ground/pages.ts
@@ -26,6 +26,8 @@ const STAY = 0.7;
 const RETRY_MS = 2000, RETRY_MAX_MS = 60_000;
 /** The look at the eye blends the regions at the nodes of this level about it (0.84 km at 47°), with a tent weight of this reach in nodes. */
 const LOOK_LEVEL = 15, LOOK_REACH = 3;
+/** Blocks of 16 × 16 texels a page side, for the regions near a point; a block's word where its texels hold more than one region. */
+const BLOCKS = PAGE / 16, MIXED = 256;
 
 /** The four pages of a ground tile, null where it has no ground; not complete when a layer failed to load. */
 export interface GroundResult { pages: (GroundPage | null)[]; complete: boolean }
@@ -44,8 +46,9 @@ export interface Slot {
     used: number;
     /** The date of the content, or -1 before the first upload. */
     date: number;
-    /** The region of each texel, for the look at the eye. */
+    /** The region of each texel, for the look at the eye, and of each block of texels where they all hold one, else MIXED. */
     regions?: Uint8Array;
+    blocks?: Uint16Array;
     /** A layer of the content failed to load: the page loads again after its tile's wait. */
     partial?: boolean;
 }
@@ -86,6 +89,8 @@ export class GroundPages {
     private readonly failures = new Map();
     private free: number[];
     private frame = 0;
+    /** Counts the arrivals and evictions of pages, so a reader of their regions knows when to read again. */
+    changes = 0;
     private dateKey = '';
     private today = { quarters: [0, 1] as [number, number], weight: 0, band: 0 };
     private loads = 0;
@@ -203,7 +208,13 @@ export class GroundPages {
             page.date = date;
             page.partial = partial;
             page.regions ??= new Uint8Array(PAGE * PAGE);
-            for (let i = 0; i < PAGE * PAGE; i++) page.regions[i] = data.cells[4 * i + 2];
+            const blocks = (page.blocks ??= new Uint16Array(BLOCKS * BLOCKS));
+            for (let i = 0; i < PAGE * PAGE; i++) {
+                // The first texel of a block, in this order, is its top left one.
+                const region = (page.regions[i] = data.cells[4 * i + 2]), b = ((i >> 12) << 4) | ((i & 255) >> 4);
+                blocks[b] = (i & 0xf0f) === 0 || blocks[b] === region ? region : MIXED;
+            }
+            this.changes++;
             this.refresh.delete(page);
             work.uploads.push({ page, data, horizons });
             this.dirty = true;
@@ -226,6 +237,7 @@ export class GroundPages {
     /** A lost device keeps the absent and the failed tiles; every page and the rules come again. */
     lost(): void {
         this.pages.clear();
+        this.changes++;
         this.free = range(this.capacity);
         this.arrivals = [];
         this.loading.clear();
@@ -258,6 +270,26 @@ export class GroundPages {
         return out;
     }
 
+    /**
+     * The regions of the texels of the resident pages within `metres` of a point, across or along, and one texel more: a
+     * point reads its nearest texel.
+     */
+    regionsNear(lon: number, lat: number, metres: number): Set {
+        const [ux, uy] = worldPixel([lon, lat], UNITS), reach = metres / anchorAt(lon, lat).unit, seen = new Uint8Array(256);
+        for (const { node, regions, blocks } of this.pages.values()) {
+            if (!regions || !blocks) continue;
+            const side = size(node.level), texel = side / PAGE, x = ux - node.x * side, y = uy - node.y * side;
+            const i0 = Math.max(0, Math.floor((x - reach) / texel) - 1), i1 = Math.min(PAGE - 1, Math.floor((x + reach) / texel) + 1);
+            const j0 = Math.max(0, Math.floor((y - reach) / texel) - 1), j1 = Math.min(PAGE - 1, Math.floor((y + reach) / texel) + 1);
+            for (let bj = j0 >> 4; i0 <= i1 && bj <= j1 >> 4; bj++) for (let bi = i0 >> 4; bi <= i1 >> 4; bi++) {
+                const block = blocks[bj * BLOCKS + bi];
+                if (block !== MIXED) seen[block] = 1;
+                else for (let j = Math.max(j0, 16 * bj); j <= Math.min(j1, 16 * bj + 15); j++) for (let i = Math.max(i0, 16 * bi); i <= Math.min(i1, 16 * bi + 15); i++) seen[regions[j * PAGE + i]] = 1;
+            }
+        }
+        return new Set([...seen.keys()].filter(region => seen[region]));
+    }
+
     /** The first `n` pages of a set that are still resident; they leave it. */
     private take(set: Set, n: number): Slot[] {
         const pages = [...set].slice(0, n);
@@ -332,6 +364,7 @@ export class GroundPages {
             for (const page of this.pages.values()) if (page.used < this.frame && (!oldest || page.used < oldest.used)) oldest = page;
             if (!oldest) return undefined;
             this.pages.delete(key(oldest.node));
+            this.changes++;
             this.refresh.delete(oldest);
             this.dirty = true;
             slot = oldest.slot;
diff --git a/builder/web/src/lib/trailview/ground/roads.wgsl b/builder/web/src/lib/trailview/ground/roads.wgsl
index f6c515a65f..8166bba170 100644
--- a/builder/web/src/lib/trailview/ground/roads.wgsl
+++ b/builder/web/src/lib/trailview/ground/roads.wgsl
@@ -4,6 +4,11 @@
 // `rule()` and `noise()` of look.wgsl: an include composes each file once.
 // #include ../terrain/features.wgsl
 // #include look.wgsl
+// #include ../roads/look-codes.wgsl
+
+// The look of the one road model (`ground=plan`): the paint and the ground terms of the stamp's textures, as
+// model_road draws them, and the rock of its steep cuts (look.wgsl). The terrain and the pieces set it on that path.
+override MODEL: bool = false;
 
 struct Road {
     colour: vec3f,
@@ -11,13 +16,12 @@ struct Road {
     cover: f32,
     // The share of the ground that shows through the road's paint.
     share: f32,
-    // On a cut or a fill face of a paved road that is a retaining wall: faded as the paint.
+    // On a cut or a fill face of a paved road that is a retaining wall: faded as the paint. On the plan path, where no
+    // road paints a wall, 1 on a piece's wall that stands as rock (wall_rock of roads/corridor.wgsl).
     wall: f32,
     // The share of the ground that a road's or a path's cut or fill shaped: within its reach of the edge.
     shaped: f32,
-    // The share of the ground on a road's cut or fill, whose detail runs up its
-    // face, and on a path's bench, which lights as its hillside does.
-    cuts: f32,
+    // The share of the ground on a path's bench, which lights as its hillside does.
     bench: f32,
 }
 
@@ -30,6 +34,8 @@ const WALL_M: f32 = 5.2;
 const SHAPED_M: f32 = 10.0;
 const PATH_SHAPED_M: f32 = 3.0;
 const PATH_HALF_M: f32 = 1.2;
+// The one road model shapes the ground where its heights moved it from the plain terrain by more than this.
+const MOVED_M: f32 = 0.1;
 // Only a road this wide on each side carries lines.
 const MARKED_HALF_M: f32 = 2.75;
 // A sidewalk's granite kerb: its top, its dark face on the road side and its soft shadow on the road, in metres across.
@@ -48,6 +54,8 @@ const CODE_PATH: u32 = 6u;
 const CODE_ONEWAY: u32 = 7u;
 // Paving lies in square slabs of SLAB_M; their joints show only near the eye.
 const SLAB_M: f32 = 0.6;
+// A track's top narrower than this on each side carries two concrete strips on its own surface.
+const STRIPS_HALF_M: f32 = 2.2;
 
 // The tracks, from RAIL_CODE on as SURFACES of bins.ts: standard and narrow gauge, each without and with
 // a rack. A track painted where nothing counts its sleepers, on a deck or in a bore, takes NO_SLEEPERS
@@ -129,6 +137,38 @@ fn paving(region: u32, p: vec2f, w: f32) -> vec3f {
     return c;
 }
 
+// The share of a pixel `cross_w` metres wide on a track's concrete strips, `across` metres from its middle.
+fn on_strips(across: f32, cross_w: f32) -> f32 {
+    return band(abs(across), 0.48, 1.03, cross_w);
+}
+
+// The broad tones of concrete and of pavers, about 1: their looks in roads/looks.wgsl and material_top share them.
+fn concrete_tone(p: vec2f) -> f32 {
+    return 0.975 + 0.035 * noise(p / 11.0) + 0.02 * noise(p / 43.0 + 7.0);
+}
+
+fn pavers_tone(p: vec2f) -> f32 {
+    return 0.97 + 0.06 * noise(p / 4.0);
+}
+
+// The base colour of a way's top of a material (MATERIAL_ of look-codes.wgsl): the colour of its look in
+// roads/looks.wgsl far off, where its joints and courses fade to their mean. Narrow strips lie on the colour of
+// the way's code.
+fn material_top(region: u32, material: u32, code: u32, across: f32, half: f32, p: vec2f, cross_w: f32) -> vec3f {
+    if (material == MATERIAL_SETT) {
+        return rule(region, slot_setts()).rgb;
+    }
+    if (material == MATERIAL_PAVERS) {
+        return rule(region, slot_roads() + i32(PAVING_CODE) - 1).rgb * pavers_tone(p);
+    }
+    let tone = concrete_tone(p);
+    let concrete = rule(region, slot_concrete()).rgb * tone;
+    if (material == MATERIAL_STRIPS && half <= STRIPS_HALF_M) {
+        return mix(rule(region, slot_roads() + i32(code) - 1).rgb * tone, concrete, on_strips(across, cross_w));
+    }
+    return concrete;
+}
+
 // A road's surface with its sidewalk, `walk` metres wide past its edge, at `edge` metres out from the edge:
 // the paving, a granite kerb at the edge with its dark face on the road side, and its shadow on the road.
 fn kerbed(region: u32, road: vec3f, edge: f32, walk: f32, p: vec2f, w: f32, cross_w: f32) -> vec3f {
@@ -202,19 +242,21 @@ fn masonry(stone: vec3f, along: f32, altitude: f32, w: f32) -> vec3f {
 // normal of the drawn triangle.
 fn road_at(s: vec2f, ds: mat2x2f, p: vec2f, w: f32, distance: f32, region: u32, pixel: vec2f, flat: f32) -> Road {
     if (!DETAIL) {
-        return Road(vec3f(0.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+        return Road(vec3f(0.0), 0.0, 0.0, 0.0, 0.0, 0.0);
+    }
+    if (MODEL) {
+        return model_road(s, ds, p, w, distance, region, pixel, flat);
     }
     let level = lod(s);
     let reach = (1.0 - smoothstep(0.75 * masks.reach, masks.reach, distance)) * smoothstep(f32(MASK_LEVEL) - 1.0, f32(MASK_LEVEL) - 0.5, level);
     if (reach <= 0.0) {
-        return Road(vec3f(0.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+        return Road(vec3f(0.0), 0.0, 0.0, 0.0, 0.0, 0.0);
     }
     let mask = mask_at(s, u32(ceil(level)), true);
     if (mask.level == 0u || mask.kind.x == 0u) {
-        return Road(vec3f(0.0), 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+        return Road(vec3f(0.0), 0.0, 0.0, 0.0, 0.0, 0.0);
     }
     let code = mask.kind.x;
-    let paved = code <= 2u || code == 7u || code == PAVING_CODE;
     // The paint and the road's cut and fill reach past its sidewalk on this side.
     let walk = mask.walk;
     // A wall stands under a road's or a track's paint, never under a footway's paving. Inside
@@ -226,16 +268,28 @@ fn road_at(s: vec2f, ds: mat2x2f, p: vec2f, w: f32, distance: f32, region: u32,
         let out = mask_at(s + mask.away * (WALL_M + walk - mask.edge), mask.level, false);
         wall *= out.face;
     }
-    var edge = mask.edge;
+    let edge = mask.edge;
     let half = max(mask.half, 0.05);
     let shaped_m = select(SHAPED_M, PATH_SHAPED_M, half < PATH_HALF_M);
     let shaped = reach * (1.0 - smoothstep(0.75 * shaped_m, shaped_m, edge - walk));
-    let cuts = select(0.0, shaped, half >= PATH_HALF_M);
     // The bench reaches a metre past the edge: the band and a texel of the heights about it.
     let bench = select(0.0, reach * (1.0 - smoothstep(0.75, 1.25, edge)), half < PATH_HALF_M);
-    if (edge - walk > w + 0.5) {
-        return Road(vec3f(0.0), 0.0, 0.0, wall, shaped, cuts, bench);
+    return mask_paint(mask, 0u, ds, p, w, distance, region, pixel, flat, reach, vec3f(wall, shaped, bench));
+}
+
+// The paint of the road that a mask holds at a point, its top of `material` (0 for its finish's own), over the ground
+// terms (wall, shaped, bench), faded by `reach`.
+fn mask_paint(mask: Mask, material: u32, ds: mat2x2f, p: vec2f, w: f32, distance: f32, region: u32, pixel: vec2f, flat: f32, reach: f32, ground: vec3f) -> Road {
+    var edge = mask.edge;
+    let walk = mask.walk;
+    if (mask.kind.x == 0u || edge - walk > w + 0.5) {
+        return Road(vec3f(0.0), 0.0, 0.0, ground.x, ground.y, ground.z);
     }
+    let code = mask.kind.x;
+    // As line_look: a track and paving keep their own looks, and a top of a material is paved whatever its code.
+    let top = select(material, 0u, code == PAVING_CODE || code >= RAIL_CODE);
+    let paved = code <= 2u || code == 7u || code == PAVING_CODE || top != 0u;
+    let half = max(mask.half, 0.05);
     let across = abs(mask.across);
     // The pixel's span across the road: far off, a pixel is long along the view and narrow across it,
     // so the lines of a road that runs away from the eye stay sharp.
@@ -244,7 +298,10 @@ fn road_at(s: vec2f, ds: mat2x2f, p: vec2f, w: f32, distance: f32, region: u32,
     let ahead = vec2f(-mask.axis.y, mask.axis.x);
     let along_w = select(w, max(length(vec2f(dot(ds[0], ahead), dot(ds[1], ahead))), 1e-3), known);
     var surface = road_surface(region, code, max(-edge, 0.0), across, half, select(NO_SLEEPERS, mask.sleepers, code >= RAIL_CODE), p, w, cross_w, along_w, mask.marked);
-    if (code >= CODE_DIRT && code <= CODE_PATH) {
+    if (top != 0u) {
+        surface = vec4f(material_top(region, top, code, across, half, p, cross_w), 0.0);
+    }
+    if (code >= CODE_DIRT && code <= CODE_PATH && !paved) {
         surface.w = mix(surface.w, ground_mean(code, half, mask.trodden), smoothstep(0.1, 0.4, cross_w));
     }
     if (walk > 0.0) {
@@ -262,5 +319,46 @@ fn road_at(s: vec2f, ds: mat2x2f, p: vec2f, w: f32, distance: f32, region: u32,
     // A triangle that rises over a sidewalk's edge would carry its paint up the cut: a corridor draws the sidewalk.
     let riding = edge > 0.0 && flat < 0.86 && !paint_draws(distance, pixel);
     let cover = select(1.0, 0.0, corridor || riding) * (1.0 - smoothstep(-cross_w, cross_w, edge - walk - thin)) * min(1.0, 2.0 * half / cross_w + 0.35) * reach;
-    return Road(surface.rgb, cover, surface.w, wall, shaped, cuts, bench);
+    return Road(surface.rgb, cover, surface.w, ground.x, ground.y, ground.z);
+}
+
+// The road of the one road model: the paint of the stamp's paint texture, which holds the paved labels as
+// the mask holds a road, over the ground terms (model_ground). The paint and the ground terms fade out before
+// the reach of the mask pool, as road_at's.
+fn model_road(s: vec2f, ds: mat2x2f, p: vec2f, w: f32, distance: f32, region: u32, pixel: vec2f, flat: f32) -> Road {
+    let level = lod(s);
+    let reach = model_reach(level, distance);
+    if (reach <= 0.0) {
+        return Road(vec3f(0.0), 0.0, 0.0, 0.0, 0.0, 0.0);
+    }
+    let mask = mask_at(s, u32(ceil(level)), true);
+    let ground = reach * model_ground(s, u32(ceil(level)), mask);
+    // The core holds the paved area, so no paint reaches a point whose core lies farther than mask_paint's reach.
+    if (mask.level == 0u || mask.kind.x == 0u || mask.edge > w + 0.5) {
+        return Road(vec3f(0.0), 0.0, 0.0, ground.x, ground.y, ground.z);
+    }
+    // Its `kind.y` is the material of the way's top, not flags (Mask).
+    let paint = mask_in(paint_texels, s, mask.level, mask.page, true);
+    return mask_paint(paint, paint.kind.y, ds, p, w, distance, region, pixel, flat, reach, ground);
+}
+
+// The share of the one road model's look at a LOD and a distance: it fades out before the reach of the mask pool.
+fn model_reach(level: f32, distance: f32) -> f32 {
+    return (1.0 - smoothstep(0.75 * masks.reach, masks.reach, distance)) * smoothstep(f32(MASK_LEVEL) - 1.0, f32(MASK_LEVEL) - 0.5, level);
+}
+
+// The one road model's ground terms: wall (none: the records set no wall flag), shaped ground, bench.
+// The ground is shaped (plants as the satellite sees them) where the heights moved it from the plain terrain
+// by more than MOVED_M; `edge` is the metres past the core edge of the nearest way and `half` its half-width.
+// A path's bench is road_at's, within a path's reach.
+fn ground_terms(moved: f32, edge: f32, half: f32) -> vec3f {
+    let shaped = smoothstep(0.5 * MOVED_M, 1.5 * MOVED_M, moved);
+    let path = half < PATH_HALF_M && edge < PATH_SHAPED_M;
+    return vec3f(0.0, shaped, select(0.0, 1.0 - smoothstep(0.75, 1.25, edge), path));
+}
+
+// The ground terms at a point, the nearest way from the feature mask.
+fn model_ground(s: vec2f, top: u32, mask: Mask) -> vec3f {
+    let known = mask.level != 0u && mask.kind.x != 0u;
+    return ground_terms(moved_at(s, top), select(MASK_M, mask.edge, known), select(MASK_M, mask.half, known));
 }
diff --git a/builder/web/src/lib/trailview/hud.ts b/builder/web/src/lib/trailview/hud.ts
index 62d260665e..6942f1aca7 100644
--- a/builder/web/src/lib/trailview/hud.ts
+++ b/builder/web/src/lib/trailview/hud.ts
@@ -1,6 +1,7 @@
 import type { TrailView } from './engine';
 import { dayOfYear } from './ground/rules';
-import { DEBUG_VIEWS, type DebugView } from './view';
+import type { PlanStats } from './plan/plan';
+import { DEBUG_VIEWS, PLAN_VIEWS, type DebugView, type PlanView } from './view';
 
 const REFRESH_MS = 250;
 /** A new date builds the ground again, so the date slider takes effect once it rests this long after a change: a step of an arrow key is a change. */
@@ -8,7 +9,7 @@ const DATE_REST_MS = 400;
 
 /**
  * The HUD: the GPU time of a frame and its passes, the date and the time of day, the debug view, and
- * a line for what goes wrong. H hides it.
+ * a line for what goes wrong. With `ground=plan`, a line of the ground plan and its debug draw. H hides it.
  */
 export function hud(element: HTMLElement, engine: TrailView): void {
     const text = document.createElement('pre');
@@ -31,7 +32,14 @@ export function hud(element: HTMLElement, engine: TrailView): void {
     // A control that the pointer used gives the keys back to the eye (controls.ts).
     for (const range of [date, time]) range.addEventListener('pointerup', () => range.blur());
     debug.addEventListener('change', () => debug.blur());
-    element.replaceChildren(text, date.parentElement!, time.parentElement!, debug);
+    const plan = document.createElement('select');
+    plan.setAttribute('aria-label', 'Plan view');
+    for (const view of PLAN_VIEWS) plan.add(new Option(`plan: ${view}`, view));
+    plan.addEventListener('change', () => {
+        engine.view = { ...engine.view, plan: plan.value as PlanView };
+        plan.blur();
+    });
+    element.replaceChildren(text, date.parentElement!, time.parentElement!, debug, ...(engine.groundPlan ? [plan] : []));
     addEventListener('keydown', event => {
         if (event.key.toLowerCase() === 'h' && !event.ctrlKey && !event.metaKey) element.hidden = !element.hidden;
     });
@@ -40,6 +48,7 @@ export function hud(element: HTMLElement, engine: TrailView): void {
         if (!element.checkVisibility()) return;
         const stats = engine.stats(), view = engine.view, passes = Object.entries(stats.gpu);
         debug.value = view.debug;
+        plan.value = view.plan;
         if (document.activeElement !== date && resting === undefined) [date.valueAsNumber, dateLabel.textContent] = [dayOfYear(view.date), view.date];
         if (document.activeElement !== time) [time.valueAsNumber, timeLabel.textContent] = [Number(view.time.slice(0, 2)) * 60 + Number(view.time.slice(3, 5)), view.time];
         const frame = passes.reduce((sum, [, ms]) => sum + ms, 0);
@@ -48,11 +57,17 @@ export function hud(element: HTMLElement, engine: TrailView): void {
             stats.failed && `${stats.failed} requests failed`,
             stats.ground.shortage && `${stats.ground.shortage} ground pages short`,
             stats.instances.dropped && `${stats.instances.dropped} instances dropped`,
-            stats.terrain.quality < 0 && `terrain quality ${stats.terrain.quality}`,
+            stats.terrain.stampLimits && `${stats.terrain.stampLimits} stamp limits hit`,
+            stats.terrain.quality > 0 && `terrain quality ${stats.terrain.quality} steps coarser`,
+            stats.terrain.left.some(Boolean) && `terrain pages left out: ${stats.terrain.left.flatMap((pages, level) => (pages ? [`L${level} ${pages}`] : [])).reverse().join(' · ')}`,
+            stats.terrain.records?.error && `records: ${stats.terrain.records.error}`,
+            stats.plan?.error && `plan: ${stats.plan.error}`,
+            stats.plan?.unfilled && `plan: ${stats.plan.unfilled} faces unfilled`,
         ].filter(Boolean);
         text.textContent = [
             passes.length ? `frame ${frame.toFixed(2)} ms GPU ≈ ${Math.round(1000 / frame)} fps · cpu ${stats.cpu.toFixed(2)} ms` : 'no timestamp queries',
             passes.map(([pass, ms]) => `${pass} ${ms.toFixed(2)}`).join(' · '),
+            ...(stats.plan ? [planLine(stats.plan)] : []),
             ...(problems.length ? [`! ${problems.join(' · ')}`] : []),
             'W A S D move · drag to look · F walk or fly · wheel altitude · Ctrl+C / Ctrl+V view · H HUD',
         ].join('\n');
@@ -61,6 +76,12 @@ export function hud(element: HTMLElement, engine: TrailView): void {
     setInterval(update, REFRESH_MS);
 }
 
+/** `plan 14 cells · 1 building · 0 failed · 0 restarts · build 82 ms (input 2 · graph 16 · faces 64) · prepare 9 ms · ready 1240 ms · heap 31 MiB` */
+function planLine({ cells, building, failed, restarts, build, ready, heap }: PlanStats): string {
+    const stages = Object.entries(build.stages).map(([stage, ms]) => `${stage} ${ms.toFixed(0)}`).join(' · ');
+    return `plan ${cells} cells · ${building} building · ${failed} failed · ${restarts} restarts · build ${build.median.toFixed(0)} ms (${stages}) · prepare ${build.prepare.toFixed(0)} ms · ready ${ready.toFixed(0)} ms · heap ${(heap / 2 ** 20).toFixed(0)} MiB`;
+}
+
 /** A labelled range input, and the label's value text. */
 function slider(name: string, min: number, max: number, step: number): [HTMLInputElement, HTMLSpanElement] {
     const label = document.createElement('label'), input = document.createElement('input'), value = document.createElement('span');
diff --git a/builder/web/src/lib/trailview/instances/instances.ts b/builder/web/src/lib/trailview/instances/instances.ts
index 58d0cbdecb..7cb57c6835 100644
--- a/builder/web/src/lib/trailview/instances/instances.ts
+++ b/builder/web/src/lib/trailview/instances/instances.ts
@@ -191,6 +191,10 @@ export class Instances {
     private readonly sunTally: number[][] = [];
     private quad: [number, number, number] = [0, 0, 0];
     private uploaded = false;
+    /** Where each mesh lies in the pools since an upload wrote it, and the first free vertex and index. */
+    private pool = emptyPool();
+    /** Per model, the mesh and the record of its last baked impostor: it bakes again when either changes. */
+    private readonly baked = new Map();
     private detail_ = 1;
     /** The factor of the tier distances in the last frame. */
     private lod = 1;
@@ -283,6 +287,8 @@ export class Instances {
         this.uploaded = false;
         this.atlas.clear();
         this.unbaked.clear();
+        this.pool = emptyPool();
+        this.baked.clear();
         const { device } = gpu, p = await gpu.once(instancePipelines);
         const storage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, uniform = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
         const atlas = () => gpu.texture('instances', {
@@ -576,53 +582,61 @@ export class Instances {
         return made;
     }
 
-    /** Writes the models and their meshes into the pools; every impostor bakes again. */
-    private upload(r: Resources): void {
+    /**
+     * Writes the models into the pools. A mesh stays where an earlier upload wrote it, so an upload writes only
+     * the meshes that are new; a model that finds no room packs the pools again from empty, without the meshes
+     * that no model draws any more. A model's impostor bakes again when its mesh or its record changed.
+     */
+    private upload(r: Resources, packed = false): void {
         const models = new ArrayBuffer(MODELS * MODEL_BYTES), f = new Float32Array(models);
-        const meshes = new Int32Array(DRAWS * MESH_BYTES / 4);
-        let vertex = 0, index = 0;
+        const meshes = new Int32Array(DRAWS * MESH_BYTES / 4), pool = this.pool;
         const fits = (tiers: Mesh[]) => {
             const count = tiers.reduce((sum, mesh) => sum + mesh.position.length / 3, 0), indices = tiers.reduce((sum, mesh) => sum + mesh.index.length, 0);
-            return (vertex + count) * VERTEX_BYTES <= VERTEX_POOL && (index + indices) * 4 <= INDEX_POOL;
+            return (pool.vertex + count) * VERTEX_BYTES <= VERTEX_POOL && (pool.index + indices) * 4 <= INDEX_POOL;
         };
+        // A mesh that models share, such as a tree as a tree and as a shrub, lies once in the pools.
         const put = (mesh: Mesh, extent: number): [number, number, number] => {
+            const known = pool.at.get(mesh);
+            if (known?.extent === extent) return known.at;
             const count = mesh.position.length / 3;
-            r.gpu.device.queue.writeBuffer(r.vertices, vertex * VERTEX_BYTES, quantize(mesh, extent));
-            r.gpu.device.queue.writeBuffer(r.indices, index * 4, Uint32Array.from(mesh.index));
-            const at: [number, number, number] = [index, mesh.index.length, vertex];
-            vertex += count;
-            index += mesh.index.length;
+            r.gpu.device.queue.writeBuffer(r.vertices, pool.vertex * VERTEX_BYTES, quantize(mesh, extent));
+            r.gpu.device.queue.writeBuffer(r.indices, pool.index * 4, Uint32Array.from(mesh.index));
+            const at: [number, number, number] = [pool.index, mesh.index.length, pool.vertex];
+            pool.vertex += count;
+            pool.index += mesh.index.length;
+            pool.at.set(mesh, { extent, at });
             return at;
         };
         this.quad = put(QUAD, 1);
-        // A mesh that models share, such as a tree as a tree and as a shrub, lies once in the pools.
-        const shared = new Map();
-        const putOnce = (mesh: Mesh, extent: number) => {
-            const known = shared.get(mesh);
-            if (known?.extent === extent) return known.at;
-            const at = put(mesh, extent);
-            shared.set(mesh, { extent, at });
-            return at;
-        };
         const dropped: number[] = [];
+        // The meshes that an upload writes: those that the pools do not hold at this extent.
+        const room = (meshes: Mesh[], extent: number) => fits(meshes.filter(mesh => pool.at.get(mesh)?.extent !== extent));
         this.placed = this.specs.map((spec, m) => {
             const { tiers } = spec;
             if (!tiers.length) return [];
-            if (!fits(tiers.map(({ mesh }) => mesh).filter(mesh => !shared.has(mesh)))) return void dropped.push(m), [];
-            const extent = Math.max(...tiers.map(({ mesh }) => largest(mesh.position)));
+            const extent = Math.max(...tiers.map(({ mesh }) => scan(mesh).largest));
+            if (!room(tiers.map(({ mesh }) => mesh), extent)) return void dropped.push(m), [];
             const placed = tiers.map(({ mesh, until }, t) => {
-                const at = putOnce(mesh, extent);
+                const at = put(mesh, extent);
                 meshes.set([at[1], at[0], at[2], 0], (m * TIERS + t) * 4);
                 f[m * 20 + t] = until;
                 return at;
             });
+            if (spec.impostor) f[m * 20 + tiers.length] = spec.impostor.until;
+            f.set([extent, radius(spec), spec.fade ?? 0.15, spread(spec), spec.crown ?? -1, tiers.some(({ mesh }) => mesh.trunk) ? 1 : 0, spec.tie ?? 0, spec.sized ?? 0, ...sinks(spec)], m * 20 + 4);
             if (spec.impostor) {
-                f[m * 20 + tiers.length] = spec.impostor.until;
-                if (this.atlas.has(m)) this.unbaked.add(m);
+                const mesh = tiers[spec.impostor.from].mesh, record = f.slice(m * 20, m * 20 + 20), last = this.baked.get(m);
+                if (last?.mesh !== mesh || !last.record.every((value, i) => Object.is(value, record[i]))) {
+                    this.baked.set(m, { mesh, record });
+                    if (this.atlas.has(m)) this.unbaked.add(m);
+                }
             }
-            f.set([extent, radius(spec), spec.fade ?? 0.15, spread(spec), spec.crown ?? -1, tiers.some(({ mesh }) => mesh.trunk) ? 1 : 0, spec.tie ?? 0, spec.sized ?? 0, ...sinks(spec)], m * 20 + 4);
             return placed;
         });
+        if (dropped.length && !packed) {
+            this.pool = emptyPool();
+            return this.upload(r, true);
+        }
         // A model that does not fit the pools draws nothing; the frames go on.
         if (dropped.length) console.warn(`The instance meshes of ${dropped.length} models do not fit their pools.`);
         r.gpu.device.queue.writeBuffer(r.models, 0, models);
@@ -642,13 +656,21 @@ export class Instances {
         this.meshTable = meshes;
         r.gpu.device.queue.writeBuffer(r.meshes, 0, meshes);
         const coarse = meshes.slice(), proxies = meshes.slice();
+        let hullless = false;
         this.specs.forEach((spec, m) => {
             const coarsest = this.placed[m].at(-1);
             if (!coarsest) return;
             if (spec.impostor) coarse.set([coarsest[1], coarsest[0], coarsest[2], 0], (m * TIERS + spec.tiers.length) * 4);
-            const hull = proxy(spec.tiers.at(-1)!.mesh), at = hull && fits([hull]) ? put(hull, f[m * 20 + 4]) : coarsest;
+            const hull = scan(spec.tiers.at(-1)!.mesh).proxy, fitted = hull && room([hull], f[m * 20 + 4]);
+            hullless ||= !!hull && !fitted;
+            const at = fitted ? put(hull, f[m * 20 + 4]) : coarsest;
             for (let t = 0; t < TIERS; t++) proxies.set([at[1], at[0], at[2], 0], (m * TIERS + t) * 4);
         });
+        // A shadow proxy without room packs the pools once too, as a model without room does.
+        if (hullless && !packed) {
+            this.pool = emptyPool();
+            return this.upload(r, true);
+        }
         this.casterTables = [coarse, proxies];
         this.uploaded = true;
     }
@@ -781,9 +803,27 @@ function largest(values: ArrayLike): number {
 
 /** The radius of a sphere about (0, 0, 0.5) that holds every mesh of a model, in model units; a sized plant may stand taller than 1. */
 function radius(spec: ModelSpec): number {
-    let most = 0;
-    for (const { mesh: { position: p } } of spec.tiers) for (let i = 0; i < p.length; i += 3) most = Math.max(most, Math.hypot(p[i], p[i + 1], p[i + 2] - 0.5));
-    return most;
+    return Math.max(0, ...spec.tiers.map(({ mesh }) => scan(mesh).radius));
+}
+
+/** A pool keyed weakly: a mesh that no model draws any more does not stay in memory for the pool's sake. */
+const emptyPool = () => ({ at: new WeakMap(), vertex: 0, index: 0 });
+
+/** What an upload reads of a mesh, made once per mesh: a mesh does not change once made. */
+const scans = new WeakMap();
+
+function scan(mesh: Mesh): { largest: number; radius: number; spread: number; proxy?: Mesh } {
+    let known = scans.get(mesh);
+    if (!known) {
+        const p = mesh.position;
+        let most = 0, spread = 0;
+        for (let i = 0; i < p.length; i += 3) {
+            most = Math.max(most, Math.hypot(p[i], p[i + 1], p[i + 2] - 0.5));
+            spread = Math.max(spread, Math.hypot(p[i], p[i + 1]));
+        }
+        scans.set(mesh, (known = { largest: largest(p), radius: most, spread, proxy: proxy(mesh) }));
+    }
+    return known;
 }
 
 /**
@@ -840,9 +880,7 @@ export function outlines(mesh: Mesh, radius: number): Float32Array
 
 /** The farthest that a vertex of a model lies from its axis. */
 function spread(spec: ModelSpec): number {
-    let most = 0;
-    for (const { mesh: { position: p } } of spec.tiers) for (let i = 0; i < p.length; i += 3) most = Math.max(most, Math.hypot(p[i], p[i + 1]));
-    return most;
+    return Math.max(0, ...spec.tiers.map(({ mesh }) => scan(mesh).spread));
 }
 
 /**
diff --git a/builder/web/src/lib/trailview/kinds/building.ts b/builder/web/src/lib/trailview/kinds/building.ts
deleted file mode 100644
index c4fa25a87f..0000000000
--- a/builder/web/src/lib/trailview/kinds/building.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-// Buildings show their use, which the bake gives them (specs/trailview-features.md): a sign at the corner of the
-// wall that faces the nearest way. The houses draw the buildings themselves.
-import { hospitalSign, pharmacySign, shopSign } from '../models/amenities';
-import { SKIPPED } from '../structures/house-records';
-import { metresPerUnit } from '../terrain/bins';
-import { coreAt } from '../roads/cores';
-import { nearestWay, unitModel, type Kind } from './kind';
-
-/**
- * A sign hangs on a wall at least WALL_M long, CORNER_M from its corner nearer the way: closer than a
- * window or a shutter of any house of houses.wgsl comes to it, and far from the door in the wall's
- * middle. It draws to REACH_M.
- */
-const WALL_M = 2.5, CORNER_M = 0.12, REACH_M = 500;
-/** A sign stands this far out from its wall. */
-const OFF_WALL_M = 0.1;
-const SIGNS = { shop: unitModel(shopSign, REACH_M), pharmacy: unitModel(pharmacySign, REACH_M), hospital: unitModel(hospitalSign, REACH_M) };
-
-export default {
-    build({ tags, parts }, out) {
-        const sign = SIGNS[tags.use as keyof typeof SIGNS], ring = parts.find(part => part.outer)?.xy;
-        if (!sign || !ring || ring.length < 6 || SKIPPED.has(tags.building)) return;
-        // The node that owns the sign's corner places it: the others need not look for the way.
-        const n = ring.length / 2, unit = metresPerUnit(ring[1]);
-        if (!ring.some((_, i) => i % 2 === 0 && out.owns(ring[i], ring[i + 1]))) return;
-        // A wall's outside is (dy, −dx) along it when the ring's signed area is positive, else the other side.
-        let twice = 0;
-        for (let i = 0; i < n; i++) {
-            const j = (i + 1) % n;
-            twice += (ring[2 * i] - ring[0]) * (ring[2 * j + 1] - ring[1]) - (ring[2 * j] - ring[0]) * (ring[2 * i + 1] - ring[1]);
-        }
-        const side = twice > 0 ? 1 : -1;
-        // The wall nearest a way, else the longest.
-        let best: { corner: [number, number]; x: number; y: number; ox: number; oy: number; score: number } | undefined;
-        for (let i = 0; i < n; i++) {
-            const ax = ring[2 * i], ay = ring[2 * i + 1], bx = ring[(2 * i + 2) % ring.length], by = ring[(2 * i + 3) % ring.length];
-            const length = Math.hypot(bx - ax, by - ay);
-            if (length * unit < WALL_M) continue;
-            const mx = (ax + bx) / 2, my = (ay + by) / 2, way = nearestWay(out.ways, mx, my);
-            const score = way ? Math.hypot(way.px, way.py) * unit : 1e6 - length * unit;
-            if (best && score >= best.score) continue;
-            // The corner nearer the way, and CORNER_M from it along the wall.
-            const [wx, wy] = way ? [mx + way.px, my + way.py] : [ax, ay], fromA = Math.hypot(wx - ax, wy - ay) <= Math.hypot(wx - bx, wy - by);
-            const corner: [number, number] = fromA ? [ax, ay] : [bx, by], along = (fromA ? 1 : -1) * CORNER_M / unit / length;
-            const ox = side * (by - ay) / length, oy = -side * (bx - ax) / length;
-            const x = corner[0] + (bx - ax) * along + ox * OFF_WALL_M / unit, y = corner[1] + (by - ay) * along + oy * OFF_WALL_M / unit;
-            // A wall that stands in a way's core or a junction's corner takes no sign: the way draws over its foot.
-            if (coreAt(out.cores, x, y) || out.cornered(x, y)) continue;
-            best = { corner, x, y, ox, oy, score };
-        }
-        if (!best || !out.owns(...best.corner)) return;
-        out.place({ x: best.x, y: best.y, yaw: Math.atan2(best.ox, best.oy), height: sign.height, model: tags.use });
-    },
-    models: Object.fromEntries(Object.entries(SIGNS).map(([name, { spec }]) => [name, spec])),
-} satisfies Kind;
diff --git a/builder/web/src/lib/trailview/kinds/kind.test.ts b/builder/web/src/lib/trailview/kinds/kind.test.ts
index ed6ec54eda..f91cc886aa 100644
--- a/builder/web/src/lib/trailview/kinds/kind.test.ts
+++ b/builder/web/src/lib/trailview/kinds/kind.test.ts
@@ -11,6 +11,9 @@ import { streetLamps } from '../roads/lamps';
 import { BRIDGE, metresPerUnit, PROFILES, RAIL, ROAD, TUNNEL, type Line, type Shapes } from '../terrain/bins';
 import { RIGHT } from '../terrain/town';
 
+/** The shapes of a tile with these lines and buildings alone. */
+const tileOf = (lines: Line[], buildings: unknown[] = []) => ({ lines, lakes: [], seas: [], pads: [], areas: [], buildings }) as unknown as Shapes;
+
 describe('kinds', () => {
     it('draws only kinds of the table', () => {
         const names = new Set(TABLE.map(entry => entry.kind));
@@ -40,13 +43,13 @@ describe('kinds', () => {
     });
 
     it('stands a model along the nearest way within reach, its front toward it', () => {
-        const y = 2 ** 29, m = 1 / metresPerUnit(y), way = (xy: number[]) => ({ xy }) as Line;
+        const y = 2 ** 29, m = 1 / metresPerUnit(y), way = (xy: number[]) => ({ kind: ROAD, xy, h: 2.5 }) as Line;
         // An east–west way 5 m south of the point (world y runs south), and one 8 m north.
         const ways = [way([-50 * m, y + 5 * m, 50 * m, y + 5 * m]), way([-50 * m, y - 8 * m, 50 * m, y - 8 * m])];
         const front = (yaw: number) => [Math.sin(yaw), -Math.cos(yaw)].map(v => Math.round(v * 1e6) / 1e6 + 0);
-        expect(front(facing(ways, 0, y)!)).toEqual([0, -1]);
-        expect(front(facing(ways.slice(1), 0, y)!)).toEqual([0, 1]);
-        expect(facing([way([-50 * m, y + 20 * m, 50 * m, y + 20 * m])], 0, y)).toBeUndefined();
+        expect(front(facing(tileOf(ways), 0, y)!)).toEqual([0, -1]);
+        expect(front(facing(tileOf(ways.slice(1)), 0, y)!)).toEqual([0, 1]);
+        expect(facing(tileOf([way([-50 * m, y + 20 * m, 50 * m, y + 20 * m])]), 0, y)).toBeUndefined();
     });
 
     describe('a model at a point keeps out of the ways', () => {
@@ -56,8 +59,8 @@ describe('kinds', () => {
         const road = (xy: number[]) => ({ kind: ROAD, xy, z: xy.filter((_, i) => i % 2 === 0).map(() => 0), h: 2.5, code: 2, ford: false, profile: 0 }) as Line;
         const EDGE = 2.9, ROOM = EDGE + 0.35, STEP = 0.1;
         const stand = (kind: string, lines: Line[], x: number, at: number, { cornered = (() => false) as Build['cornered'], buildings = [] as Shapes['buildings'] } = {}) => {
-            const placed: Placement[] = [], shapes = { lines, lakes: [], seas: [], areas: [], buildings } as unknown as Shapes;
-            const out = { owns: () => true, place: (p: Placement) => placed.push(p), ways: lines, cores: coresOf(shapes), taken: [], cornered } as unknown as Build;
+            const placed: Placement[] = [], shapes = tileOf(lines, buildings);
+            const out = { owns: () => true, place: (p: Placement) => placed.push(p), shapes, cores: coresOf(shapes), taken: [], cornered } as unknown as Build;
             KINDS.get(kind)!.build({ tags: {}, parts: [{ outer: false, xy: [x, at] }] }, out);
             return placed[0];
         };
@@ -126,8 +129,8 @@ describe('kinds', () => {
         });
 
         it('a moved model keeps clear of a model that the node placed before', () => {
-            const placed: Placement[] = [], shapes = { lines: east, lakes: [], seas: [], areas: [], buildings: [] } as unknown as Shapes;
-            const out = { owns: () => true, place: (p: Placement) => placed.push(p), ways: east, cores: coresOf(shapes), taken: [], cornered: () => false } as unknown as Build;
+            const placed: Placement[] = [], shapes = tileOf(east);
+            const out = { owns: () => true, place: (p: Placement) => placed.push(p), shapes, cores: coresOf(shapes), taken: [], cornered: () => false } as unknown as Build;
             for (const kind of ['bench', 'drinking-water']) KINDS.get(kind)!.build({ tags: {}, parts: [{ outer: false, xy: [0, y + m] }] }, out);
             // The bench reaches 0.8 m along its seat.
             expect(Math.hypot(placed[0].x - placed[1].x, placed[0].y - placed[1].y) / m).toBeGreaterThan(0.8);
@@ -155,7 +158,7 @@ describe('kinds', () => {
         const main = road([0, y, 112 * m, y, 320 * m, y], { sidewalks: [RIGHT, RIGHT] }), house = { rings: [[0, y - 10 * m, 100 * m, y - 10 * m, 100 * m, y - 20 * m]], outer: [true] };
         const places = (lines: Line[], { buildings = [house] as unknown[], cornered = (() => false) as (x: number, y: number) => boolean } = {}) => {
             const placed: Placement[] = [];
-            streetLamps({ owns: () => true, place: p => placed.push(p), buildings, cornered } as Parameters[0], lines);
+            streetLamps({ owns: () => true, place: p => placed.push(p), shapes: tileOf(lines, buildings), cornered });
             return placed;
         };
         const along = (lines: Line[], others?: Parameters[1]) => places(lines, others).map(p => Math.round(p.x / m));
diff --git a/builder/web/src/lib/trailview/kinds/kind.ts b/builder/web/src/lib/trailview/kinds/kind.ts
index 3945fb4a2d..da7ad492a0 100644
--- a/builder/web/src/lib/trailview/kinds/kind.ts
+++ b/builder/web/src/lib/trailview/kinds/kind.ts
@@ -8,7 +8,7 @@ import type { AnchoredBuilder } from '../structures/anchored';
 import { GROUND, mix, type MeshBuilder, station, type Corner } from '../structures/mesh';
 import type { Light } from '../structures/light-pools';
 import type { Owns } from '../structures/node';
-import { metresPerUnit, type Line, type Node, type Shapes } from '../terrain/bins';
+import { linesNear, metresPerUnit, PATH, ROAD, type Line, type Node, type Shapes } from '../terrain/bins';
 import { besideWays, type Beside, type Cores, type Stand, type Taken } from '../roads/cores';
 
 /**
@@ -38,13 +38,12 @@ export interface Build {
     near: { mesh: MeshBuilder; anchored: AnchoredBuilder };
     place: (placement: Placement) => void;
     owns: Owns;
-    /** The roads and paths of the tile, and its buildings' rings. */
-    ways: Line[];
+    /** The shapes of the tile: a model faces the nearest of its roads and paths, and a lamp keeps off its buildings. */
+    shapes: Shapes;
     /** The ground that the models at points keep out of: the ways' cores, the water and the buildings. */
     cores: Cores;
     /** The models at points that the node placed, which a moved model keeps clear of. */
     taken: Taken[];
-    buildings: Shapes['buildings'];
     /** Whether a point lies in a junction's corner, which paints its asphalt and its sidewalk. */
     cornered: (x: number, y: number) => boolean;
 }
@@ -88,25 +87,30 @@ export function halfDepth(model: Model, facesWay: boolean): number {
 /** A model faces the nearest way within this many metres. */
 const FACE_M = 15;
 
-/** The nearest of `ways` within FACE_M of world point x, y: its line, its unit direction there and the offset to it, in world units. */
-export function nearestWay(ways: Line[], x: number, y: number): { line: Line; v: number; dx: number; dy: number; px: number; py: number } | undefined {
-    let best = (FACE_M / metresPerUnit(y)) ** 2, way: ReturnType;
-    for (const line of ways) for (let i = 0; i + 3 < line.xy.length; i += 2) {
-        const ax = line.xy[i], ay = line.xy[i + 1], dx = line.xy[i + 2] - ax, dy = line.xy[i + 3] - ay, l = dx * dx + dy * dy;
-        const t = l ? Math.min(1, Math.max(0, ((x - ax) * dx + (y - ay) * dy) / l)) : 0, px = ax + t * dx - x, py = ay + t * dy - y;
-        if (!l || px * px + py * py >= best) continue;
-        best = px * px + py * py;
-        way = { line, v: i / 2, dx: dx / Math.sqrt(l), dy: dy / Math.sqrt(l), px, py };
+/** The nearest road or path of a tile within FACE_M of world point x, y: its line, its unit direction there and the offset to it, in world units. */
+function nearestWay(shapes: Shapes, x: number, y: number): { line: Line; v: number; dx: number; dy: number; px: number; py: number } | undefined {
+    const reach = FACE_M / metresPerUnit(y);
+    let best = reach ** 2, way: ReturnType;
+    for (const k of linesNear(shapes, x, y, reach)) {
+        const line = shapes.lines[k];
+        if (line.kind !== ROAD && line.kind !== PATH) continue;
+        for (let i = 0; i + 3 < line.xy.length; i += 2) {
+            const ax = line.xy[i], ay = line.xy[i + 1], dx = line.xy[i + 2] - ax, dy = line.xy[i + 3] - ay, l = dx * dx + dy * dy;
+            const t = l ? Math.min(1, Math.max(0, ((x - ax) * dx + (y - ay) * dy) / l)) : 0, px = ax + t * dx - x, py = ay + t * dy - y;
+            if (!l || px * px + py * py >= best) continue;
+            best = px * px + py * py;
+            way = { line, v: i / 2, dx: dx / Math.sqrt(l), dy: dy / Math.sqrt(l), px, py };
+        }
     }
     return way;
 }
 
 /**
- * The yaw that stands a model at world point x, y along the nearest of `ways` within FACE_M, its front
- * (−y) toward it, as a bench beside a path; undefined without one.
+ * The yaw that stands a model at world point x, y along the nearest road or path of a tile within FACE_M, its
+ * front (−y) toward it, as a bench beside a path; undefined without one.
  */
-export function facing(ways: Line[], x: number, y: number): number | undefined {
-    const way = nearestWay(ways, x, y);
+export function facing(shapes: Shapes, x: number, y: number): number | undefined {
+    const way = nearestWay(shapes, x, y);
     if (!way) return undefined;
     // World y runs south: the way's direction and the front's, east and north.
     const along = Math.atan2(-way.dy, way.dx);
@@ -122,7 +126,7 @@ export function modelKind(name: string, model: () => Model, reach: number, { fac
     const { height, spec } = unitModel(model, reach), stand = { half: halfDepth(model(), facesWay), radius: halfDepth(model(), false), corner };
     return {
         build(feature, out) {
-            pointModels(feature, out, stand, (x, y, faced) => ({ yaw: (facesWay ? faced ?? facing(out.ways, x, y) : undefined) ?? ((x * 7 + y * 13) % 628) / 100, height, model: name }));
+            pointModels(feature, out, stand, (x, y, faced) => ({ yaw: (facesWay ? faced ?? facing(out.shapes, x, y) : undefined) ?? ((x * 7 + y * 13) % 628) / 100, height, model: name }));
         },
         models: { [name]: spec },
         lights: light && { [name]: light },
diff --git a/builder/web/src/lib/trailview/light/shade.wgsl b/builder/web/src/lib/trailview/light/shade.wgsl
index 88e12e083b..b62c21ca7f 100644
--- a/builder/web/src/lib/trailview/light/shade.wgsl
+++ b/builder/web/src/lib/trailview/light/shade.wgsl
@@ -90,12 +90,27 @@ fn finish(colour: vec3f) -> vec3f {
 // shows relief. A face out of the sun keeps the cool sky light, never black; `open` is how much of the
 // sky a hollow still sees. Steep faces also catch light thrown up from the ground below.
 fn light_up(albedo: vec3f, n: vec3f, shadow: f32, open: f32, relief: f32) -> vec3f {
+    return light_spread(albedo, n, shadow, open, relief, 0.0);
+}
+
+// light_up for a normal that turns by `spread` from one texel of its data to the next: each band's edge is at least that
+// soft (spread_step).
+fn light_spread(albedo: vec3f, n: vec3f, shadow: f32, open: f32, relief: f32, spread: f32) -> vec3f {
     let lit = max(dot(n, look.sun.xyz), 0.0) * shadow;
     let softness = look.zenith.w;
-    let band = 0.45 * smoothstep(0.03, 0.03 + softness, lit) + 0.55 * smoothstep(0.32, 0.32 + softness, lit);
+    let band = 0.45 * spread_step(0.03, 0.03 + softness, lit, spread) + 0.55 * spread_step(0.32, 0.32 + softness, lit, spread);
     return albedo * (look.ambient.rgb * ((0.85 + 0.15 * n.z) * open + 0.2 * (1.0 - abs(n.z))) + look.sun_colour.rgb * mix(band, lit, relief));
 }
 
+// smoothstep(lo, hi, x) for an x that the data holds per texel and that changes by `spread` from one texel to the next:
+// at least that wide about the same middle. A narrower step's edge would follow the texels where x changes fast, as
+// across a crease sharper than a texel.
+fn spread_step(lo: f32, hi: f32, x: f32, spread: f32) -> f32 {
+    let half = 0.5 * max(hi - lo, spread);
+    let middle = 0.5 * (lo + hi);
+    return smoothstep(middle - half, middle + half, x);
+}
+
 // The haze between the eye and a point `view` metres from it, at `altitude` above sea level.
 fn atmosphere(colour: vec3f, view: vec3f, altitude: f32) -> vec3f {
     let d = length(view);
diff --git a/builder/web/src/lib/trailview/models/amenities.ts b/builder/web/src/lib/trailview/models/amenities.ts
index 692265c9da..f035b4dcb3 100644
--- a/builder/web/src/lib/trailview/models/amenities.ts
+++ b/builder/web/src/lib/trailview/models/amenities.ts
@@ -11,7 +11,6 @@ const FLAME = rgb('#ff7a1c'), CORE = rgb('#ffd04a'), POST = rgb('#2f7fc1'), PUMP
 const OLIVE = rgb('#5c5a2e'), SIGN = rgb('#f4a81d');
 const POLE = rgb('#4a4f54'), LAMP = rgb('#fff1c4');
 const CONCRETE = rgb('#9b988e'), COPING = rgb('#b4b1a7'), DARK = rgb('#15181a');
-const BAG = rgb('#f08a24'), CROSS = rgb('#2fa84f'), HOSPITAL = rgb('#1f5fae'), WHITE = rgb('#f7f7f2');
 
 /** A park bench: a seat, a back and two pairs of legs. */
 export function bench(): Model {
@@ -128,38 +127,3 @@ export function bikeRepair(): Model {
     for (const x of [-1, 1]) m.beam([0.04 * x, 0, 1.32], [0.34 * x, 0, 1.48], 0.04, METAL);
     return m.beam([0.28, -0.2, 0.04], [0.28, -0.2, 0.95], 0.13, PUMP, { sides: 6, capped: true });
 }
-
-// The signs of a building's use: a symbol on a bracket across a wall in the x–z plane, so that the street
-// toward −y sees it from both ways, at the height of the ground floor, which every building has. It glows at night.
-
-/** The bracket from the wall, and the middle of the symbol that it holds. */
-function bracket(): { m: Model; at: Vec } {
-    return { m: new Model().beam([0, 0, 2.8], [0, -0.45, 2.8], 0.05, METAL), at: [0, -0.78, 2.8] };
-}
-
-/** A shop: a shopping bag with its handle. */
-export function shopSign(): Model {
-    const { m, at: [x, y, z] } = bracket(), symbol = m.triangles;
-    m.box([x, y, z - 0.04], [0.08, 0.44, 0.38], BAG);
-    for (const [a, b] of [[[y + 0.12, z + 0.15], [y + 0.1, z + 0.29]], [[y + 0.1, z + 0.29], [y - 0.1, z + 0.29]], [[y - 0.1, z + 0.29], [y - 0.12, z + 0.15]]]) {
-        m.beam([x, a[0], a[1]], [x, b[0], b[1]], 0.035, BAG);
-    }
-    return m.glowing(symbol);
-}
-
-/** A pharmacy: a green cross. */
-export function pharmacySign(): Model {
-    const { m, at } = bracket(), symbol = m.triangles;
-    return m.box(at, [0.08, 0.18, 0.56], CROSS).box(at, [0.08, 0.56, 0.18], CROSS).glowing(symbol);
-}
-
-/** A hospital: a white H on a blue square, as the road sign shows it, on both faces. */
-export function hospitalSign(): Model {
-    const { m, at: [x, y, z] } = bracket(), symbol = m.triangles;
-    m.box([x, y, z], [0.06, 0.56, 0.56], HOSPITAL);
-    for (const face of [-0.04, 0.04]) {
-        for (const dy of [-0.14, 0.14]) m.box([x + face, y + dy, z], [0.02, 0.08, 0.38], WHITE);
-        m.box([x + face, y, z], [0.02, 0.22, 0.08], WHITE);
-    }
-    return m.glowing(symbol);
-}
diff --git a/builder/web/src/lib/trailview/plan/bridge.ts b/builder/web/src/lib/trailview/plan/bridge.ts
new file mode 100644
index 0000000000..96e165553f
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/bridge.ts
@@ -0,0 +1,61 @@
+// The page's one copy of the ground plan bridge: fetched and compiled once, from the first call on, for the main
+// thread (which only names a cell's inputs) and every plan worker.
+import { sha256 } from '../terrain/device-cache';
+import type { Vocabulary } from './debug';
+import init, { vocabulary } from './pkg/obc_ground_plan_bridge.js';
+
+const WASM = new URL('./pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url);
+
+/** The compiled module for the workers, the bridge's names and stages, and the SHA-256 of its bytes, which keys the device cache. */
+export interface Bridge { module: WebAssembly.Module; vocabulary: Vocabulary; digest: string }
+
+let loaded: Promise | undefined;
+/** Plan workers that `preload` started: their scripts load while the page waits for the release and the device. */
+const spares: Worker[] = [];
+const newWorker = () => new Worker(new URL('./plan-worker.ts', import.meta.url), { type: 'module' });
+
+/** At page load: the bridge and `workers` plan workers start to load. */
+export function preload(workers: number): void {
+    bridge().catch(() => {});
+    while (spares.length < workers) {
+        const worker = newWorker();
+        // A script that fails to load fires its error once, before a taker listens: the taker gets a new worker, whose error it sees.
+        worker.onerror = () => {
+            const k = spares.indexOf(worker);
+            if (k >= 0) spares.splice(k, 1);
+        };
+        spares.push(worker);
+    }
+}
+
+/** A plan worker that `preload` started, or a new one. */
+export function planWorker(): Worker {
+    return spares.shift() ?? newWorker();
+}
+
+/** The bridge, once it is up on the main thread. A load that fails loads again at the next call. */
+export function bridge(): Promise {
+    if (!loaded) {
+        loaded = load();
+        loaded.catch(() => (loaded = undefined));
+    }
+    return loaded;
+}
+
+async function load(): Promise {
+    const response = await fetch(WASM);
+    if (!response.ok) throw new Error(`the plan bridge answered ${response.status}`);
+    const bytes = response.clone().arrayBuffer();
+    const module = await compiled(response, bytes);
+    await init({ module_or_path: module });
+    return { module, vocabulary: JSON.parse(vocabulary()), digest: await sha256(await bytes) };
+}
+
+/**
+ * A module compiled while it streams in, which lets the browser keep its machine code for the next visit. A server
+ * that sends another type than `application/wasm`, or a browser without the streaming compile, gets the bytes compiled.
+ */
+function compiled(response: Response, bytes: Promise): Promise {
+    const whole = async () => WebAssembly.compile(await bytes);
+    return typeof WebAssembly.compileStreaming === 'function' ? WebAssembly.compileStreaming(response).catch(whole) : whole();
+}
diff --git a/builder/web/src/lib/trailview/plan/cells-buffer.wgsl b/builder/web/src/lib/trailview/plan/cells-buffer.wgsl
new file mode 100644
index 0000000000..731a5af121
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/cells-buffer.wgsl
@@ -0,0 +1,2 @@
+// The cells whose ground-plan meshes draw (cells.wgsl), at the binding of the terrain's and the pieces' groups.
+@group(0) @binding(3) var plan_cells: array;
diff --git a/builder/web/src/lib/trailview/plan/cells.wgsl b/builder/web/src/lib/trailview/plan/cells.wgsl
new file mode 100644
index 0000000000..c6467d4d7f
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/cells.wgsl
@@ -0,0 +1,132 @@
+// The cells whose ground-plan mesh draws (pieces.ts), as the terrain's vertices and the pieces' read them: a
+// window of PLAN_WINDOW × PLAN_WINDOW cells (zoom 16) from the cell in words 0 and 1, each with the slot + 1 of
+// its sunk points (0 where no mesh draws), then from PLAN_HEAD per slot the cell's level-18 grid points that
+// lie strictly inside its mesh's owned region, one bit each, row by row from the north-west, both borders
+// included.
+// #include ../terrain/drawn-mesh.wgsl
+// #include cells-buffer.wgsl
+
+// As WINDOW, HEAD, SIDE and SUNK_WORDS of pieces.ts.
+const PLAN_WINDOW: i32 = 7;
+const PLAN_HEAD: u32 = 64u;
+const PLAN_SIDE: u32 = 257u;
+const PLAN_SUNK_WORDS: u32 = 2065u;
+
+// The slot + 1 of world cell `c`, 0 where no mesh draws.
+fn plan_slot(c: vec2i) -> u32 {
+    let k = c - vec2i(bitcast(plan_cells[0]), bitcast(plan_cells[1]));
+    if (any(k < vec2i(0)) || any(k >= vec2i(PLAN_WINDOW))) {
+        return 0u;
+    }
+    return plan_cells[2u + u32(k.y * PLAN_WINDOW + k.x)];
+}
+
+// Whether a mesh draws over the cell that holds a point `u` whole units about the anchor.
+fn plan_meshed(u: vec2i) -> bool {
+    return plan_slot((surface.anchor + u) >> vec2u(14u)) != 0u;
+}
+
+// The LOD distance (m) where level 18 starts to morph. Nearer, a mesh draws whole and the terrain sinks
+// under it, over level-18 nodes and, at a lower quality, over level-17 nodes: level 17 morphs only
+// twice as far out.
+fn plan_sink_m() -> f32 {
+    return surface.range * exp2(-18.0 - MORPH);
+}
+
+// Units past plan_sink_m to which a mesh draws whole (corridor.wgsl): two level-17 cells, the reach of a
+// terrain triangle with a sunk corner. Level 17 starts to morph only at twice plan_sink_m, farther out.
+const PLAN_TRIANGLE_UNITS: f32 = 256.0;
+
+// Whether a grid point lies nearer than `m` metres in the LOD metric.
+fn plan_within(u: vec2i, m: f32) -> bool {
+    return length(vec3f(lod_space(vec2f(u)), surface.above)) < m;
+}
+
+// The share of a mesh's pixels that draw at `u` units about the anchor: 1 to where a cut piece starts to fade into
+// the far look (CUT of roads/corridor.wgsl), 0 where level 18 ends and where no mesh draws. A pixel draws by
+// dither(clip + PLAN_DITHER) < share, as a cut piece's.
+const PLAN_DITHER: vec2f = vec2f(61.0, 7.0);
+
+fn plan_share(u: vec2f) -> f32 {
+    if (!plan_meshed(vec2i(floor(u)))) {
+        return 0.0;
+    }
+    let d = length(vec3f(lod_space(u), surface.above));
+    return 1.0 - smoothstep(plan_sink_m() + PLAN_TRIANGLE_UNITS * surface.unit, surface.range * exp2(-18.0), d);
+}
+
+// Whether a mesh draws a grid point whole: its cell has one, and the point lies before the band where the
+// mesh fades into the far look. A level-18 or level-17 vertex there takes no snap of its own: the mesh
+// draws the ways, and the snap would move a strip vertex across the strip's triangles. Farther out a
+// vertex takes the snap, as the coarser node beside it does.
+fn plan_near(u: vec2i) -> bool {
+    return plan_within(u, plan_sink_m() + PLAN_TRIANGLE_UNITS * surface.unit) && plan_meshed(u);
+}
+
+// The sunk bit of the level-18 grid point at `u` of the cell that holds it, false where no mesh draws.
+fn plan_bit(u: vec2i) -> bool {
+    let w = surface.anchor + u;
+    let slot = plan_slot(w >> vec2u(14u));
+    if (slot == 0u) {
+        return false;
+    }
+    let g = vec2u((w & vec2i(16383)) >> vec2u(6u));
+    let bit = g.y * PLAN_SIDE + g.x;
+    return ((plan_cells[PLAN_HEAD + (slot - 1u) * PLAN_SUNK_WORDS + bit / 32u] >> (bit % 32u)) & 1u) == 1u;
+}
+
+// Whether the terrain sinks its vertex at grid point `u` (level 18, or level 17 at an even point), and so
+// drops each triangle that has it: the point lies strictly inside the mesh's owned region, nearer than
+// plan_sink_m, and a mesh draws over every cell that holds it. Every terrain triangle inside the region then
+// has a sunk corner, or has all three corners on its border: an ear that the strip leaves to the terrain at
+// the drawn level. A triangle with a sunk corner reaches at most a level-17 triangle past plan_sink_m, where
+// the mesh still draws every pixel.
+fn plan_sunk(u: vec2i) -> bool {
+    let w = surface.anchor + u;
+    let c = w >> vec2u(14u);
+    let g = vec2u((w & vec2i(16383)) >> vec2u(6u));
+    if (!plan_within(u, plan_sink_m())) {
+        return false;
+    }
+    if ((g.x == 0u && plan_slot(c - vec2i(1, 0)) == 0u) || (g.y == 0u && plan_slot(c - vec2i(0, 1)) == 0u) || (all(g == vec2u(0u)) && plan_slot(c - vec2i(1, 1)) == 0u)) {
+        return false;
+    }
+    return plan_bit(u);
+}
+
+// The debug view `owned`: whether the mesh draws a point of LOD space drawn by a terrain node of `level`, by
+// the strip's rule. The point lies in R of a cell whose mesh draws (the middle of its region cell is sunk),
+// nearer than plan_sink_m less two level-17 cells, where each terrain triangle that holds it has its corners
+// sunk or on ∂R; and not in what the strip leaves to the terrain: at level 18 an ear, at level 17 a half,
+// with all three corners on ∂R.
+fn plan_owns(s: vec2f, level: u32) -> bool {
+    if (length(vec3f(s, surface.above)) >= plan_sink_m() - PLAN_TRIANGLE_UNITS * surface.unit) {
+        return false;
+    }
+    let at = units_of(s);
+    let o = (((surface.anchor + vec2i(floor(at))) >> vec2u(7u)) << vec2u(7u)) - surface.anchor;
+    if (!plan_bit(o + vec2i(64))) {
+        return false;
+    }
+    let q = (at - vec2f(o)) / 64.0;
+    var corners: array;
+    if (level >= 18u) {
+        if (q.x + q.y < 1.0) {
+            corners = array(vec2i(0, 0), vec2i(0, 1), vec2i(1, 0));
+        } else if (q.x >= 1.0 && q.y >= 1.0 && q.x + q.y > 3.0) {
+            corners = array(vec2i(2, 1), vec2i(1, 2), vec2i(2, 2));
+        } else {
+            return true;
+        }
+    } else if (q.x + q.y < 2.0) {
+        corners = array(vec2i(0, 0), vec2i(0, 2), vec2i(2, 0));
+    } else {
+        corners = array(vec2i(2, 0), vec2i(0, 2), vec2i(2, 2));
+    }
+    for (var k = 0; k < 3; k++) {
+        if (plan_bit(o + corners[k] * 64)) {
+            return true;
+        }
+    }
+    return false;
+}
diff --git a/builder/web/src/lib/trailview/plan/corners.wgsl b/builder/web/src/lib/trailview/plan/corners.wgsl
new file mode 100644
index 0000000000..952409af30
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/corners.wgsl
@@ -0,0 +1,339 @@
+// The corners of a cell's mesh (pieces.ts), once per cell: each corner's height from the one height function
+// (height_at with the corner's label over the ground that the water and the structures stamp), its normal from
+// the same function, and the look of its label in the corridors' words: material, surface code, half-width,
+// and the metres across and along of its line. A ground corner is ground: it shades as the terrain (corridor.wgsl); its words hold its nearest
+// way's half-width and the metres past that way's edge, for the ways' ground terms (ground_terms).
+// #include ../terrain/drawn-height.wgsl
+// #include ../terrain/model.wgsl
+// #include ../terrain/stamp-core.wgsl
+// #include line-look.wgsl
+
+// A piece's words: its corners (2 words each, as `mesh/mod.rs` of obc-ground-plan packs them), at `out` the
+// corners' height, look word, place word and normal, at `slots` its step slots; as pieces.ts lays them out. A
+// storey mesh's corners take their offsets (`mesh/shell.rs`).
+struct Piece {
+    // The cell's north-west corner in whole world units.
+    origin: vec2i,
+    corners: u32,
+    slots: u32,
+    out: u32,
+    // The first step slot of the end faces (the mesh's last slots).
+    faces: u32,
+    // The first word of the cell's records block, and the first corner of a dispatch; the top bit of
+    // `first`: make only the plain terrain's corners, which read the drawn page.
+    block: u32,
+    first: u32,
+    // The first word of the culvert mouths (piece.wgsl).
+    culverts: u32,
+    // A storey mesh's: the first word of its corners' height offsets (f32 metres; 0 for a cell's mesh), of its
+    // triangles (three corners each) and the count of its top's triangles (piece.wgsl).
+    offsets: u32,
+    tris: u32,
+    top: u32,
+}
+
+@group(0) @binding(0) var piece: array;
+@group(0) @binding(2) var params: Piece;
+// `stamp_data` starts with a table of NODES × NODES level-18 nodes, row by row from one node north-west of the
+// cell's first: the offset + 1 of each node's stamp data, 0 for none. Every point that a corner or a normal tap
+// reads lies in the node that holds it, as in the neighbour cell, so two cells give a shared corner one height.
+const NODES: i32 = 6;
+
+// As NO_LABEL of the mesh: the plain terrain.
+const NO_LABEL: u32 = 33554431u;
+// The normal is the function's slope over this many metres each side.
+const NORMAL_STEP_M: f32 = 0.1;
+// As MAT of roads/section.ts, and the surfaces of faces::Surface.
+const MAT_GROUND: u32 = 1u;
+const MAT_WATER: u32 = 50u;
+const S_SHOULDER: u32 = 3u;
+const S_WATER: u32 = 9u;
+const S_ZONE: u32 = 11u;
+// The code of a ground-looking shoulder without a line, until its nearest way gives its class.
+const CODE_ROAD_SURFACE: u32 = 1u;
+// In a corner's look word, the bit of the corridors' fine offset (1 << FINE_SHIFT), which pieces do not read:
+// the face lies on the road surface of a wall class (the line's M_WALL, from `leg_wall` of roads.json), so a step
+// beside it is a wall (piece.wgsl's WALL_SIDE).
+const LOOK_WALL_SIDE: u32 = 268435456u;
+// The next bit: that wall is a bridge's (M_BRIDGE_GROUND), of concrete (piece.wgsl's BRIDGE_SIDE). A storey's corner
+// has no wall: it takes these bits for its deck's build and planks (M_BUILD_SHIFT), in the bits from DECK_SHIFT.
+const LOOK_BRIDGE_SIDE: u32 = 536870912u;
+const SIDE_SHIFT: u32 = 28u;
+const DECK_SHIFT: u32 = 29u;
+const S_CORNER_FILL: u32 = 5u;
+const S_PLATFORM: u32 = 8u;
+// A face without a frame has no edge in its look: this far across a way this wide on each side, as a junction's faces in section.ts.
+const FACE_ACROSS_M: f32 = 2.0;
+const FACE_HALF_M: f32 = 12.0;
+// As piece.ts.
+const ACROSS_STEP_M: f32 = 0.0078163;
+const ALONG_STEPS: f32 = 64.0;
+
+
+// The stamps of the water and the structures at a world point, from the level-18 node that holds it.
+fn cell_stamp(u: vec2i) -> Stamp {
+    let node = u >> vec2u(12u);
+    let at = node - (params.origin >> vec2u(12u)) + vec2i(1);
+    let entry = stamp_data[at.y * NODES + at.x];
+    return stamp_at(18u, node << vec2u(8u), select(NO_DATA, entry - 1u, entry != 0u), u);
+}
+
+// A storey's corner lies on no ground: no stamp bounds it. Its plain terrain (a pier's foot) is the stamp's ground,
+// which reads no drawn page: the storeys' corners are made in `all` passes only.
+fn height_of(q: vec2i, label: u32, storey: bool) -> f32 {
+    let u = params.origin + q / 16;
+    // The plain terrain's rule: the drawn page, which holds the water's bed and the structures' ground as
+    // the terrain beside the mesh draws them.
+    if (label == M_NONE && !storey) {
+        return units_height(u, 18u);
+    }
+    // Under a label, the stamp's ground of the level-18 page: the bicubic of the stored pages after the water and
+    // the structures, which bound the height as in model_height of stamp.wgsl.
+    let base = stored_base(u, 18u);
+    if (!known(base)) {
+        return NONE;
+    }
+    let s = cell_stamp(u);
+    if (label == M_NONE) {
+        return stamped_ground(base, s);
+    }
+    let h = height_at(params.block, vec2f(q), label, stamped_ground(base, s), 0u);
+    return select(stamp_bounded(h.x, h.y == H_PAVED, s), h.x, storey);
+}
+
+// Whether a line's finish word is of a wall class: the one flag that heights reads for a wall at its edge.
+fn road_wall(finish: u32) -> bool {
+    return (finish & M_WALL) != 0u;
+}
+
+// The bits of a wall beside a line of finish word `finish`: none, or LOOK_WALL_SIDE for a wall class (road_wall), with
+// LOOK_BRIDGE_SIDE on a bridge's ground stretch.
+fn wall_side(finish: u32) -> u32 {
+    return select(0u, LOOK_WALL_SIDE | select(0u, LOOK_BRIDGE_SIDE, (finish & M_BRIDGE_GROUND) != 0u), road_wall(finish));
+}
+
+// The metres past the core edge of the way whose core lies nearest q, its half-width, and its wall_side bits (from
+// SIDE_SHIFT): of the lines whose heights reach q's bin, but water. M_FAR and FACE_HALF_M where none does. A bin
+// lists every line whose heights reach it, and every class's reach is at least a path's, so within a path's reach
+// (ground_terms) the answer does not depend on the bin.
+fn nearest_way(q: vec2i, mpu: f32) -> vec3f {
+    var out = vec3f(M_FAR, FACE_HALF_M, 0.0);
+    let qf = vec2f(q);
+    let head = m_bin_head(params.block, qf);
+    if (head == 0u) {
+        return out;
+    }
+    let at = h_heights_start(params.block, qf);
+    let lines = params.block + mw(params.block + 6u);
+    let samples = params.block + mw(params.block + 7u);
+    for (var k = 0u; k < (mw(head + 2u) >> 16u); k++) {
+        let item = mw(at + k);
+        let line = item & 0xffffu;
+        let finish = mw(lines + M_LINE * line + 1u);
+        if ((finish & (M_WATER | M_CEILING)) != 0u) {
+            continue;
+        }
+        let wa = samples + M_SAMPLE * (mw(lines + M_LINE * line + 2u) + (item >> 16u));
+        let wb = wa + M_SAMPLE;
+        let a = vec2f(m_vertex(wa));
+        let u = vec2f(m_vertex(wb)) - a;
+        let t = clamp(dot(qf - a, u) / max(dot(u, u), 1e-9), 0.0, 1.0);
+        let half = mix(mf(wa + 2u), mf(wb + 2u), t) * mpu;
+        let edge = length(qf - a - t * u) * mpu - half;
+        if (edge < out.x) {
+            out = vec3f(edge, half, f32(wall_side(finish) >> SIDE_SHIFT));
+        }
+    }
+    return out;
+}
+
+// Metres across from the middle of `line` (signed by side), along it and its half-width, from its nearest segment in
+// q's bin; across is M_FAR where none lies there.
+fn line_frame(q: vec2i, line: u32, mpu: f32) -> vec3f {
+    let block = params.block;
+    let segs = m_bin_segments(block, vec2f(q));
+    let samples = block + mw(block + 7u);
+    let table = block + mw(block + 6u);
+    let qf = vec2f(q);
+    var best = M_FAR;
+    var out = vec3f(M_FAR, 0.0, FACE_HALF_M);
+    for (var k = 0u; k < segs.y; k++) {
+        let s = mw(segs.x + k);
+        if ((s & 0xffffu) != line) {
+            continue;
+        }
+        let wa = samples + M_SAMPLE * (mw(table + M_LINE * line + 2u) + (s >> 16u));
+        let wb = wa + M_SAMPLE;
+        let a = vec2f(m_vertex(wa));
+        let u = vec2f(m_vertex(wb)) - a;
+        let t = clamp(dot(qf - a, u) / max(dot(u, u), 1e-9), 0.0, 1.0);
+        let d = length(qf - a - t * u);
+        if (d < best) {
+            best = d;
+            out = vec3f(sign(m_cross(u, qf - a)) * d * mpu, mix(mf(wa + 3u), mf(wb + 3u), t), mix(mf(wa + 2u), mf(wb + 2u), t) * mpu);
+        }
+    }
+    return out;
+}
+
+fn place_word(across: f32, along: f32) -> u32 {
+    return (bitcast(i32(round(clamp(across, -16.0, 16.0) / ACROSS_STEP_M))) & 0xfffu) | (u32(clamp(round(along * ALONG_STEPS), 0.0, 1048575.0)) << 12u);
+}
+
+// Whether a label's face can take a look other than the ground's: only such a face needs the function's normal.
+fn may_pave(label: u32) -> bool {
+    if (label == M_NONE) {
+        return false;
+    }
+    let surface_code = mw(m_label(params.block, label)) & 0xffu;
+    return m_paved(params.block, label) || surface_code == S_SHOULDER || surface_code == S_CORNER_FILL || surface_code == S_PLATFORM || surface_code == S_WATER;
+}
+
+// The look word and the place word of a corner with a label. A paved face takes its way's look and a frame:
+// a way's carriageway, bed and shoulder their line's, a junction's carriageway its one or two through lines',
+// and soil its line's, in a junction the nearest arm's (from the junction's record). A junction's corner fill and a
+// platform are one surface without edges. A water face is water. Every other face is ground.
+fn corner_look(q: vec2i, label: u32, mpu: f32) -> vec2u {
+    let ground = vec2u(MAT_GROUND, 0u);
+    // A culvert's zone is ground, though its material is its way's line.
+    if (label != M_NONE && (mw(m_label(params.block, label)) & 0xffu) == S_ZONE) {
+        return ground;
+    }
+    if (!may_pave(label)) {
+        return ground;
+    }
+    let lw = m_label(params.block, label);
+    let w0 = mw(lw);
+    let surface_code = w0 & 0xffu;
+    let shoulder = surface_code == S_SHOULDER;
+    let line = mw(lw + 2u);
+    let lines = params.block + mw(params.block + 6u);
+    let finish = select(mw(lines + M_LINE * line + 1u), 0u, line == M_NONE);
+    let code = finish & 0xffu;
+    let wall = wall_side(finish);
+    if (surface_code == S_WATER) {
+        return vec2u(look_word(MAT_WATER, 0u, 0.0), 0u);
+    }
+    // A shoulder without a line looks like ground; its nearest way decides whether a step beside it is a wall.
+    if (line == M_NONE && shoulder) {
+        return vec2u(look_word(MAT_GROUND, CODE_ROAD_SURFACE, 0.0), 0u);
+    }
+    if (line != M_NONE && code == 0u && surface_code != S_RAILBED) {
+        return ground;
+    }
+    var look = line_look(finish);
+    if (surface_code == S_RAILBED) {
+        look = vec2u(LOOK_BALLAST, code);
+    } else if (surface_code == S_PLATFORM && look.x != LOOK_BALLAST) {
+        look = vec2u(LOOK_PAVERS, code);
+    }
+    let mat = look.x;
+    let drawn = look.y;
+    let uniform = vec2u(look_word(mat, drawn, FACE_HALF_M) | wall, place_word(FACE_ACROSS_M, 0.0));
+    let soil = soil_look(mat);
+    if (line == M_NONE || surface_code == S_CORNER_FILL || surface_code == S_PLATFORM) {
+        return uniform;
+    }
+    let jr = m_junction(params.block, label);
+    var f: vec3f;
+    if (jr == M_NONE) {
+        f = line_frame(q, line, mpu);
+    } else {
+        // Each soil way keeps its tread through the junction: the nearest of all its arms.
+        f = m_junction_frame(params.block, jr, vec2f(q), m_arms_with(jr, select(M_ARM_HOST, 0u, soil)), line, mpu).place;
+    }
+    if (f.x == M_FAR) {
+        return uniform;
+    }
+    // Inside a carriageway its pixels keep the frame within the half-width (corridor.wgsl), so the look draws no
+    // verge there; between the corners the frame stays linear, so its lines stay straight.
+    let inside = select(PIECE_INSIDE, 0u, soil || shoulder);
+    return vec2u(look_word(mat, drawn, f.z) | inside | wall, place_word(f.x, f.y));
+}
+
+// A workgroup makes GROUP_CORNERS corners, LANES lanes each: lane 0 the height and the look, lanes 1 to 4 the
+// normal's taps, so that a corner's five heights run side by side, not one after another.
+const LANES: u32 = 5u;
+const GROUP_CORNERS: u32 = 12u;
+var corner_heights: array;
+
+// A dispatch makes the corners from `first` on: a large cell takes a few frames.
+@compute @workgroup_size(64)
+fn corners(@builtin(local_invocation_index) lane: u32, @builtin(workgroup_id) group: vec3u) {
+    let k = (params.first & 0x7fffffffu) + group.x * GROUP_CORNERS + lane / LANES;
+    let tap = lane % LANES;
+    let terrain_only = (params.first >> 31u) == 1u;
+    let w0 = piece[2u * min(k, params.corners - 1u)];
+    let w1 = piece[2u * min(k, params.corners - 1u) + 1u];
+    // A terrain vertex draws with the terrain's vertex code, as ground.
+    let makes = lane < LANES * GROUP_CORNERS && k < params.corners && (w1 >> 31u) == 0u;
+    let q = vec2i(i32(w0 & 0x7ffffu), i32(w1 & 0x7ffffu));
+    var label = (w0 >> 19u) | (((w1 >> 19u) & 0xfffu) << 13u);
+    if (label == NO_LABEL) {
+        label = M_NONE;
+    }
+    let mpu = h_scale(params.block, vec2f(q));
+    // Frame y runs south: the taps east, west, north, south. They stay in the cell: past its border the
+    // block holds no records, and a paved label there is the plain terrain.
+    let step = i32(max(1.0, round(NORMAL_STEP_M / mpu)));
+    var taps = array(vec2i(0), vec2i(step, 0), vec2i(-step, 0), vec2i(0, -step), vec2i(0, step));
+    let cell = vec2i(i32(M_CELL));
+    var h = NONE;
+    if (makes && (tap == 0u || (!terrain_only && may_pave(label))) && (!terrain_only || label == M_NONE)) {
+        h = height_of(clamp(q + taps[tap], vec2i(0), cell), label, params.offsets != 0u);
+    }
+    corner_heights[lane] = h;
+    workgroupBarrier();
+    if (lane >= LANES * GROUP_CORNERS || k >= params.corners || tap != 0u) {
+        return;
+    }
+    let o = params.out + 4u * k;
+    if (!makes) {
+        // A terrain vertex: ground, with its nearest way.
+        let way = nearest_way(q, mpu);
+        piece[o] = bitcast(NONE);
+        piece[o + 1u] = look_word(MAT_GROUND, 0u, way.y);
+        piece[o + 2u] = place_word(way.x, 0.0);
+        piece[o + 3u] = 0u;
+        return;
+    }
+    if (terrain_only) {
+        if (label == M_NONE) {
+            piece[o] = bitcast(h);
+        }
+        return;
+    }
+    var look = corner_look(q, label, mpu);
+    // Ground takes the pages' normal (corridor.wgsl); a paved face the function's, over NORMAL_STEP_M each side.
+    var n = vec3f(0.0, 0.0, 1.0);
+    if ((look.x & 127u) != MAT_GROUND) {
+        let low = max(q - vec2i(step), vec2i(0));
+        let high = min(q + vec2i(step), cell);
+        let metres = vec2f(high - low) * mpu;
+        let east = (corner_heights[lane + 1u] - corner_heights[lane + 2u]) / metres.x;
+        let north = (corner_heights[lane + 3u] - corner_heights[lane + 4u]) / metres.y;
+        if (known(h) && abs(east) < 1e3 && abs(north) < 1e3) {
+            n = normalize(vec3f(-east, -north, 1.0));
+        }
+    } else {
+        // Ground: its nearest way, for the ground terms; a shoulder takes that way's wall class.
+        let way = nearest_way(q, mpu);
+        let side = select(0u, u32(way.z) << SIDE_SHIFT, ((look.x >> 7u) & 15u) == CODE_ROAD_SURFACE);
+        look = vec2u(look_word(MAT_GROUND, 0u, way.y) | side, place_word(way.x, 0.0));
+    }
+    // A storey's corner: its deck's build and planks, from its label's line.
+    if (params.offsets != 0u && label != M_NONE) {
+        let line = mw(m_label(params.block, label) + 2u);
+        let finish = select(mw(params.block + mw(params.block + 6u) + M_LINE * line + 1u), 0u, line == M_NONE);
+        look.x = (look.x & ~(7u << DECK_SHIFT)) | (((finish >> M_BUILD_SHIFT) & 7u) << DECK_SHIFT);
+    }
+    // Octahedral, as piece.wgsl decodes it.
+    let e = n.xy / (abs(n.x) + abs(n.y) + n.z);
+    if (params.offsets != 0u && known(h)) {
+        h += bitcast(piece[params.offsets + k]);
+    }
+    piece[o] = bitcast(h);
+    piece[o + 1u] = look.x;
+    piece[o + 2u] = look.y;
+    piece[o + 3u] = pack2x16snorm(e);
+}
diff --git a/builder/web/src/lib/trailview/plan/debug.test.ts b/builder/web/src/lib/trailview/plan/debug.test.ts
new file mode 100644
index 0000000000..d6b2e04ca5
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/debug.test.ts
@@ -0,0 +1,119 @@
+import { readFileSync } from 'node:fs';
+import { gunzipSync } from 'node:zlib';
+import earcut from 'earcut';
+import { beforeAll, describe, expect, it } from 'vitest';
+import { metresPerUnit } from '../terrain/bins';
+import { size } from '../terrain/lod';
+import { DEBUG_WORDS, debugMesh, EDGE_STEP_M, type Vocabulary } from './debug';
+import { CELL_LEVEL } from './plan';
+import { build, CellRequest, feature_tiles, initSync, vocabulary } from './pkg/obc_ground_plan_bridge.js';
+
+const cell = { x: 4286 * 8, y: 2888 * 8 };
+const unit = metresPerUnit((cell.y + 0.5) * size(CELL_LEVEL));
+/** Metres as frame units: 16 per world unit. */
+const frame = (m: number) => Math.round(m / unit * 16);
+const area = (p: number[][]) => p.reduce((sum, a, i) => sum + a[0] * p[(i + 1) % p.length][1] - p[(i + 1) % p.length][0] * a[1], 0) / 2;
+
+/** One plan of faces, each a list of rings of [x, y] in metres from the cell's origin. */
+function plan(words: Vocabulary, faces: { surface: string; rings: number[][][] }[]) {
+    const vertices: number[] = [], face: number[] = [], rings: number[] = [], ringVertices: number[] = [];
+    for (const [id, { surface, rings: own }] of faces.entries()) {
+        face.push(id, words.owners.indexOf('way'), 0, words.surfaces.findIndex(s => s.name === surface), 0, 0, 0, 0, 0, 1, 0, 0, rings.length / 2, own.length);
+        for (const ring of own) {
+            rings.push(ringVertices.length, ring.length);
+            for (const [x, y] of ring) ringVertices.push(vertices.push(frame(x), frame(y)) / 2 - 1);
+        }
+    }
+    const empty = { samples: new Int32Array(0), ways: new Uint32Array(0), points: new Uint32Array(0), crossings: new Uint32Array(0), edges: new Uint32Array(0) };
+    return { ...empty, vertices: Int32Array.from(vertices), faces: Uint32Array.from(face), rings: Uint32Array.from(rings), ring_vertices: Uint32Array.from(ringVertices) };
+}
+
+/** The triangles of a fill in metres. */
+function triangles(fills: Int32Array): number[][][] {
+    const s = size(CELL_LEVEL), out = [];
+    for (let v = 0; v < fills.length; v += 3 * DEBUG_WORDS) {
+        out.push([0, 1, 2].map(k => [(fills[v + k * DEBUG_WORDS] - cell.x * s) * unit, (fills[v + k * DEBUG_WORDS + 1] - cell.y * s) * unit]));
+    }
+    return out;
+}
+
+describe('the debug mesh of the faces', () => {
+    let words: Vocabulary;
+    beforeAll(() => {
+        initSync({ module: readFileSync(new URL('./pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url)) });
+        words = JSON.parse(vocabulary());
+    });
+
+    it('fills a face with its holes and a long strip in short triangles, the strip linear in its length', () => {
+        const square = [[[50, 50], [150, 50], [150, 150], [50, 150]], [[80, 80], [80, 120], [120, 120], [120, 80]]];
+        const [c, s] = [Math.cos(Math.PI / 6), Math.sin(Math.PI / 6)], along = (t: number, w: number) => [10 + t * c - w * s, 190 + t * s + w * c];
+        const strip = [[along(0, 0), along(400, 0), along(400, 6), along(0, 6)]];
+        for (const [rings, expected] of [[square, 100 * 100 - 40 * 40], [strip, 400 * 6]] as const) {
+            const mesh = debugMesh(plan(words, [{ surface: 'carriageway', rings: rings as unknown as number[][][] }]), words, cell);
+            const parts = triangles(mesh.fills);
+            expect(Math.abs(parts.reduce((sum, t) => sum + Math.abs(area(t)), 0) / expected - 1)).toBeLessThan(1e-3);
+            for (const t of parts) for (let k = 0; k < 3; k++) expect(Math.hypot(t[k][0] - t[(k + 1) % 3][0], t[k][1] - t[(k + 1) % 3][1])).toBeLessThanOrEqual(4);
+            // The gate holds the count linear in the length.
+            if (rings === strip) expect(parts.length).toBeLessThanOrEqual(1500);
+            expect(mesh.unfilled).toBe(0);
+        }
+    });
+
+    it('gives a terrain face no fill, counts a face without area as unfilled and draws every edge in steps', () => {
+        const flat = plan(words, [
+            { surface: 'terrain', rings: [[[0, 0], [300, 0], [300, 300]]] },
+            { surface: 'verge', rings: [[[10, 10], [20, 10], [30, 10]]] },
+        ]);
+        flat.edges = Uint32Array.from([0, 1, 0, 1, 0, 0, 1, 2, 0, 1, words.edges.findIndex(e => e.name === 'kerb'), 0]);
+        const mesh = debugMesh(flat, words, cell);
+        expect(mesh.fills.length).toBe(0);
+        expect(mesh.unfilled).toBe(1);
+        expect(mesh.lines.length).toBeGreaterThan(2 * 300 / EDGE_STEP_M * 2 * DEBUG_WORDS);
+        for (let v = 0; v < mesh.lines.length; v += 2 * DEBUG_WORDS) {
+            const [ax, ay, , bx, by] = mesh.lines.subarray(v, v + 2 * DEBUG_WORDS);
+            expect(Math.hypot(bx - ax, by - ay) * unit).toBeLessThanOrEqual(EDGE_STEP_M + 0.1);
+        }
+    });
+
+    it('fills each face of real fixture cells to its own area', () => {
+        const fixture = new URL('../../../../tests/browser/trailview/fixture/features/13/', import.meta.url);
+        // Cells whose faces have holes, bends and shoulders that wrap around grid squares.
+        for (const [x, y] of [[34303, 23102], [34298, 23099], [34297, 23099]]) {
+            const request = new CellRequest(x, y), tiles = feature_tiles(x, y);
+            for (let t = 0; t < tiles.length; t += 2) {
+                const bytes = readFileSync(new URL(`${tiles[t]}/${tiles[t + 1]}.bin`, fixture));
+                request.add_tile(tiles[t], tiles[t + 1], bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes);
+            }
+            const p = build(request, false);
+            const all = { samples: new Int32Array(0), ways: new Uint32Array(0), points: new Uint32Array(0), crossings: new Uint32Array(0), edges: new Uint32Array(0), vertices: p.vertices(), faces: p.faces(), rings: p.rings(), ring_vertices: p.ring_vertices() };
+            p.free();
+            const at = { x, y }, s = size(CELL_LEVEL), F = words.words.face;
+            expect(debugMesh(all, words, at).unfilled).toBe(0);
+            let checked = 0;
+            for (let f = 0; f < all.faces.length; f += F) {
+                const [first, count] = all.faces.subarray(f + F - 2, f + F);
+                if (!all.faces[f + 9] || !words.surfaces[all.faces[f + 3]].fill) continue;
+                // The face alone, whole in the cell square: earcut of its rings is its area.
+                const mesh = debugMesh({ ...all, faces: all.faces.slice(f, f + F) }, words, at);
+                const rings = Array.from({ length: count }, (_, r) => {
+                    const [start, n] = all.rings.subarray(2 * (first + r), 2 * (first + r) + 2);
+                    return Array.from(all.ring_vertices.subarray(start, start + n), v => [all.vertices[2 * v] / 16, all.vertices[2 * v + 1] / 16]);
+                });
+                const coords = rings.flat(2), holes: number[] = [];
+                rings.reduce((n, r, k) => (k && holes.push(n), n + r.length), 0);
+                const tri = earcut(coords, holes), corner = (k: number) => [coords[2 * k], coords[2 * k + 1]];
+                let own = 0, perimeter = 0, filled = 0;
+                for (let t = 0; t < tri.length; t += 3) own += Math.abs(area([corner(tri[t]), corner(tri[t + 1]), corner(tri[t + 2])]));
+                for (const r of rings) r.forEach((q, i) => (perimeter += Math.hypot(r[(i + 1) % r.length][0] - q[0], r[(i + 1) % r.length][1] - q[1])));
+                for (let v = 0; v < mesh.fills.length; v += 3 * DEBUG_WORDS) {
+                    filled += Math.abs(area([0, 1, 2].map(k => [mesh.fills[v + k * DEBUG_WORDS] - x * s, mesh.fills[v + k * DEBUG_WORDS + 1] - y * s])));
+                }
+                // Rounding each vertex to a world unit moves the outline by at most 0.75 units.
+                expect(Math.abs(filled - own), `cell ${x}-${y} face ${all.faces[f]}`).toBeLessThanOrEqual(0.75 * perimeter);
+                checked++;
+            }
+            expect(checked).toBeGreaterThan(20);
+        }
+        // Three real cells, each face meshed alone: a busy runner takes longer than the default limit.
+    }, 30_000);
+});
diff --git a/builder/web/src/lib/trailview/plan/debug.ts b/builder/web/src/lib/trailview/plan/debug.ts
new file mode 100644
index 0000000000..25ae0b2af0
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/debug.ts
@@ -0,0 +1,287 @@
+// The debug mesh of a built cell: its faces as fills and edges and its graph as lines, in world units,
+// each vertex with the colour of the debug tool. The plan worker makes it; draw.ts draws it over the view.
+import { metresPerUnit } from '../terrain/bins';
+
+/** Frame units per world unit: the crate's frame is 2^34 of the square, the viewer's units 2^30. */
+const FRAME_PER_UNIT = 16;
+/** A cell is a zoom-16 tile: 2^18 frame units. */
+const CELL_FRAME = 2 ** 18;
+/** Words of a debug vertex: x and y in world units, and the colour as sRGB bytes with alpha, red lowest. */
+export const DEBUG_WORDS = 3;
+/**
+ * Each vertex drapes on the drawn surface, so a line goes in steps of at most this: from 60 m, a height
+ * error of 1 m at 50 m from the middle moves a point by 0.8 m on the screen; at these steps, by centimetres.
+ */
+export const EDGE_STEP_M = 2;
+/** The fill's alpha over the surface's own, so the view shows through the faces. */
+export const FILL_ALPHA = 0.5;
+/** A fill is cut by the squares of this grid, so that no edge is longer than its diagonal, 4 m: the vertices drape as the lines' do. */
+export const FILL_GRID_M = 2.8;
+/** The share of its area by which a face's fill may differ from it before the face counts as unfilled. */
+const FILL_TOLERANCE = 1e-3;
+/** The alpha of the cell border, so that two neighbours show their shared border, and of a way in a tunnel. */
+const FAINT = 0.4;
+/** The sizes of the marks of the graph's points and crossings, in metres. */
+const JUNCTION_M = 1.5, JOINT_M = 0.75, END_M = 1.5, CROSSING_M = 3;
+const FAILED = '#ff0000';
+
+/** The bridge's `vocabulary()`. */
+export interface Vocabulary {
+    stages: string[];
+    /** Words per entry of the bridge's arrays. */
+    words: Record<'wanted' | 'way' | 'point' | 'crossing' | 'face' | 'ring' | 'edge' | 'corner', number>;
+    way_flags: Record<'link' | 'synthetic_deck', number>;
+    families: { name: string; colour: string }[];
+    levels: string[];
+    networks: string[];
+    points: string[];
+    crossings: { name: string; letter: string }[];
+    sources: string[];
+    owners: string[];
+    /** In surface code order; `fill` is '#rrggbbaa', null for no fill. */
+    surfaces: { name: string; fill: string | null }[];
+    /** The fill of a junction's face where it differs from its surface's. */
+    junction_surfaces: { surface: number; fill: string }[];
+    rules: string[];
+    edges: { name: string; colour: string }[];
+    colours: Record<'link' | 'synthetic_deck' | 'junction' | 'joint' | 'end' | 'crossing', string>;
+}
+
+/** The flat plan of a `CellPlan`: positions in frame units from the cell's origin. */
+export interface FlatPlan {
+    samples: Int32Array; ways: Uint32Array; points: Uint32Array; crossings: Uint32Array;
+    vertices: Int32Array; faces: Uint32Array; rings: Uint32Array; ring_vertices: Uint32Array; edges: Uint32Array;
+}
+
+export interface DebugMesh {
+    /** Vertex pairs of a line list. */
+    lines: Int32Array;
+    /** Vertex triples of a triangle list. */
+    fills: Int32Array;
+    /** Faces with a fill colour whose fill does not cover their area in the cell square: none, or off by more than FILL_TOLERANCE. */
+    unfilled: number;
+}
+
+/** '#rrggbb' or '#rrggbbaa', its alpha times `alpha`, as the bytes of WGSL's unorm8x4: red lowest. */
+export function packed(hex: string, alpha = 1): number {
+    const own = hex.length === 9 ? parseInt(hex.slice(7, 9), 16) / 255 : 1;
+    return (parseInt(hex.slice(1, 3), 16) | parseInt(hex.slice(3, 5), 16) << 8 | parseInt(hex.slice(5, 7), 16) << 16 | Math.round(own * alpha * 255) << 24) >>> 0;
+}
+
+type P = [number, number];
+
+/** Writes lines and fills in world units from points in frame units of a cell, clipped to its square and in steps. */
+class Mesh {
+    readonly words: number[] = [];
+    readonly fills: number[] = [];
+    private readonly step: number;
+    private readonly grid: number;
+    private readonly origin: [number, number];
+
+    constructor(cell: { x: number; y: number }) {
+        const size = CELL_FRAME / FRAME_PER_UNIT;
+        this.origin = [cell.x * size, cell.y * size];
+        this.step = EDGE_STEP_M / metresPerUnit((cell.y + 0.5) * size) * FRAME_PER_UNIT;
+        this.grid = this.frame(FILL_GRID_M);
+    }
+
+    private at(p: P): [number, number] {
+        return [this.origin[0] + Math.round(p[0] / FRAME_PER_UNIT), this.origin[1] + Math.round(p[1] / FRAME_PER_UNIT)];
+    }
+
+    /**
+     * A face, its outer ring first and then its holes, as trapezoids in the squares of the grid inside
+     * the cell square. In each square, the heights where an edge ends or leaves the square cut it into
+     * slabs; no edge ends inside a slab, so the even-odd rule over the edges that cross its middle
+     * pairs its walls. Each piece is convex and lies in one square, and the count grows with the area
+     * and the outline. Returns the filled area in frame units squared.
+     */
+    fill(rings: P[][], colour: number): number {
+        const g = this.grid, points = rings.flat(), range = (k: 0 | 1) => {
+            const v = points.map(p => p[k]);
+            return [Math.max(0, Math.floor(Math.min(...v) / g)), Math.min(Math.ceil(CELL_FRAME / g), Math.ceil(Math.max(...v) / g))];
+        };
+        // A level edge crosses no slab, but its height is a level of the squares it passes.
+        const edges = rings.flatMap(r => r.map((p, i) => [p, r[(i + 1) % r.length]] as const));
+        const [[i0, i1], [j0, j1]] = [range(0), range(1)];
+        let filled = 0;
+        for (let j = j0; j < j1; j++) {
+            const y0 = j * g, y1 = Math.min((j + 1) * g, CELL_FRAME);
+            const band = edges.filter(([a, b]) => Math.max(a[1], b[1]) >= y0 && Math.min(a[1], b[1]) <= y1);
+            for (let i = i0; i < i1 && band.length; i++) {
+                const x0 = i * g, x1 = Math.min((i + 1) * g, CELL_FRAME), levels = [y0, y1];
+                for (const [a, b] of band) {
+                    const c = clip(a, b, [x0, y0, x1, y1]);
+                    if (c) levels.push(c[0][1], c[1][1]);
+                }
+                levels.sort((p, q) => p - q);
+                for (let k = 0; k + 1 < levels.length; k++) {
+                    const [ya, yb] = [levels[k], levels[k + 1]], ym = (ya + yb) / 2;
+                    if (yb - ya < 1e-6) continue;
+                    // The walls of the slab: x at ya, at yb and at its middle.
+                    const walls: [number, number, number][] = [];
+                    let inside = false;
+                    for (const [a, b] of band) {
+                        if ((a[1] <= ym) === (b[1] <= ym)) continue;
+                        const x = (y: number) => Math.min(x1, Math.max(x0, a[0] + (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1])));
+                        const xm = a[0] + (b[0] - a[0]) * (ym - a[1]) / (b[1] - a[1]);
+                        if (xm < x0) inside = !inside;
+                        else if (xm <= x1) walls.push([x(ya), x(yb), xm]);
+                    }
+                    walls.sort((p, q) => p[2] - q[2]);
+                    if (inside) walls.unshift([x0, x0, x0]);
+                    if (walls.length % 2) walls.push([x1, x1, x1]);
+                    for (let w = 0; w < walls.length; w += 2) {
+                        const [[la, lb], [ra, rb]] = [walls[w], walls[w + 1]];
+                        const quad = [this.at([la, ya]), this.at([ra, ya]), this.at([rb, yb]), this.at([lb, yb])];
+                        // A wall pair that meets at a corner leaves a triangle.
+                        if (ra > la) this.fills.push(...quad[0], colour, ...quad[1], colour, ...quad[2], colour);
+                        if (rb > lb) this.fills.push(...quad[0], colour, ...quad[2], colour, ...quad[3], colour);
+                        filled += (ra - la + rb - lb) / 2 * (yb - ya);
+                    }
+                }
+            }
+        }
+        return filled;
+    }
+
+    /** Metres as frame units at the cell. */
+    frame(metres: number): number {
+        return metres / EDGE_STEP_M * this.step;
+    }
+
+    line(a: [number, number], b: [number, number], colour: number): void {
+        const clipped = clip(a, b);
+        if (!clipped) return;
+        const [p, q] = clipped, steps = Math.max(1, Math.ceil(Math.hypot(q[0] - p[0], q[1] - p[1]) / this.step));
+        const at = (k: number) => this.at([p[0] + (q[0] - p[0]) * k / steps, p[1] + (q[1] - p[1]) * k / steps]);
+        for (let k = 0; k < steps; k++) this.words.push(...at(k), colour, ...at(k + 1), colour);
+    }
+
+    ring(points: [number, number][], colour: number): void {
+        points.forEach((p, i) => this.line(p, points[(i + 1) % points.length], colour));
+    }
+
+    /** A regular polygon of `n` corners about c with the radius r in frame units, the first at `turn` of a circle. */
+    mark(c: [number, number], r: number, n: number, colour: number, turn = 0): void {
+        this.ring(Array.from({ length: n }, (_, i) => {
+            const a = 2 * Math.PI * (i / n + turn);
+            return [c[0] + r * Math.cos(a), c[1] + r * Math.sin(a)] as [number, number];
+        }), colour);
+    }
+}
+
+/** The part of segment a–b inside box [x0, y0, x1, y1], by default the cell square (Liang–Barsky), or undefined. */
+function clip(a: readonly [number, number], b: readonly [number, number], [x0, y0, x1, y1] = [0, 0, CELL_FRAME, CELL_FRAME]): [[number, number], [number, number]] | undefined {
+    let t0 = 0, t1 = 1;
+    const d = [b[0] - a[0], b[1] - a[1]];
+    for (const [p, q] of [[-d[0], a[0] - x0], [d[0], x1 - a[0]], [-d[1], a[1] - y0], [d[1], y1 - a[1]]]) {
+        if (p === 0) {
+            if (q < 0) return undefined;
+            continue;
+        }
+        const t = q / p;
+        if (p < 0) t0 = Math.max(t0, t);
+        else t1 = Math.min(t1, t);
+        if (t0 > t1) return undefined;
+    }
+    return [[a[0] + t0 * d[0], a[1] + t0 * d[1]], [a[0] + t1 * d[0], a[1] + t1 * d[1]]];
+}
+
+/** The part of a ring between `lo` and `hi` on axis `k` (Sutherland–Hodgman): a concave ring may keep edges along the bounds. */
+function clipRing(ring: P[], k: 0 | 1, lo: number, hi: number): P[] {
+    let out = ring;
+    for (const [bound, below] of [[lo, false], [hi, true]] as const) {
+        const inside = (p: P) => (below ? p[k] <= bound : p[k] >= bound), next: P[] = [];
+        out.forEach((p, i) => {
+            const q = out[(i + 1) % out.length];
+            if (inside(p)) next.push(p);
+            if (inside(p) !== inside(q)) {
+                const t = (bound - p[k]) / (q[k] - p[k]);
+                next.push([p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])]);
+            }
+        });
+        if (next.length < 3) return [];
+        out = next;
+    }
+    return out;
+}
+
+/** The signed area of a ring. */
+const area = (ring: P[]) => ring.reduce((sum, p, i) => sum + p[0] * ring[(i + 1) % ring.length][1] - ring[(i + 1) % ring.length][0] * p[1], 0) / 2;
+
+/** The faces of a plan: each face with a fill in trapezoids, each edge in its kind's colour. Returns the count of faces left unfilled. */
+function faces(mesh: Mesh, flat: FlatPlan, vocabulary: Vocabulary): number {
+    const { face: FACE_WORDS, ring: RING_WORDS, edge: EDGE_WORDS } = vocabulary.words, junction = vocabulary.owners.indexOf('junction');
+    const fill = vocabulary.surfaces.map(({ fill }) => (fill ? packed(fill, FILL_ALPHA) : undefined));
+    const junctionFill = new Map(vocabulary.junction_surfaces.map(({ surface, fill }) => [surface, packed(fill, FILL_ALPHA)]));
+    const v = flat.vertices, point = (i: number): P => [v[2 * i], v[2 * i + 1]];
+    let unfilled = 0;
+    for (let f = 0; f < flat.faces.length; f += FACE_WORDS) {
+        const [, owner, , surface] = flat.faces.subarray(f, f + 4), [first, count] = flat.faces.subarray(f + FACE_WORDS - 2, f + FACE_WORDS);
+        const colour = (owner === junction ? junctionFill.get(surface) : undefined) ?? fill[surface];
+        if (colour === undefined) continue;
+        const rings = Array.from({ length: count }, (_, r) => {
+            const [start, n] = flat.rings.subarray(RING_WORDS * (first + r), RING_WORDS * (first + r) + 2);
+            return Array.from(flat.ring_vertices.subarray(start, start + n), point);
+        });
+        // The face's area in the cell square: a clip of each ring keeps its signed area.
+        const own = rings.reduce((sum, r) => sum + area(clipRing(clipRing(r, 0, 0, CELL_FRAME), 1, 0, CELL_FRAME)), 0);
+        const filled = mesh.fill(rings, colour);
+        if (rings.reduce((sum, r) => sum + area(r), 0) <= 0 || Math.abs(filled - own) > FILL_TOLERANCE * own + 1) unfilled++;
+    }
+    const border = vocabulary.edges.findIndex(e => e.name === 'cell_border');
+    const edge = vocabulary.edges.map(({ colour }, kind) => packed(colour, kind === border ? FAINT : 1));
+    for (let e = 0; e < flat.edges.length; e += EDGE_WORDS) mesh.line(point(flat.edges[e]), point(flat.edges[e + 1]), edge[flat.edges[e + 4]]);
+    return unfilled;
+}
+
+const square = (lines: Mesh, colour: number) => lines.ring([[0, 0], [CELL_FRAME, 0], [CELL_FRAME, CELL_FRAME], [0, CELL_FRAME]], colour);
+
+/**
+ * The debug mesh of a cell's plan: the faces (`faces`), then over them each way's samples in its family's colour (red a link, orange a
+ * synthetic deck, faint in a tunnel), a square at each owned junction, a cross at a joint, a ring at an
+ * end, a diamond at a crossing, and the faint cell border. Every line stays inside the cell square.
+ */
+export function debugMesh(flat: FlatPlan, vocabulary: Vocabulary, cell: { x: number; y: number }): DebugMesh {
+    const lines = new Mesh(cell), unfilled = faces(lines, flat, vocabulary), c = vocabulary.colours, { way: WAY_WORDS, point: POINT_WORDS, crossing: CROSSING_WORDS } = vocabulary.words;
+    const { link: WAY_LINK, synthetic_deck: WAY_SYNTHETIC_DECK } = vocabulary.way_flags;
+    const family = vocabulary.families.map(({ colour }) => [packed(colour), packed(colour, FAINT)]);
+    const tunnel = vocabulary.levels.indexOf('tunnel');
+    for (let w = 0; w < flat.ways.length; w += WAY_WORDS) {
+        const [, kind, level, flags, first, count] = flat.ways.subarray(w, w + WAY_WORDS);
+        const faint = level === tunnel ? 1 : 0;
+        const colour = flags & WAY_LINK ? packed(c.link) : flags & WAY_SYNTHETIC_DECK ? packed(c.synthetic_deck) : family[kind][faint];
+        for (let s = first; s + 1 < first + count; s++) {
+            lines.line([flat.samples[2 * s], flat.samples[2 * s + 1]], [flat.samples[2 * s + 2], flat.samples[2 * s + 3]], colour);
+        }
+    }
+    const marks = [
+        (p: [number, number]) => lines.mark(p, lines.frame(JUNCTION_M) * Math.SQRT2, 4, packed(c.junction), 1 / 8),
+        (p: [number, number]) => {
+            const r = lines.frame(JOINT_M), colour = packed(c.joint);
+            lines.line([p[0] - r, p[1]], [p[0] + r, p[1]], colour);
+            lines.line([p[0], p[1] - r], [p[0], p[1] + r], colour);
+        },
+        (p: [number, number]) => lines.mark(p, lines.frame(END_M), 8, packed(c.end)),
+    ];
+    for (let i = 0; i < flat.points.length; i += POINT_WORDS) {
+        const [kind, , x, y, owned] = flat.points.subarray(i, i + POINT_WORDS);
+        if (owned) marks[kind]([x | 0, y | 0]);
+    }
+    for (let i = 0; i < flat.crossings.length; i += CROSSING_WORDS) {
+        const [x, y, , , owned] = flat.crossings.subarray(i, i + CROSSING_WORDS);
+        if (owned) lines.mark([x | 0, y | 0], lines.frame(CROSSING_M), 4, packed(c.crossing));
+    }
+    square(lines, packed('#000000', FAINT));
+    return { ...words(lines), unfilled };
+}
+
+const words = (mesh: Mesh) => ({ lines: new Int32Array(Uint32Array.from(mesh.words, w => w >>> 0).buffer), fills: new Int32Array(Uint32Array.from(mesh.fills, w => w >>> 0).buffer) });
+
+/** The red outline of a cell that failed, so that a failed cell never hides. */
+export function failedMesh(cell: { x: number; y: number }): DebugMesh {
+    const lines = new Mesh(cell);
+    square(lines, packed(FAILED));
+    return { ...words(lines), unfilled: 0 };
+}
diff --git a/builder/web/src/lib/trailview/plan/debug.wgsl b/builder/web/src/lib/trailview/plan/debug.wgsl
new file mode 100644
index 0000000000..ca69b494f5
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/debug.wgsl
@@ -0,0 +1,70 @@
+// The debug draw of the ground plan over the canvas, after the resolve (plan/draw.ts): the lines and
+// fills of plan/debug.ts, LIFT_M above the drawn surface, in the debug tool's sRGB colours. A primitive
+// with a vertex of unknown height draws nothing. A fragment more than HIDDEN_M behind the scene's depth
+// is hidden: a hill hides the plan behind it, but no house or tree hides it from above.
+// #include ../terrain/drawn-mesh.wgsl
+
+// As Frame of terrain.wgsl, which shares its buffer.
+struct Frame {
+    view_proj: mat4x4f,
+    sun: vec4f,
+    eye: f32,
+    curvature: f32,
+    debug: u32,
+    pixel: f32,
+}
+
+@group(0) @binding(0) var frame: Frame;
+// xy: render pixels per canvas pixel.
+@group(0) @binding(1) var ratio: vec4f;
+// The scene's depth in its top left, reversed Z: depth = NEAR / distance along the view.
+@group(2) @binding(0) var scene_depth: texture_depth_2d;
+
+const LIFT_M: f32 = 0.05;
+const HIDDEN_M: f32 = 50.0;
+// As NEAR of frame/camera.ts.
+const NEAR: f32 = 0.1;
+
+struct PlanIn {
+    // World units.
+    @location(0) at: vec2i,
+    // sRGB with alpha.
+    @location(1) colour: vec4f,
+}
+
+struct PlanOut {
+    @builtin(position) clip: vec4f,
+    // Premultiplied.
+    @location(0) colour: vec4f,
+    // 1 where the surface under the vertex is known.
+    @location(1) known: f32,
+    // The distance along the view.
+    @location(2) along: f32,
+}
+
+@vertex
+fn plan_vertex(v: PlanIn) -> PlanOut {
+    let s = lod_space(vec2f(v.at - surface.anchor));
+    let h = stand_height(s, v.at);
+    let r = to_render(s);
+    // A vertex of unknown height takes the eye's ground, as the route's does.
+    let z = select(-surface.above, h + LIFT_M - frame.eye, known(h)) - frame.curvature * dot(r, r);
+    var out: PlanOut;
+    out.clip = frame.view_proj * vec4f(r, z, 1.0);
+    out.colour = vec4f(v.colour.rgb * v.colour.a, v.colour.a);
+    out.known = select(0.0, 1.0, known(h));
+    out.along = out.clip.w;
+    return out;
+}
+
+@fragment
+fn plan_fragment(in: PlanOut) -> @location(0) vec4f {
+    if (in.known < 0.999) {
+        discard;
+    }
+    let depth = textureLoad(scene_depth, vec2i(floor(in.clip.xy * ratio.xy)), 0);
+    if (depth > 0.0 && in.along > NEAR / depth + HIDDEN_M) {
+        discard;
+    }
+    return in.colour;
+}
diff --git a/builder/web/src/lib/trailview/plan/draw.ts b/builder/web/src/lib/trailview/plan/draw.ts
new file mode 100644
index 0000000000..a94fb8920a
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/draw.ts
@@ -0,0 +1,118 @@
+import type { Gpu } from '../gpu/device';
+import { layouts } from '../gpu/layouts';
+import { wgsl } from '../gpu/wgsl';
+import { DEBUG_WORDS, type DebugMesh } from './debug';
+
+/** A vertex buffer grows by this when a set of meshes does not fit. */
+const GROWTH = 1.5;
+
+interface Resources {
+    gpu: Gpu;
+    lines: GPURenderPipeline;
+    fills: GPURenderPipeline;
+    layout: GPUBindGroupLayout;
+    depthLayout: GPUBindGroupLayout;
+    frame: GPUBuffer;
+    ratio: GPUBuffer;
+    group: GPUBindGroup;
+}
+
+/**
+ * The debug draw of the ground plan (plan/debug.wgsl): its own render pass on the canvas after the
+ * resolve, so the plan shows in the debug tool's colours at the canvas resolution and the TAA does
+ * not touch it. A hill hides what lies behind it; no house or tree hides the plan from above.
+ */
+export class PlanDraw {
+    private resources?: Resources;
+    private meshes: DebugMesh[] = [];
+    private fresh = true;
+    private buffers: Partial> = {};
+    private counts = { lines: 0, fills: 0 };
+
+    /** The vertices of the meshes drawn. */
+    get vertices(): number {
+        return this.meshes.reduce((sum, { lines, fills }) => sum + (lines.length + fills.length) / DEBUG_WORDS, 0);
+    }
+
+    set(meshes: DebugMesh[]): void {
+        this.meshes = meshes;
+        this.fresh = true;
+    }
+
+    /** `frame` is the frame uniform of the eye's view. */
+    async attach(gpu: Gpu, frame: GPUBuffer): Promise {
+        this.resources = undefined;
+        const { lines, fills, layout, depthLayout } = await gpu.once(planPipelines);
+        const ratio = gpu.buffer('plan', 16, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
+        const group = gpu.device.createBindGroup({ layout, entries: [{ binding: 0, resource: { buffer: frame } }, { binding: 1, resource: { buffer: ratio } }] });
+        this.buffers = {};
+        this.fresh = true;
+        this.resources = { gpu, lines, fills, layout, depthLayout, frame, ratio, group };
+    }
+
+    /**
+     * Draws the meshes over `canvas`. `depth` holds the scene's depth in its top left, `ratio` render
+     * pixels per canvas pixel along each axis.
+     */
+    encode(encoder: GPUCommandEncoder, canvas: GPUTextureView, depth: GPUTexture, ratio: [number, number], surface: GPUBindGroup, features: GPUBindGroup): void {
+        const r = this.resources;
+        if (!r) return;
+        if (this.fresh) this.write(r);
+        if (!this.counts.lines && !this.counts.fills) return;
+        r.gpu.device.queue.writeBuffer(r.ratio, 0, new Float32Array([...ratio, 0, 0]));
+        const depthGroup = r.gpu.device.createBindGroup({ layout: r.depthLayout, entries: [{ binding: 0, resource: depth.createView() }] });
+        const pass = encoder.beginRenderPass({ label: 'plan', colorAttachments: [{ view: canvas, loadOp: 'load', storeOp: 'store' }] });
+        [r.group, surface, depthGroup, features].forEach((group, k) => pass.setBindGroup(k, group));
+        for (const [kind, pipeline] of [['fills', r.fills], ['lines', r.lines]] as const) {
+            if (!this.counts[kind]) continue;
+            pass.setPipeline(pipeline);
+            pass.setVertexBuffer(0, this.buffers[kind]!);
+            pass.draw(this.counts[kind]);
+        }
+        pass.end();
+    }
+
+    private write(r: Resources): void {
+        this.fresh = false;
+        for (const kind of ['lines', 'fills'] as const) {
+            const words = this.meshes.reduce((sum, mesh) => sum + mesh[kind].length, 0);
+            this.counts[kind] = words / DEBUG_WORDS;
+            if (!words) continue;
+            let buffer = this.buffers[kind];
+            if (!buffer || buffer.size < 4 * words) {
+                if (buffer) r.gpu.destroy('plan', buffer);
+                buffer = this.buffers[kind] = r.gpu.buffer('plan', Math.ceil(4 * words * GROWTH / 4) * 4, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST);
+            }
+            let offset = 0;
+            for (const mesh of this.meshes) {
+                if (!mesh[kind].length) continue;
+                r.gpu.device.queue.writeBuffer(buffer, offset, mesh[kind]);
+                offset += mesh[kind].byteLength;
+            }
+        }
+    }
+}
+
+async function planPipelines(gpu: Gpu) {
+    const { device } = gpu, { surface, features } = gpu.once(layouts), { VERTEX, FRAGMENT } = GPUShaderStage;
+    const layout = device.createBindGroupLayout({ entries: [
+        { binding: 0, visibility: VERTEX | FRAGMENT, buffer: { type: 'uniform' } },
+        { binding: 1, visibility: FRAGMENT, buffer: { type: 'uniform' } },
+    ] });
+    const depthLayout = device.createBindGroupLayout({ entries: [{ binding: 0, visibility: FRAGMENT, texture: { sampleType: 'depth' } }] });
+    const module = device.createShaderModule({ label: 'plan', code: wgsl('plan/debug.wgsl') });
+    const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [layout, surface, depthLayout, features] });
+    // Premultiplied: a fill covers by its alpha.
+    const blend: GPUBlendComponent = { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' };
+    const pipeline = (topology: GPUPrimitiveTopology) => device.createRenderPipelineAsync({
+        label: `plan ${topology}`, layout: pipelineLayout,
+        vertex: {
+            module, entryPoint: 'plan_vertex',
+            buffers: [{ arrayStride: 4 * DEBUG_WORDS, attributes: [{ shaderLocation: 0, offset: 0, format: 'sint32x2' }, { shaderLocation: 1, offset: 8, format: 'unorm8x4' }] }],
+        },
+        fragment: { module, entryPoint: 'plan_fragment', targets: [{ format: gpu.format, blend: { color: blend, alpha: blend } }] },
+        primitive: { topology },
+    });
+    const [lines, fills] = await Promise.all([pipeline('line-list'), pipeline('triangle-list')]);
+    return { lines, fills, layout, depthLayout };
+}
diff --git a/builder/web/src/lib/trailview/plan/inputs.ts b/builder/web/src/lib/trailview/plan/inputs.ts
new file mode 100644
index 0000000000..51e51fccd3
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/inputs.ts
@@ -0,0 +1,45 @@
+// The inputs of one cell of the ground plan, collected on the main thread from the tiles that the
+// viewer already loads. The bridge names them, so no TypeScript copy of the crate's input walk exists.
+import type { FeatureTiles } from '../terrain/stamps';
+
+/** The zoom of the feature tiles that a cell reads: FEATURE_ZOOM of the crate. */
+const FEATURE_ZOOM = 13;
+
+/** The body of stored terrain tile z/x/y, undefined where it is absent. */
+export type StoredTiles = (z: number, x: number, y: number) => Promise;
+
+/** The bridge's names of a cell's inputs; `words` is `words.wanted` of its vocabulary. */
+export interface InputNames {
+    feature_tiles(x: number, y: number): Uint32Array;
+    wanted(x: number, y: number): Uint32Array;
+    words: number;
+}
+
+export interface CellInputs {
+    /** The feature tiles that exist, as bodies of the archive (they can be gzip); without a body where the worker holds it. */
+    tiles: { column: number; row: number; body?: ArrayBuffer }[];
+    /** The stored tiles that hold the wanted pages and exist, each once. */
+    terrain: { z: number; x: number; y: number; body: ArrayBuffer }[];
+    /** The bridge's `wanted` of the cell. */
+    pages: Uint32Array;
+}
+
+/**
+ * The inputs of cell (x, y) of zoom 16, or 'empty' when none of its feature tiles exists. A fetch that
+ * fails rejects: a cell never builds with an input left out, which would differ from the native build.
+ * A tile that `held` names exists and goes without its body.
+ */
+export async function cellInputs({ x, y }: { x: number; y: number }, names: InputNames, features: FeatureTiles, stored: StoredTiles,
+    held: (column: number, row: number) => boolean = () => false): Promise {
+    const pairs = names.feature_tiles(x, y);
+    const found = await Promise.all(Array.from({ length: pairs.length / 2 }, async (_, i) => {
+        const [column, row] = [pairs[2 * i], pairs[2 * i + 1]];
+        return held(column, row) ? { column, row, held: true } : { column, row, body: await features(FEATURE_ZOOM, column, row) };
+    }));
+    const tiles = found.flatMap(({ column, row, body, held }) => (held ? [{ column, row }] : body ? [{ column, row, body }] : []));
+    if (!tiles.length) return 'empty';
+    const pages = names.wanted(x, y), seen = new Map();
+    for (let i = 0; i < pages.length; i += names.words) seen.set(`${pages[i + 3]}/${pages[i + 4]}/${pages[i + 5]}`, [pages[i + 3], pages[i + 4], pages[i + 5]]);
+    const bodies = await Promise.all([...seen.values()].map(async ([z, tx, ty]) => ({ z, x: tx, y: ty, body: await stored(z, tx, ty) })));
+    return { tiles, terrain: bodies.flatMap(({ body, ...at }) => (body ? [{ ...at, body }] : [])), pages };
+}
diff --git a/builder/web/src/lib/trailview/plan/line-look.wgsl b/builder/web/src/lib/trailview/plan/line-look.wgsl
new file mode 100644
index 0000000000..835e650def
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/line-look.wgsl
@@ -0,0 +1,45 @@
+// A line's look in a piece's look word, as `lookOf` of roads/section.ts: the corners (corners.wgsl) and a stop arm's
+// mouth (piece.wgsl) read it.
+// #include ../terrain/records.wgsl
+// #include ../roads/look-codes.wgsl
+
+// As CODE_PATH of ground/roads.wgsl: the drawn code of a concrete path, which has no vehicle tracks.
+const LINE_PATH_CODE: u32 = 6u;
+// The band's priority field of a look word, which a piece takes for its frame's clamp.
+const PIECE_INSIDE: u32 = 65536u;
+
+// The look and the drawn code of a line's finish word; a soil line of a path (M_PATH) wears a trail.
+fn line_look(finish: u32) -> vec2u {
+    let code = finish & 0xffu;
+    let material = (finish >> M_MATERIAL_SHIFT) & 15u;
+    if ((finish & M_RAIL) != 0u || code >= 9u) {
+        return vec2u(LOOK_BALLAST, code);
+    }
+    if (code == 8u || material == MATERIAL_PAVERS) {
+        return vec2u(LOOK_PAVERS, code);
+    }
+    if (material == MATERIAL_SETT) {
+        return vec2u(LOOK_SETT, code);
+    }
+    if (material == MATERIAL_CONCRETE || material == MATERIAL_STRIPS) {
+        return vec2u(select(LOOK_CONCRETE, LOOK_STRIPS, material == MATERIAL_STRIPS), select(code, LINE_PATH_CODE, (finish & M_PATH) != 0u));
+    }
+    if ((finish & M_MARKED) != 0u) {
+        return vec2u(select(LOOK_MAIN, LOOK_MOTORWAY, (finish & M_MOTORWAY) != 0u), code);
+    }
+    if (code == 3u) {
+        return vec2u(LOOK_GRAVEL, code);
+    }
+    if (code == 4u || code == 5u) {
+        return vec2u(select(LOOK_DIRT, LOOK_TRAIL, (finish & M_PATH) != 0u), code);
+    }
+    if (code == 6u) {
+        return vec2u(LOOK_TRAIL, code);
+    }
+    return vec2u(LOOK_ASPHALT, 2u);
+}
+
+// Whether a look is soil: its tread keeps its own edge, with no frame clamp.
+fn soil_look(mat: u32) -> bool {
+    return mat == LOOK_DIRT || mat == LOOK_TRAIL;
+}
diff --git a/builder/web/src/lib/trailview/plan/mesh.test.ts b/builder/web/src/lib/trailview/plan/mesh.test.ts
new file mode 100644
index 0000000000..c7fef3429d
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/mesh.test.ts
@@ -0,0 +1,64 @@
+import { readFileSync } from 'node:fs';
+import { gunzipSync } from 'node:zlib';
+import { describe, expect, it } from 'vitest';
+import { cellMesh, meshBytes, SIDE } from './mesh';
+import { build, CellRequest, feature_tiles, initSync } from './pkg/obc_ground_plan_bridge.js';
+
+/** Frame units per grid cell of the mesh level, as `params::GRID`. */
+const GRID = 1024;
+
+describe('the mesh reader', () => {
+    it('reads a real cell: every index names a corner, and no terrain vertex sinks while points inside R do', () => {
+        initSync({ module: readFileSync(new URL('./pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url)) });
+        // The north-west cell of zoom-13 tile 4286/2888, the tile of the vector: its roads lie there.
+        const request = new CellRequest(4286 * 8, 2888 * 8);
+        request.add_tile(4286, 2888, readFileSync(new URL('../../../../../../specs/vectors/trailview-features.bin', import.meta.url)));
+        const plan = build(request, false), input = plan.mesh_input();
+        try {
+            const mesh = cellMesh(input.mesh(plan.rim())!.buffer as ArrayBuffer), corners = mesh.corners.length / 2;
+            expect(mesh.triangles.length).toBeGreaterThan(0);
+            let k = 0;
+            for (const { count, base } of mesh.runs) for (let n = 0; n < 3 * count; n++, k++) expect(mesh.triangles[k] + base).toBeLessThan(corners);
+            expect(k).toBe(mesh.triangles.length);
+            expect(mesh.steps.every(k => k < corners)).toBe(true);
+            const sunk = (i: number, j: number) => ((mesh.sunk[(j * SIDE + i) >> 5] >>> ((j * SIDE + i) & 31)) & 1) === 1;
+            let terrain = 0, inside = 0;
+            for (let k = 0; k < corners; k++) {
+                const x = mesh.corners[2 * k] & 0x7ffff, y = mesh.corners[2 * k + 1] & 0x7ffff;
+                if (mesh.corners[2 * k + 1] >>> 31 === 0) continue;
+                terrain++;
+                // A terrain vertex is a grid point on R's border: the terrain draws it, so it never sinks.
+                expect([x % GRID, y % GRID, +sunk(x / GRID, y / GRID)]).toEqual([0, 0, 0]);
+            }
+            for (let j = 0; j < SIDE; j++) for (let i = 0; i < SIDE; i++) inside += +sunk(i, j);
+            expect(terrain).toBeGreaterThan(0);
+            expect(inside).toBeGreaterThan(0);
+        } finally {
+            input.free();
+            plan.free();
+        }
+    });
+
+    it('reads the storeys after a cell mesh: every index names a storey corner, the top comes first, then the shell in its parts', () => {
+        // A cell of the browser fixture with decks over a road.
+        const fixture = new URL('../../../../tests/browser/trailview/fixture/features/13/', import.meta.url), [x, y] = [34294, 23098];
+        const request = new CellRequest(x, y), tiles = feature_tiles(x, y);
+        for (let t = 0; t < tiles.length; t += 2) {
+            const bytes = readFileSync(new URL(`${tiles[t]}/${tiles[t + 1]}.bin`, fixture));
+            request.add_tile(tiles[t], tiles[t + 1], bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes);
+        }
+        const plan = build(request, false), input = plan.mesh_input();
+        try {
+            const storeys = cellMesh(meshBytes(input.mesh(plan.rim())!, input.storeys())).storeys!, corners = storeys.offsets.length;
+            expect(storeys.corners.length).toBe(2 * corners);
+            expect([...storeys.triangles, ...storeys.slots].every(c => c < corners)).toBe(true);
+            expect(storeys.top).toBeGreaterThan(0);
+            expect(storeys.top).toBeLessThan(storeys.triangles.length / 3);
+            expect(storeys.top <= storeys.railings && storeys.railings <= storeys.piers && storeys.piers <= storeys.triangles.length / 3).toBe(true);
+            expect([...new Float32Array(storeys.offsets.buffer)].every(Number.isFinite)).toBe(true);
+        } finally {
+            input.free();
+            plan.free();
+        }
+    });
+});
diff --git a/builder/web/src/lib/trailview/plan/mesh.ts b/builder/web/src/lib/trailview/plan/mesh.ts
new file mode 100644
index 0000000000..af9e20c175
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/mesh.ts
@@ -0,0 +1,134 @@
+// A cell's near mesh as the plan worker hands it over (`CellMesh::to_bytes` of `mesh/mod.rs` in
+// obc-ground-plan), then the meshes of its storeys over the ground (`StoreyMesh::to_bytes` of `mesh/shell.rs`)
+// where it has any: the one reader of those bytes, in the form that pieces.ts uploads.
+
+const MAGIC = 0x4f424d05;
+const HEAD = 12;
+const STOREY_MAGIC = 0x4f425301;
+/** The storey mesh's head: its magic, cell, counts and top slots, then the triangles of each of its 7 parts (`PARTS`). */
+const STOREY_HEAD = 16;
+/** Region cells (2 × 2 grid cells) along a side of a cell, as `params::CELLS`, and the words of R on the cell and one ring. */
+const CELLS = 128;
+const REGION_WORDS = Math.ceil(((CELLS + 2) * (CELLS + 2)) / 32);
+/** Grid points along a side of a cell, both borders included, and the words of one bit each. */
+export const SIDE = 2 * CELLS + 1;
+export const SUNK_WORDS = Math.floor((SIDE * SIDE) / 32) + 1;
+
+export interface CellMesh {
+    /** The cell, zoom 16. */
+    x: number;
+    y: number;
+    /** Two words per corner: x and y in frame units from the cell's origin, the label and the terrain-vertex flag. */
+    corners: Uint32Array;
+    /** Three 16-bit corner indices per triangle, the strip's among them, each less the base of its run. */
+    triangles: Uint16Array;
+    /** The runs of triangles: their count and the base that their indices add. */
+    runs: { count: number; base: number }[];
+    /** The last runs, which draw only over level-18 nodes: the strip's triangles of halves that the level-17 terrain draws. */
+    level18Runs: number;
+    /** Four corner indices per step slot: a_p, a_q, b_q, b_p. */
+    steps: Uint32Array;
+    /** The last slots of `steps`: the end faces on the deck end lines. */
+    endFaces: number;
+    /** One bit per grid point (j × SIDE + i) whose region cells all lie in R: the terrain sinks there. */
+    sunk: Uint32Array;
+    /** Four words per culvert mouth: its corner on the water, its corner in the zone, the outline's direction and the water's half-width. */
+    culverts: Uint32Array;
+    /** The meshes of the cell's storeys over the ground, where it has any. */
+    storeys?: StoreyMesh;
+}
+
+/**
+ * The storeys' meshes of a cell: the sheets and the shells about them. A corner's height is that of its label plus its
+ * offset; the top's triangles come first, then the shell's (underside, edges, parapets, railings, posts, piers).
+ */
+export interface StoreyMesh {
+    /** Two words per corner, as the cell mesh's (never a terrain vertex), and each corner's offset in metres (f32 bits). */
+    corners: Uint32Array;
+    offsets: Uint32Array;
+    /** Three whole corner indices per triangle; the count of the top's, and the first of the railings' and of the piers'. */
+    triangles: Uint32Array;
+    top: number;
+    railings: number;
+    piers: number;
+    /** Four whole corner indices per slot (a_p, a_q, b_q, b_p): the tops' steps between two labels, then the undersides' risers. */
+    slots: Uint32Array;
+}
+
+/** The bytes that `cellMesh` reads: a cell's mesh, then its storeys' mesh where it has a storey corner. */
+export function meshBytes(mesh: Uint8Array, storeys?: Uint8Array): ArrayBuffer {
+    // A storey mesh's corner count follows its magic and its cell.
+    if (!storeys || !new Uint32Array(storeys.buffer, storeys.byteOffset, 4)[3]) {
+        return mesh.byteOffset === 0 && mesh.byteLength === mesh.buffer.byteLength ? (mesh.buffer as ArrayBuffer) : mesh.slice().buffer;
+    }
+    const out = new Uint8Array(mesh.byteLength + storeys.byteLength);
+    out.set(mesh);
+    out.set(storeys, mesh.byteLength);
+    return out.buffer;
+}
+
+export function cellMesh(bytes: ArrayBuffer): CellMesh {
+    const words = new Uint32Array(bytes);
+    const [magic, x, y, corners, triangles, , triangleRuns, steps, stepRuns, level18Runs, endFaces, mouths] = words.subarray(0, HEAD);
+    if (magic !== MAGIC) throw new Error(`not a ground plan mesh: ${magic.toString(16)}`);
+    let at = HEAD;
+    const take = (n: number) => words.subarray(at, (at += n));
+    const corner = words.slice(at, (at += 2 * corners));
+    /** Items of `size` corners in runs of (count, base), their 16-bit indices less the base. */
+    const items = (count: number, runs: number, size: number) => {
+        // Whole words, so that the indices upload as they are.
+        const table = take(2 * runs), short = new Uint16Array(bytes.slice(4 * at, 4 * (at += Math.ceil((size * count) / 2))), 0, size * count);
+        return { short, runs: Array.from({ length: runs }, (_, r) => ({ count: table[2 * r], base: table[2 * r + 1] })) };
+    };
+    const triangle = items(triangles, triangleRuns, 3), step = items(steps, stepRuns, 4), region = take(REGION_WORDS), culverts = take(4 * mouths).slice();
+    if (region.length !== REGION_WORDS || culverts.length !== 4 * mouths) throw new Error('a ground plan mesh ends early');
+    const storeys = at < words.length ? storeyMesh(bytes, at) : undefined;
+    return { x, y, corners: corner, triangles: triangle.short, runs: triangle.runs, level18Runs, steps: whole(step, 4), endFaces, sunk: sunkOf(region), culverts, storeys };
+}
+
+/** Items of runs as whole corner indices: the vertex stage reads them by index. */
+function whole({ short, runs }: { short: Uint16Array; runs: { count: number; base: number }[] }, size: number): Uint32Array {
+    const out = new Uint32Array(short.length);
+    let k = 0;
+    for (const { count, base } of runs) for (let n = 0; n < size * count; n++, k++) out[k] = short[k] + base;
+    return out;
+}
+
+/** The storey meshes from word `start` of `bytes` on. */
+function storeyMesh(bytes: ArrayBuffer, start: number): StoreyMesh {
+    const words = new Uint32Array(bytes, 4 * start);
+    const [magic, , , corners, triangles, triangleRuns, slots, slotRuns] = words.subarray(0, STOREY_HEAD);
+    if (magic !== STOREY_MAGIC) throw new Error(`not a storey mesh: ${magic.toString(16)}`);
+    let at = STOREY_HEAD;
+    const take = (n: number) => words.subarray(at, (at += n));
+    const corner = take(3 * corners), packed = new Uint32Array(2 * corners), offsets = new Uint32Array(corners);
+    for (let k = 0; k < corners; k++) {
+        packed[2 * k] = corner[3 * k];
+        packed[2 * k + 1] = corner[3 * k + 1];
+        offsets[k] = corner[3 * k + 2];
+    }
+    const items = (count: number, runs: number, size: number) => {
+        const table = take(2 * runs), short = new Uint16Array(bytes.slice(4 * (start + at), 4 * (start + (at += Math.ceil((size * count) / 2))))).subarray(0, size * count);
+        return { short, runs: Array.from({ length: runs }, (_, r) => ({ count: table[2 * r], base: table[2 * r + 1] })) };
+    };
+    const triangle = items(triangles, triangleRuns, 3), slot = items(slots, slotRuns, 4);
+    if (at > words.length) throw new Error('a storey mesh ends early');
+    // The parts' triangles: top, underside, edge, parapet, railing, post, pier.
+    const parts = words.subarray(STOREY_HEAD - 7, STOREY_HEAD), first = (k: number) => parts.subarray(0, k).reduce((sum, n) => sum + n, 0);
+    return { corners: packed, offsets, triangles: whole(triangle, 3), top: parts[0], railings: first(4), piers: first(6), slots: whole(slot, 4) };
+}
+
+/** The grid points whose region cells all lie in R: cells ⌊(i − 1) / 2⌋ to ⌊i / 2⌋ across, the same down. */
+function sunkOf(region: Uint32Array): Uint32Array {
+    const inR = (cx: number, cy: number) => {
+        const bit = (cy + 1) * (CELLS + 2) + cx + 1;
+        return ((region[bit >> 5] >>> (bit & 31)) & 1) === 1;
+    };
+    const out = new Uint32Array(SUNK_WORDS);
+    for (let j = 0; j < SIDE; j++) for (let i = 0; i < SIDE; i++) {
+        let all = true;
+        for (let cy = Math.floor((j - 1) / 2); cy <= j >> 1 && all; cy++) for (let cx = Math.floor((i - 1) / 2); cx <= i >> 1 && all; cx++) all = inR(cx, cy);
+        if (all) out[(j * SIDE + i) >> 5] |= 1 << ((j * SIDE + i) & 31);
+    }
+    return out;
+}
diff --git a/builder/web/src/lib/trailview/plan/mouth-in.wgsl b/builder/web/src/lib/trailview/plan/mouth-in.wgsl
new file mode 100644
index 0000000000..43dbf96191
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/mouth-in.wgsl
@@ -0,0 +1,46 @@
+// The corridors' varyings with a piece corner's label, and the mouth's hooks: this file takes the place of
+// roads/corridor-in.wgsl in the pieces of a junction with a stop arm (pieces.ts). A pixel in a stop arm's mouth
+// (terrain/mouth.wgsl) shades with the arm's look in the arm's frame. Its includes are relative to roads/, the folder
+// of the file that it replaces.
+// #include ../terrain/mouth.wgsl
+// #include ../plan/line-look.wgsl
+
+struct CorridorOut {
+    @builtin(position) @invariant clip: vec4f,
+    // Units about the anchor.
+    @location(0) u: vec2f,
+    @location(1) relative: vec3f,
+    @location(2) altitude: f32,
+    @location(3) @interpolate(flat) word: u32,
+    // Metres across and the half-width.
+    @location(4) road: vec2f,
+    @location(5) along: f32,
+    // A piece's normal in LOD-space axes; zero on a corridor.
+    @location(6) normal: vec3f,
+    // The corner's label in its cell's records.
+    @location(7) @interpolate(flat) label: u32,
+}
+
+fn corridor_in(in: CorridorOut) -> CorridorOut {
+    if ((in.word & MAT_BITS) == MAT_GROUND) {
+        return in;
+    }
+    let q = (in.u - vec2f(params.origin - surface.anchor)) * 16.0;
+    let mouth = m_mouth(params.block, m_junction(params.block, in.label), q, h_scale(params.block, q));
+    if (mouth.line == M_NONE) {
+        return in;
+    }
+    let look = line_look(m_line_finish(params.block, mouth.line));
+    // A paved arm draws neither its edge nor its edge lines in the mouth, as a junction's look past its frame; a soil
+    // arm keeps its tread's own margins.
+    let open = PIECE_INSIDE | ((CF_NO_LEFT_LINE | CF_NO_RIGHT_LINE) << FLAGS_SHIFT);
+    var out = in;
+    out.word = look_word(look.x, look.y, mouth.place.z) | select(open, 0u, soil_look(look.x));
+    out.road = mouth.place.xz;
+    out.along = mouth.place.y;
+    return out;
+}
+
+fn corridor_label(out: ptr, label: u32) {
+    (*out).label = label;
+}
diff --git a/builder/web/src/lib/trailview/plan/piece.wgsl b/builder/web/src/lib/trailview/plan/piece.wgsl
new file mode 100644
index 0000000000..083101e04c
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/piece.wgsl
@@ -0,0 +1,358 @@
+// The ground plan's mesh of a cell (pieces.ts), drawn before the terrain with the corridors' fragment stage
+// (PIECE): its triangles at the corners' heights from corners.wgsl, and its step slots, two triangles each
+// on the slot's four corners; and the meshes of its storeys over the ground, their slots all plain concrete. A terrain vertex of the strip is the terrain's own
+// vertex at its level-18 grid point, made by the same code, so the strip meets the terrain without a crack.
+// #include ../roads/corridor.wgsl
+// #include cells.wgsl
+
+// As Piece of corners.wgsl.
+struct Piece {
+    origin: vec2i,
+    corners: u32,
+    slots: u32,
+    out: u32,
+    faces: u32,
+    block: u32,
+    first: u32,
+    culverts: u32,
+    offsets: u32,
+    tris: u32,
+    top: u32,
+    // A storey mesh's first triangle of its railings and posts, and of its piers (mesh/shell.rs's PARTS).
+    railings: u32,
+    piers: u32,
+}
+
+@group(0) @binding(1) var piece: array;
+@group(0) @binding(2) var params: Piece;
+
+// As NO_LABEL of corners.wgsl: the plain terrain.
+const NO_LABEL: u32 = 33554431u;
+// As `cracks` in DEBUG_VIEWS of view.ts.
+const CRACKS_VIEW: u32 = 3u;
+// A step beside a paved face this high is a stone wall.
+const WALL_STEP_M: f32 = 0.5;
+// A bank this high or lower shades as the ground beside it, this high or higher as a face of its own.
+const BANK_LOW_M: f32 = 0.05;
+const BANK_HIGH_M: f32 = 0.5;
+
+struct PieceVertex {
+    u: vec2f,
+    s: vec2f,
+    h: f32,
+}
+
+// A corner's place and height: a terrain vertex as the terrain's vertex_main makes it, any other at its stored height.
+fn corner_at(k: u32) -> PieceVertex {
+    let w0 = piece[2u * k];
+    let w1 = piece[2u * k + 1u];
+    let q = vec2u(w0 & 0x7ffffu, w1 & 0x7ffffu);
+    if ((w1 >> 31u) == 1u) {
+        let u = params.origin - surface.anchor + vec2i(q / 16u);
+        // At the finest level 17 the mesh lies over level-17 nodes: the vertex is the terrain's level-17 vertex at
+        // the even point that it slides to, by the same code, so that it lands where the terrain's does (the strip
+        // at morph 1). The mesh's range lies within level 18's, so at the finest level 18 its nodes are level 18.
+        if (surface.finest < 18u) {
+            let even = u - ((surface.anchor + u) & vec2i(64));
+            let v = grid_vertex_by(even, 17u, !plan_near(even), true);
+            return PieceVertex(vec2f(u), v.s, v.h);
+        }
+        let v = grid_vertex_by(u, 18u, !plan_near(u), true);
+        return PieceVertex(vec2f(u), v.s, v.h);
+    }
+    let u = vec2f(params.origin - surface.anchor) + vec2f(q) / 16.0;
+    return PieceVertex(u, lod_space(u), bitcast(piece[params.out + 4u * k]));
+}
+
+// As vertex_main of terrain.wgsl, so that a terrain vertex lands bit for bit where the terrain's does: render space about the eye.
+fn corner_point(v: PieceVertex) -> vec3f {
+    var p = vec3f(to_render(v.s), select(-surface.above, v.h - frame.eye, known(v.h)));
+    p.z -= frame.curvature * dot(p.xy, p.xy);
+    return p;
+}
+
+fn octahedral(e: vec2f) -> vec3f {
+    var n = vec3f(e, 1.0 - abs(e.x) - abs(e.y));
+    if (n.z < 0.0) {
+        n = vec3f((1.0 - abs(n.yx)) * select(vec2f(-1.0), vec2f(1.0), n.xy >= vec2f(0.0)), n.z);
+    }
+    return normalize(n);
+}
+
+// A corner's look word marks a wall class's road surface (LOOK_WALL_SIDE of plan/corners.wgsl) in the bit of the
+// corridors' fine offset, which pieces do not read.
+const WALL_SIDE: u32 = 1u << FINE_SHIFT;
+
+// Whether corner k lies on the road surface of a wall class.
+fn on_road(k: u32) -> bool {
+    return (piece[params.out + 4u * k + 1u] & WALL_SIDE) != 0u;
+}
+
+// The next bit: on a bridge's ground stretch, whose wall is concrete (LOOK_BRIDGE_SIDE of plan/corners.wgsl). A
+// storey's corner holds its deck's build and planks in the bits from DECK_SHIFT, as corners.wgsl's.
+const BRIDGE_SIDE: u32 = 2u << FINE_SHIFT;
+const DECK_SHIFT: u32 = 29u;
+
+fn on_bridge(k: u32) -> bool {
+    return (piece[params.out + 4u * k + 1u] & BRIDGE_SIDE) != 0u;
+}
+
+// Whether corner k lies on water (MAT_WATER of corners.wgsl).
+fn on_water(k: u32) -> bool {
+    return (piece[params.out + 4u * k + 1u] & MAT_BITS) == MAT_WATER;
+}
+
+// A corner's metres across and half-width, and its metres along, from its look and place words.
+struct CornerPlace {
+    road: vec2f,
+    along: f32,
+}
+
+fn place_at(k: u32) -> CornerPlace {
+    let o = params.out + 4u * k;
+    return CornerPlace(vec2f(across_of(piece[o + 2u]), half_of(piece[o + 1u])), f32(piece[o + 2u] >> 12u) * ALONG_STEP);
+}
+
+// A corner's place in a ground corner's terms (corridor_ground): a paved corner lies on its way.
+fn ground_place(k: u32) -> CornerPlace {
+    let p = place_at(k);
+    if ((piece[params.out + 4u * k + 1u] & MAT_BITS) == MAT_GROUND) {
+        return p;
+    }
+    return CornerPlace(vec2f(abs(p.road.x) - p.road.y, p.road.y), p.along);
+}
+
+fn piece_out(v: PieceVertex, word: u32, place: CornerPlace, normal: vec3f) -> CorridorOut {
+    var out: CorridorOut;
+    let p = corner_point(v);
+    out.clip = frame.view_proj * vec4f(p, 1.0);
+    // The debug views show the terrain alone, as the corridors do; the crack and owned views show the meshes too.
+    if (frame.debug != 0u && frame.debug != CRACKS_VIEW && frame.debug != OWNED_VIEW) {
+        out.clip = vec4f(0.0, 0.0, 2.0, 1.0);
+    }
+    out.u = v.u;
+    out.relative = p;
+    out.altitude = v.h;
+    out.word = word;
+    out.road = place.road;
+    out.along = place.along;
+    out.normal = normal;
+    return out;
+}
+
+@vertex
+fn piece_vertex(@builtin(vertex_index) k: u32) -> CorridorOut {
+    let o = params.out + 4u * k;
+    var out = piece_out(corner_at(k), piece[o + 1u], place_at(k), octahedral(unpack2x16snorm(piece[o + 3u])));
+    if (MOUTH) {
+        // The corner's label, as corners.wgsl reads it.
+        let label = (piece[2u * k] >> 19u) | (((piece[2u * k + 1u] >> 19u) & 0xfffu) << 13u);
+        corridor_label(&out, select(label, 0xffffffffu, label == NO_LABEL));
+    }
+    return out;
+}
+
+// Six vertices per step slot a_p, a_q, b_q, b_p: a lies right of p → q from above, b left. The slot faces its
+// lower side. Its two triangles take only its four corners, so every edge it shares with a face or a
+// neighbour slot is that edge exactly and no pixel falls between them at any heights. Where the step turns,
+// the diagonal joins the lower corners at p and q: the fold then hangs below both faces, hidden.
+@vertex
+fn slot_vertex(@builtin(vertex_index) index: u32) -> CorridorOut {
+    let w = params.slots + 4u * (index / 6u);
+    var c = array(corner_at(piece[w]), corner_at(piece[w + 1u]), corner_at(piece[w + 2u]), corner_at(piece[w + 3u]));
+    let dp = c[0].h - c[3].h;
+    let dq = c[1].h - c[2].h;
+    let turns = dp * dq < 0.0;
+    // The diagonal a_p, b_q, or a_q, b_p where a stands higher at p and lower at q.
+    var order = array(0u, 1u, 2u, 0u, 2u, 3u);
+    if (turns && dp > 0.0) {
+        order = array(0u, 1u, 3u, 1u, 2u, 3u);
+    }
+    let at = order[index % 6u];
+    let v = c[at];
+    var place = ground_place(piece[w + at]);
+    let end = select(dq, dp, at == 0u || at == 3u);
+    // The rise of a over b: of the slot, or where it turns, of the triangle's visible lobe: the first
+    // triangle holds the lobe where a stands higher, the second the one where b does.
+    let rise = select(dp + dq, select(min(dp, dq), max(dp, dq), index % 6u < 3u), turns);
+    let step = abs(end);
+    // Toward b, the left of p → q, where a stands higher.
+    let along = c[1].s - c[0].s;
+    let left = normalize(vec2f(-along.y, along.x) + vec2f(1e-9, 0.0));
+    // An end face (the mesh's last slots, on a deck end line) is plain concrete at any height. A step whose upper
+    // side is water falls as water (its look foams on the upright slot). A step beside a wall class's road surface
+    // that stands as high as a wall is a wall, of concrete beside a bridge's ground stretch; any other is a bank of
+    // the ground, as on a path or a track.
+    let upper = select(vec2u(piece[w + 2u], piece[w + 3u]), vec2u(piece[w], piece[w + 1u]), rise > 0.0);
+    let wall = (on_road(piece[w]) || on_road(piece[w + 3u])) && max(abs(dp), abs(dq)) >= WALL_STEP_M;
+    var mat = select(MAT_GROUND, select(MAT_WALL, MAT_CAP, on_bridge(piece[w]) || on_bridge(piece[w + 3u])), wall);
+    if (on_water(upper.x) || on_water(upper.y)) {
+        mat = MAT_WATER;
+    }
+    mat = select(mat, MAT_CAP, index / 6u >= params.faces);
+    // A bank's level normal is as long as its share of the light: a step of millimetres shades as the ground
+    // beside it, a real one as a face of its own (corridor_ground).
+    let share = select(smoothstep(BANK_LOW_M, BANK_HIGH_M, step), 1.0, mat != MAT_GROUND);
+    let normal = vec3f(select(-left, left, rise > 0.0) * share, 0.0);
+    // A wall whose road stands on its higher side holds the road up, and the face that it continues lies below it; else
+    // that face lies above it (wall_rock of roads/corridor.wgsl).
+    let fill = select(on_road(piece[w + 3u]), on_road(piece[w]), rise > 0.0);
+    let word = mat | (480u << HALF_SHIFT) | select(0u, WALL_FILL, mat == MAT_WALL && fill);
+    if (mat == MAT_WALL || mat == MAT_CAP) {
+        place = CornerPlace(vec2f(v.h - min(c[0].h, c[3].h), half_of(word)), length(v.s - c[0].s));
+    }
+    return piece_out(v, word, place, normal);
+}
+
+// A culvert's mouth (the mesh's mouths, 4 words each: its corner on the water and its corner in the zone, the zone
+// outline's direction and the water's half-width): the end of a concrete pipe as wide as the water, which stands
+// MOUTH_FRONT_M out of the way's bank, its shell MOUTH_SHELL_M thick and its inside dark at the bank. Its frame: x
+// along the outline, y into the zone, z up from the water. The pipe's middle lies under the water, so the water runs
+// into it, and it runs along the water. A mouth lower than MOUTH_LOW_M draws no model. The pipe is as wide as the
+// water (`faces::CulvertMouth`): at a crossing and a ford at most `culvert_width_m`, at a mapped culvert and a
+// tunnel's start at most twice `HALF_MAX_M`.
+const MOUTH_SIDES: u32 = 12u;
+const MOUTH_QUADS: u32 = 4u * MOUTH_SIDES;
+const MOUTH_FRONT_M: f32 = 0.25;
+const MOUTH_SHELL_M: f32 = 0.1;
+const MOUTH_LOW_M: f32 = 0.15;
+
+struct MouthFrame {
+    // The opening's half-width along x, its half-height and its middle's z.
+    rx: f32,
+    rz: f32,
+    zc: f32,
+    // The water's direction in the frame (x, y): the pipe runs along it.
+    d: vec2f,
+}
+
+// A point of an ellipse about the opening's middle, `grow` metres out of the opening's rim, at angle t, at y.
+fn mouth_rim(f: MouthFrame, t: f32, grow: f32, y: f32) -> vec3f {
+    return vec3f((f.rx + grow) * cos(t), y, f.zc + (f.rz + grow) * sin(t));
+}
+
+// The point of the pipe at y behind the rim's point p of its front, along the water.
+fn mouth_back(f: MouthFrame, p: vec3f, y: f32) -> vec3f {
+    return vec3f(p.x + (y - p.y) / f.d.y * f.d.x, y, p.z);
+}
+
+// The rim's point at the pipe's dark end, just in front of the zone.
+fn mouth_end(f: MouthFrame, p: vec3f) -> vec3f {
+    return mouth_back(f, p, -0.02);
+}
+
+@vertex
+fn culvert_vertex(@builtin(vertex_index) index: u32) -> CorridorOut {
+    let w = params.culverts + 4u * (index / (6u * MOUTH_QUADS));
+    let cw = corner_at(piece[w]);
+    let cz = corner_at(piece[w + 1u]);
+    let e2 = unpack2x16snorm(piece[w + 2u]);
+    let half = bitcast(piece[w + 3u]);
+    // The frame in render space's metres (y north): x along the outline, y into the zone.
+    let ex = normalize(vec2f(e2.x, -e2.y) + vec2f(1e-9, 0.0));
+    let water = normalize(cz.s - cw.s + vec2f(1e-9, 0.0));
+    var ey = vec2f(-ex.y, ex.x);
+    ey *= select(-1.0, 1.0, dot(ey, water) >= 0.0);
+    var f: MouthFrame;
+    f.d = vec2f(dot(water, ex), max(dot(water, ey), 0.5));
+    // The pipe as wide as the water across its line, so as wide as the water's cut through the outline along it; as
+    // high as the bank leaves room for the shell.
+    let rise = cz.h - cw.h;
+    let r = max(1.03 * half, 0.3);
+    f.rx = r / f.d.y;
+    f.zc = -0.2 * r;
+    f.rz = clamp(rise - MOUTH_SHELL_M - f.zc, 0.15, r);
+    // The quad and its corner, MOUTH_SIDES of each part about the opening: the pipe's front ring, its outside into
+    // the bank, its inside, and its dark end (a triangle each, one corner twice).
+    let q = (index / 6u) % MOUTH_QUADS;
+    let corner = array(0u, 1u, 2u, 0u, 2u, 3u)[index % 6u];
+    let t0 = 6.2831853 * f32(q % MOUTH_SIDES) / f32(MOUTH_SIDES);
+    let t1 = 6.2831853 * f32(q % MOUTH_SIDES + 1u) / f32(MOUTH_SIDES);
+    let tm = 0.5 * (t0 + t1);
+    let y0 = -MOUTH_FRONT_M;
+    let shell = MOUTH_SHELL_M;
+    var p: array;
+    var n = vec3f(0.0, -1.0, 0.0);
+    var word = MAT_CAP | (480u << HALF_SHIFT);
+    switch (q / MOUTH_SIDES) {
+        case 0u: {
+            p = array(mouth_rim(f, t0, 0.0, y0), mouth_rim(f, t0, shell, y0), mouth_rim(f, t1, shell, y0), mouth_rim(f, t1, 0.0, y0));
+        }
+        case 1u: {
+            let a = mouth_rim(f, t0, shell, y0);
+            let b = mouth_rim(f, t1, shell, y0);
+            p = array(a, mouth_back(f, a, 0.1), mouth_back(f, b, 0.1), b);
+            n = normalize(vec3f(f.rz * cos(tm), 0.0, f.rx * sin(tm)));
+        }
+        case 2u: {
+            let a = mouth_rim(f, t0, 0.0, y0);
+            let b = mouth_rim(f, t1, 0.0, y0);
+            p = array(a, mouth_end(f, a), mouth_end(f, b), b);
+            n = normalize(vec3f(-f.rz * cos(tm), 0.0, -f.rx * sin(tm)));
+        }
+        default: {
+            let mid = mouth_end(f, vec3f(0.0, y0, f.zc));
+            p = array(mid, mouth_end(f, mouth_rim(f, t0, 0.0, y0)), mouth_end(f, mouth_rim(f, t1, 0.0, y0)), mid);
+            word |= CULVERT_DARK;
+        }
+    }
+    let l = select(p[corner], vec3f(0.0), rise < MOUTH_LOW_M);
+    let s = 0.5 * (cw.s + cz.s) + l.x * ex + l.y * ey;
+    let v = PieceVertex(surface.part + vec2f(s.x, -s.y) / surface.unit, s, cw.h + l.z);
+    let place = CornerPlace(vec2f(l.z - f.zc, half_of(word)), l.x);
+    return piece_out(v, word, place, vec3f(n.x * ex + n.y * ey, n.z));
+}
+
+// A storey mesh's triangle corner (three corners a triangle from `tris`): its top takes its corners' looks and
+// normals, or planks; its shell (underside, edges, parapets, railings, posts, piers) is flat, of its deck's build
+// (DECK_SHIFT of plan/corners.wgsl, its first corner's): the slab and its edge feature of concrete, dark timber or
+// steel, a railing of wood on timber and else of steel, the piers concrete.
+@vertex
+fn storey_vertex(@builtin(vertex_index) index: u32) -> CorridorOut {
+    let i = index / 3u;
+    let t = params.tris + 3u * i;
+    let k = piece[t + index % 3u];
+    let v = corner_at(k);
+    let a = corner_at(piece[t]);
+    let b = corner_at(piece[t + 1u]);
+    let c = corner_at(piece[t + 2u]);
+    let deck = piece[params.out + 4u * piece[t] + 1u] >> DECK_SHIFT;
+    let build = select(select(MAT_CAP, MAT_STEEL, (deck & 3u) == 2u), MAT_TIMBER, (deck & 3u) == 1u);
+    var out: CorridorOut;
+    if (i < params.top) {
+        let o = params.out + 4u * k;
+        var word = (piece[o + 1u] & ~(7u << DECK_SHIFT)) | STOREY_TOP;
+        if ((deck & 4u) != 0u) {
+            word = (word & ~MAT_BITS) | MAT_PLANKS;
+        }
+        out = piece_out(v, word, place_at(k), octahedral(unpack2x16snorm(piece[o + 3u])));
+    } else {
+        // Counter-clockwise from outside in lod space (east, north, up): the normal points out.
+        let n = normalize(cross(vec3f(b.s - a.s, b.h - a.h), vec3f(c.s - a.s, c.h - a.h)) + vec3f(0.0, 0.0, 1e-9));
+        var mat = select(build, select(MAT_STEEL, MAT_WOOD, build == MAT_TIMBER), i >= params.railings);
+        mat = select(mat, MAT_CAP, i >= params.piers);
+        let word = mat | (480u << HALF_SHIFT);
+        out = piece_out(v, word, CornerPlace(vec2f(v.h, half_of(word)), v.s.x + v.s.y), n);
+    }
+    // A storey stands on no terrain vertex: a triangle with a corner of no height yet draws nothing.
+    if (!known(a.h) || !known(b.h) || !known(c.h)) {
+        out.clip = vec4f(0.0, 0.0, 2.0, 1.0);
+    }
+    return out;
+}
+
+// A storey mesh's corner height, NONE before the corners pass.
+fn storey_height(k: u32) -> f32 {
+    return bitcast(piece[params.out + 4u * k]);
+}
+
+// A storey mesh's triangle corner in the sun's frame, as a caster of the shadow map: at its stored height.
+@vertex
+fn storey_caster(@builtin(vertex_index) index: u32) -> @builtin(position) vec4f {
+    let t = params.tris + 3u * (index / 3u);
+    let k = piece[t + index % 3u];
+    let q = vec2u(piece[2u * k] & 0x7ffffu, piece[2u * k + 1u] & 0x7ffffu);
+    let u = vec2f(params.origin - surface.anchor) + vec2f(q) / 16.0;
+    let all = known(storey_height(piece[t])) && known(storey_height(piece[t + 1u])) && known(storey_height(piece[t + 2u]));
+    return select(vec4f(0.0, 0.0, 2.0, 1.0), frame.view_proj * vec4f(corner_point(PieceVertex(u, lod_space(u), storey_height(k))), 1.0), all);
+}
diff --git a/builder/web/src/lib/trailview/plan/pieces.test.ts b/builder/web/src/lib/trailview/plan/pieces.test.ts
new file mode 100644
index 0000000000..7261b7685e
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/pieces.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it } from 'vitest';
+import { anchorAt } from '../frame/space';
+import { CALM, cdlod, RANGE } from '../terrain/lod';
+import type { CellMesh } from './mesh';
+import { meshLevel, Pieces, splitMouths } from './pieces';
+
+describe('splitMouths', () => {
+    it("moves a run's mouth triangles to its end and keeps every triangle with its first corner", () => {
+        // The corners' labels in their words, as the mesh packs them: 13 bits in the first word, 12 in the second.
+        const labels = [0, 1, 2, 3, 8193, 1, 2, 3];
+        const corners = new Uint32Array(labels.flatMap(l => [((l & 0x1fff) << 19) >>> 0, ((l >>> 13) << 19) >>> 0]));
+        // Two runs; the second's indices add its base, 4.
+        const runs = [[[0, 1, 2], [1, 2, 3], [3, 0, 1], [2, 3, 0]], [[0, 1, 2], [3, 2, 1], [1, 0, 3]]];
+        const mesh: CellMesh = {
+            x: 0,
+            y: 0,
+            corners,
+            triangles: new Uint16Array(runs.flat(2)),
+            runs: [{ count: 4, base: 0 }, { count: 3, base: 4 }],
+            level18Runs: 0,
+            steps: new Uint32Array(0),
+            endFaces: 0,
+            sunk: new Uint32Array(0),
+            culverts: new Uint32Array(0),
+        };
+        // Label 8193 has a bit in the second word.
+        expect(splitMouths(mesh, new Set([1, 8193]))).toEqual([1, 2]);
+        const tris = Array.from({ length: mesh.triangles.length / 3 }, (_, t) => Array.from(mesh.triangles.subarray(3 * t, 3 * t + 3)));
+        expect(tris.slice(0, 4)).toEqual([[0, 1, 2], [3, 0, 1], [2, 3, 0], [1, 2, 3]]);
+        expect(tris.slice(4)).toEqual([[3, 2, 1], [0, 1, 2], [1, 0, 3]]);
+    });
+});
+
+describe('meshLevel', () => {
+    /** The mesh levels of frames at these finest levels, from a calm start. */
+    const levels = (finest: number[]) => {
+        let calm = CALM;
+        return finest.map(f => {
+            const next = meshLevel(f, calm);
+            calm = next.calm;
+            return next.level;
+        });
+    };
+
+    it('draws over level 18, or 17 at a lower quality, and stops at once below 17', () => {
+        expect(levels([18, 17, 18, 16, 15])).toEqual([18, 17, 18, 0, 0]);
+    });
+
+    it('draws again only after CALM frames in a row at level 17 or finer', () => {
+        const back = levels([16, ...Array(CALM).fill(17)]);
+        expect(back.slice(0, CALM)).toEqual(Array(CALM).fill(0));
+        expect(back[CALM]).toBe(17);
+        // A dip to 16 starts the count again.
+        expect(levels([16, ...Array(CALM - 1).fill(18), 16, 18]).every(level => level === 0)).toBe(true);
+    });
+});
+
+describe('Pieces', () => {
+    it('draws again after a dip to 16 in a still view: it asks for the frames that bring the meshes back', () => {
+        const pieces = new Pieces(() => null), eye = { anchor: anchorAt(8.4048, 46.8219), above: 1.7 };
+        const frame = (finest: number) => pieces.update(cdlod(eye, RANGE.least, finest), eye, () => 0, () => '', [], () => true, () => true);
+        for (const finest of [18, 17, 16]) frame(finest);
+        expect(pieces.level).toBe(0);
+        // The quality is back at 17 and nothing else moves: only the meshes keep the frames going.
+        let frames = 1;
+        for (frame(17); pieces.returning && frames < 10 * CALM; frames++) frame(17);
+        expect(pieces.level).toBe(17);
+        expect(frames).toBe(CALM);
+    });
+
+    it('reads its pages again after a rest below 17, as pages came and went while it rested', () => {
+        const pieces = new Pieces(() => null), eye = { anchor: anchorAt(8.4048, 46.8219), above: 1.7 };
+        // A cell's mesh with no corners: the head (MAGIC, HEAD 12 words) and the region words.
+        const words = new Uint32Array(12 + Math.ceil((130 * 130) / 32));
+        words[0] = 0x4f424d05;
+        pieces.add({ level: 16, x: 34_307, y: 23_107 }, words.buffer, 0, new Set());
+        let reads = 0;
+        const frame = (finest: number) => pieces.update(cdlod(eye, RANGE.least, finest), eye, () => 0, () => `${reads++}`, [], () => true, () => true);
+        frame(18);
+        frame(16);
+        const before = reads;
+        // No page is touched in this frame: only the rest makes the piece read its keys.
+        frame(17);
+        expect(reads).toBeGreaterThan(before);
+    });
+});
diff --git a/builder/web/src/lib/trailview/plan/pieces.ts b/builder/web/src/lib/trailview/plan/pieces.ts
new file mode 100644
index 0000000000..cff82aceae
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/pieces.ts
@@ -0,0 +1,637 @@
+// The ground plan's meshes near the eye (`ground=plan`): each cell's mesh from the plan worker on the device,
+// its corners' heights, normals and looks made once by a compute pass (corners.wgsl), drawn before the
+// terrain with the corridors' fragment stage (piece.wgsl). A cell's mesh draws over the nodes of the finest
+// level, 18 or 17, within level 18's range; the terrain's vertices there take no snap of their own and sink
+// inside the mesh's owned region (cells.wgsl), and the strip, made of the terrain's own vertices at the
+// region's border, closes the mesh against it. Past them the terrain draws the records' far look. A cell's storeys
+// over the ground draw with it: their corners from the same pass, their sheets and shells with piece.wgsl, and they
+// cast into the shadow map.
+import type { Gpu } from '../gpu/device';
+import { MOUTH } from '../gpu/include';
+import { layouts } from '../gpu/layouts';
+import { wgsl } from '../gpu/wgsl';
+import { CASTER_DEPTH, CASTER_PRIMITIVE } from '../light/shadow';
+import { DEPTH, sceneFormat } from '../resolve/targets';
+import { CALM, CELL_LEVEL, distances, key, MORPH, size, type Eye, type Node, type Rule } from '../terrain/lod';
+import { touches } from '../terrain/pages';
+import { cellMesh, SUNK_WORDS, type CellMesh, type StoreyMesh } from './mesh';
+
+/** The cells per side of the window about the eye's cell, the words before the slots, and the slots of sunk points: as cells.wgsl. */
+export const WINDOW = 7;
+const HEAD = 64;
+const SLOTS = 24;
+/** The bytes of the cells buffer that the terrain and the pieces read. */
+export const CELLS_BYTES = 4 * (HEAD + SLOTS * SUNK_WORDS);
+/** A cell's mesh builds this far before the terrain draws the whole cell at level 18: about 10 s of a car. */
+const LEAD_M = 150;
+/** Corners whose heights the compute pass makes in a frame, past the plain terrain's corners of the pieces in view: a town cell takes about eight frames. */
+const CORNERS_PER_FRAME = 8192;
+/** Corners per workgroup of the pass: GROUP_CORNERS of corners.wgsl. */
+const GROUP_CORNERS = 12;
+/** A pass of the plain terrain's corners charges one corner of the budget for this many: the other corners return at once. */
+const TERRAIN_SHARE = 8;
+/** The top bit of the first corner in the parameters: the pass makes only the plain terrain's corners. */
+const TERRAIN_BIT = 0x80000000;
+/** A piece whose cell reaches this far before the level-18 plateau's end draws with the fade: the metres of four mesh triangles. */
+const FADE_MARGIN_M = 10;
+/** Bytes of a piece's parameters, as Piece of piece.wgsl (corners.wgsl reads the first 48). */
+const PARAMS_BYTES = 64;
+/** The vertices of a culvert mouth's model: MOUTH_QUADS of plan/piece.wgsl, six each. */
+const CULVERT_VERTICES = 6 * 48;
+/** The level-18 nodes per side of the block whose stamps a cell's corners read, NODES of corners.wgsl: the cell's four and one more on each side. */
+const NODES = 6;
+
+/** What a pass makes: every corner, or only the plain terrain's corners, the ones that read the drawn page. */
+type Make = 'all' | 'terrain';
+
+const more = (a: Make | undefined, b: Make): Make => (a === 'all' || b === 'all' ? 'all' : 'terrain');
+
+interface Piece {
+    node: Node;
+    mesh: CellMesh;
+    /** Per run of triangles, how many of its last triangles belong to a junction with a stop arm: they draw with the mouth's pipeline. */
+    mouths: number[];
+    /** The first word of the cell's records block that its labels index. */
+    block: number;
+    /** Its buffers, and the compute bind group with the stamp data of the pass that it was made for (`bound`). */
+    gpu?: { data: GPUBuffer; indices: GPUBuffer; params: GPUBuffer; draw: GPUBindGroup; compute?: GPUBindGroup; stamps?: GPUBuffer; bound?: Make; storeys?: StoreysGpu };
+    /** Whether its corners hold their heights, what a pass must make, and how many corners the pass made so far. */
+    computed: boolean;
+    stale?: Make;
+    done: number;
+    /** Whether the plain terrain's corners of a stale `all` piece hold the current pages, or its pass makes them all from its start. */
+    grounded?: boolean;
+    /** Its corners' box in world units, and the keys of the raw stored pages and the drawn pages that the pass reads there (Pages.reads). */
+    box: [number, number, number, number];
+    plain?: string;
+    drawn?: string;
+    /** Whether the stamp data of its stampNodes is known: a labelled corner reads it, so the pass waits for it. */
+    stamped: boolean;
+}
+
+/** A cell's storeys on the device: their buffer (as a piece's, with the triangles and the offsets after the slots), parameters, draw and cast groups, and the compute group of the last stamps. */
+interface StoreysGpu { data: GPUBuffer; params: GPUBuffer; draw: GPUBindGroup; cast?: GPUBindGroup; compute?: GPUBindGroup; computed: boolean }
+
+interface Resources {
+    gpu: Gpu;
+    frame: GPUBuffer;
+    cells: GPUBuffer;
+    records: GPUTexture;
+    /** The road and path profiles, as stamp-core.wgsl reads them. */
+    profiles: GPUBuffer;
+    /** The triangles and the step slots of a cell drawn wholly at level 18, and of one drawn in part (`cut`); the triangles of a
+     * stop arm's junction, whose pixels find the mouth (plan/mouth-in.wgsl), with pipelines of their own, so that no other pixel pays for it. */
+    triangles: GPURenderPipeline;
+    mouthTriangles: GPURenderPipeline;
+    cutMouthTriangles: GPURenderPipeline;
+    slots: GPURenderPipeline;
+    cutTriangles: GPURenderPipeline;
+    cutSlots: GPURenderPipeline;
+    /** The culvert mouths' models (`culvert_vertex` of plan/piece.wgsl). */
+    culverts: GPURenderPipeline;
+    cutCulverts: GPURenderPipeline;
+    /** The storeys' triangles, whole and cut, and their caster into the shadow map. */
+    storeys: GPURenderPipeline[];
+    storeyCaster: GPURenderPipeline;
+    corners: GPUComputePipeline;
+    drawLayout: GPUBindGroupLayout;
+    computeLayout: GPUBindGroupLayout;
+}
+
+export interface PiecesStats {
+    /** Cells whose mesh is on the device, that draw, and that draw in view; their triangles and step slots in view. */
+    cells: number;
+    drawn: number;
+    inView: number;
+    triangles: number;
+    steps: number;
+    /** The storeys' triangles and slots in view. */
+    storeyTriangles: number;
+    /** The pieces' GPU bytes, the storeys' among them. */
+    bytes: number;
+    /** Milliseconds from the first frame with a wanted cell that does not draw to the next frame in which all draw. */
+    ready: number;
+}
+
+/** The cells of zoom 16 that hold a point near the eye: those within `reach` cells of the eye's. */
+function cellsAbout(eye: Eye, reach: number): Node[] {
+    const s = size(CELL_LEVEL), x = Math.floor((eye.anchor.whole[0] + eye.anchor.part[0]) / s), y = Math.floor((eye.anchor.whole[1] + eye.anchor.part[1]) / s);
+    const out: Node[] = [];
+    for (let j = -reach; j <= reach; j++) for (let i = -reach; i <= reach; i++) out.push({ level: CELL_LEVEL, x: x + i, y: y + j });
+    return out;
+}
+
+/** The level-18 nodes whose stamps a cell's corners read, row by row from the north-west, as corners.wgsl indexes them. */
+export function stampNodes(cell: Node): Node[] {
+    return Array.from({ length: NODES * NODES }, (_, i) => ({ level: 18, x: cell.x * 4 - 1 + (i % NODES), y: cell.y * 4 - 1 + Math.floor(i / NODES) }));
+}
+
+/** Whether a quarter of a cell lies nearer than level 18's range, where the meshes draw: at the finest level 18, its level-18 nodes. */
+function inRange(rule: Rule, eye: Eye, cell: Node): boolean {
+    for (let q = 0; q < 4; q++) if (distances(eye, { level: CELL_LEVEL + 1, x: 2 * cell.x + (q & 1), y: 2 * cell.y + (q >> 1) })[0] < rule.range / 2 ** 18) return true;
+    return false;
+}
+
+/** The coarsest terrain level that the meshes draw over. With a coarser finest level they rest. */
+export const COARSEST_MESH = 17;
+
+/**
+ * The level of the nodes that the meshes draw over at the terrain's `finest` level, 0 for none, after `calm` frames in a
+ * row at COARSEST_MESH or finer: 18, or 17 at a lower quality. Below 17 they stop at once and draw again after CALM frames, so a
+ * quality that steps between 17 and 16 does not switch them every few frames. Returns the calm frames with this one.
+ */
+export function meshLevel(finest: number, calm: number): { level: number; calm: number } {
+    const now = finest >= COARSEST_MESH ? Math.min(calm + 1, CALM) : 0;
+    return { level: now >= CALM ? Math.min(finest, 18) : 0, calm: now };
+}
+
+/**
+ * The cells whose meshes the eye wants, at any finest level, so that a return to level 17 builds nothing again: those
+ * in level 18's range, and those that will be within LEAD_M, each with its metres from the eye on the ground, as
+ * `nearCells` has them.
+ */
+export function meshCells(rule: Rule, eye: Eye): { node: Node; distance: number }[] {
+    // Level 18's range: at the finest level 18, a level-17 node splits nearer than this.
+    const split = rule.range / 2 ** 18, ground = { anchor: eye.anchor, above: 0 };
+    return cellsAbout(eye, WINDOW >> 1).filter(cell => distances(eye, cell)[0] < split + LEAD_M).map(node => ({ node, distance: distances(ground, node)[0] }));
+}
+
+export class Pieces {
+    private pieces = new Map();
+    private resources?: Resources;
+    /** The cells that draw, nearest first, those in view, and those of them that reach past the level-18 plateau, where they fade out. */
+    private drawn: Piece[] = [];
+    private inView: Piece[] = [];
+    private cut = new Set();
+    private window?: [number, number];
+    private slots = new Map();
+    private cellsDirty = true;
+    private readyFrom?: number;
+    private readyMs = 0;
+    /** The level of the nodes that the meshes draw over this frame, 0 for none, and the calm frames of meshLevel. */
+    private meshLevel = 0;
+    private calm = CALM;
+    /** Whether the terrain's finest level is coarser than COARSEST_MESH: the meshes ask for no stamp and make no corner. */
+    private resting = false;
+    /** The frame uniform of the sun's view, for the storeys' casters. */
+    private sun?: GPUBuffer;
+
+    /** `stamps` gives a node's stamp data, null for none, undefined while it is on its way, and asks for it. */
+    constructor(private readonly stamps: (node: Node) => Uint32Array | null | undefined) {}
+
+    /** A cell's mesh arrives with the first word of its records block, and the labels of its junctions with a stop arm. */
+    add(node: Node, bytes: ArrayBuffer, block: number, mouths: Set): void {
+        this.remove(node);
+        const mesh = cellMesh(bytes), s = size(CELL_LEVEL), box: [number, number, number, number] = [Infinity, Infinity, -Infinity, -Infinity];
+        // A corner's x and y in frame units, 16 to a world unit, from the cell's origin.
+        for (let k = 0; k < mesh.corners.length; k += 2) {
+            const x = node.x * s + (mesh.corners[k] & 0x7ffff) / 16, y = node.y * s + (mesh.corners[k + 1] & 0x7ffff) / 16;
+            box[0] = Math.min(box[0], x);
+            box[1] = Math.min(box[1], y);
+            box[2] = Math.max(box[2], x);
+            box[3] = Math.max(box[3], y);
+        }
+        this.pieces.set(key(node), { node, mesh, mouths: splitMouths(mesh, mouths), block, computed: false, stale: 'all', done: 0, box, stamped: false });
+    }
+
+    remove(node: Node): void {
+        const piece = this.pieces.get(key(node));
+        if (!piece) return;
+        this.release(piece);
+        this.pieces.delete(key(node));
+        this.cellsDirty = true;
+    }
+
+    private release(piece: Piece): void {
+        const r = this.resources;
+        if (r && piece.gpu) for (const buffer of [piece.gpu.data, piece.gpu.indices, piece.gpu.params, piece.gpu.stamps, piece.gpu.storeys?.data, piece.gpu.storeys?.params]) if (buffer) r.gpu.destroy('plan', buffer);
+        piece.gpu = undefined;
+        piece.computed = false;
+        piece.stale = 'all';
+        piece.done = 0;
+    }
+
+    /**
+     * Takes the pipelines on a device: `frame` is the frame uniform of the eye's view, `cells` the buffer of CELLS_BYTES, `records` the
+     * records' texture, `profiles` the stamps' profile table.
+     */
+    async attach(gpu: Gpu, frame: GPUBuffer, cells: GPUBuffer, records: GPUTexture, profiles: GPUBuffer): Promise {
+        this.resources = undefined;
+        for (const piece of this.pieces.values()) Object.assign(piece, { gpu: undefined, computed: false, stale: 'all', done: 0 });
+        const made = await gpu.once(piecePipelines);
+        this.resources = { gpu, frame, cells, records, profiles, ...made };
+        this.cellsDirty = true;
+    }
+
+    /** Takes the frame uniform of the sun's view: the storeys then cast into the shadow map. */
+    castWith(sun: GPUBuffer): void {
+        this.sun = sun;
+        for (const piece of this.pieces.values()) if (piece.gpu?.storeys) piece.gpu.storeys.cast = undefined;
+    }
+
+    /**
+     * Picks the cells that draw: those in level 18's range whose mesh holds its heights, at the mesh level. A cell `rests` where
+     * a page of the mesh level in it found no room and a page coarser than COARSEST_MESH stands in its place (Pages.fallback);
+     * then every cell in range rests, as below COARSEST_MESH, and draws again after CALM frames. So inside the range, a shortage
+     * leaves every cell with its mesh or none: a resting cell beside a drawing one would show a step or a slit where a road
+     * crosses their border. Over a page of level 17 in place of one of 18 a mesh draws as it does in a load: the strip and the
+     * plain corners read that page through the terrain's own code. `block` gives each cell's records block, `reads` the key of the
+     * pages that the pass reads in a box (Pages.reads), which can change only where a page of `touched` lies; `visible` whether
+     * a cell can show, `settled` whether a cell's mesh came or never comes. Returns whether what draws changed.
+     */
+    update(rule: Rule, eye: Eye, block: (node: Node) => number | undefined, reads: (box: [number, number, number, number], stored: boolean) => string, touched: Node[],
+        visible: (node: Node) => boolean, settled: (node: Node) => boolean, rests: (cell: Node) => boolean = () => false): boolean {
+        // At rest the recovery from the shortage that took the level away comes first: the pieces keep what they hold.
+        // `touched` names only this frame's pages, so a piece reads its page keys again after a rest.
+        const resting = rule.finest < COARSEST_MESH;
+        if (resting && !this.resting) for (const piece of this.pieces.values()) piece.plain = undefined;
+        this.resting = resting;
+        for (const piece of this.resting ? [] : this.pieces.values()) {
+            // Every node is asked for at once.
+            const now = block(piece.node) ?? -1, ready = stampNodes(piece.node).map(this.stamps).every(data => data !== undefined);
+            // A new piece takes its first keys.
+            const read = piece.plain === undefined || touched.some(node => touches(node, piece.box));
+            const plain = read ? reads(piece.box, true) : piece.plain, drawn = read ? reads(piece.box, false) : piece.drawn;
+            const all = now !== piece.block || plain !== piece.plain || ready !== piece.stamped;
+            if (all || drawn !== piece.drawn) {
+                piece.block = now;
+                piece.plain = plain;
+                piece.drawn = drawn;
+                piece.stamped = ready;
+                // A new drawn page changes only the plain terrain's corners: an `all` pass under way goes on, as its
+                // labelled corners read the stored pages, the stamps and the block. Any other pass starts again.
+                if (all || piece.stale !== 'all') piece.done = 0;
+                piece.stale = more(piece.stale, all ? 'all' : 'terrain');
+                piece.grounded = false;
+            }
+        }
+        const before = this.drawn.map(piece => key(piece.node)).join();
+        const range = cellsAbout(eye, WINDOW >> 1).filter(cell => inRange(rule, eye, cell));
+        ({ level: this.meshLevel, calm: this.calm } = meshLevel(range.some(rests) ? 0 : rule.finest, this.calm));
+        const cells = this.meshLevel ? range : [];
+        const near = (piece: Piece) => distances(eye, piece.node)[0];
+        // The plateau of level 18 ends here; a triangle's reach and a little more stay whole past it.
+        const plateau = rule.range / 2 ** (18 + MORPH) - FADE_MARGIN_M;
+        this.cut.clear();
+        this.drawn = cells.flatMap(cell => {
+            const piece = this.pieces.get(key(cell));
+            if (piece?.computed && distances(eye, cell)[1] >= plateau) this.cut.add(piece);
+            return piece?.computed ? [piece] : [];
+        }).sort((a, b) => near(a) - near(b));
+        this.inView = this.drawn.filter(piece => visible(piece.node));
+        const waiting = cells.some(cell => !this.pieces.get(key(cell))?.computed && !settled(cell));
+        const now = performance.now();
+        if (waiting) this.readyFrom ??= now;
+        else if (this.readyFrom !== undefined) {
+            this.readyMs = now - this.readyFrom;
+            this.readyFrom = undefined;
+        }
+        const changed = before !== this.drawn.map(piece => key(piece.node)).join();
+        this.cellsDirty ||= changed;
+        return changed || (!this.resting && [...this.pieces.values()].some(piece => piece.stale));
+    }
+
+    /** Uploads new pieces and the window of the cells that draw. */
+    write(eye: Eye): void {
+        const r = this.resources;
+        if (!r) return;
+        const { device } = r.gpu;
+        for (const piece of this.pieces.values()) if (!piece.gpu) this.upload(r, piece);
+        const s = size(CELL_LEVEL), window: [number, number] = [Math.floor((eye.anchor.whole[0] + eye.anchor.part[0]) / s) - (WINDOW >> 1), Math.floor((eye.anchor.whole[1] + eye.anchor.part[1]) / s) - (WINDOW >> 1)];
+        if (!this.cellsDirty && window[0] === this.window?.[0] && window[1] === this.window?.[1]) return;
+        this.cellsDirty = false;
+        this.window = window;
+        const names = new Set(this.drawn.map(piece => key(piece.node)));
+        for (const name of this.slots.keys()) if (!names.has(name)) this.slots.delete(name);
+        const used = new Set(this.slots.values()), head = new Int32Array(HEAD);
+        head.set(window);
+        for (const piece of this.drawn) {
+            const name = key(piece.node), i = piece.node.x - window[0], j = piece.node.y - window[1];
+            if (i < 0 || j < 0 || i >= WINDOW || j >= WINDOW) continue;
+            let slot = this.slots.get(name);
+            if (slot === undefined) {
+                slot = [...Array(SLOTS).keys()].find(k => !used.has(k));
+                if (slot === undefined) continue;
+                used.add(slot);
+                this.slots.set(name, slot);
+                device.queue.writeBuffer(r.cells, 4 * (HEAD + slot * SUNK_WORDS), piece.mesh.sunk);
+            }
+            head[2 + j * WINDOW + i] = slot + 1;
+        }
+        // A cell without a slot does not draw: its terrain would neither sink nor lose its snap.
+        this.drawn = this.drawn.filter(piece => this.slots.has(key(piece.node)));
+        this.inView = this.inView.filter(piece => this.slots.has(key(piece.node)));
+        device.queue.writeBuffer(r.cells, 0, head);
+    }
+
+    private upload(r: Resources, piece: Piece): void {
+        const { device } = r.gpu, { corners, triangles, steps, culverts } = piece.mesh, n = corners.length / 2;
+        // COPY_SRC for the determinism check's reads (`buffers`).
+        const data = r.gpu.buffer('plan', 4 * Math.max(4, 6 * n + steps.length + culverts.length), GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC);
+        // A buffer write takes whole words.
+        const indices = r.gpu.buffer('plan', 4 * Math.max(2, Math.ceil(triangles.length / 2)), GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST);
+        const params = r.gpu.buffer('plan', PARAMS_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
+        device.queue.writeBuffer(data, 0, corners);
+        device.queue.writeBuffer(data, 4 * 6 * n, steps);
+        device.queue.writeBuffer(data, 4 * (6 * n + steps.length), culverts);
+        device.queue.writeBuffer(indices, 0, triangles.buffer, triangles.byteOffset, 4 * Math.ceil(triangles.length / 2));
+        piece.gpu = { data, indices, params, draw: this.drawGroup(r, data, params, r.frame), storeys: piece.mesh.storeys && this.uploadStoreys(r, piece.mesh.storeys) };
+        piece.computed = false;
+        piece.stale = 'all';
+        piece.done = 0;
+    }
+
+    /** A cell's storeys: their corners, out words, slots, triangles and offsets in one buffer, as their parameters name them. */
+    private uploadStoreys(r: Resources, storeys: StoreyMesh): StoreysGpu {
+        const { device } = r.gpu, { corners, slots, triangles, offsets } = storeys, n = offsets.length;
+        const data = r.gpu.buffer('plan', 4 * Math.max(4, 7 * n + slots.length + triangles.length), GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);
+        const params = r.gpu.buffer('plan', PARAMS_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
+        device.queue.writeBuffer(data, 0, corners);
+        device.queue.writeBuffer(data, 4 * 6 * n, slots);
+        device.queue.writeBuffer(data, 4 * (6 * n + slots.length), triangles);
+        device.queue.writeBuffer(data, 4 * (6 * n + slots.length + triangles.length), offsets);
+        return { data, params, draw: this.drawGroup(r, data, params, r.frame), computed: false };
+    }
+
+    private drawGroup(r: Resources, data: GPUBuffer, params: GPUBuffer, frame: GPUBuffer): GPUBindGroup {
+        return r.gpu.device.createBindGroup({ layout: r.drawLayout, entries: [
+            { binding: 0, resource: { buffer: frame } }, { binding: 1, resource: { buffer: data } }, { binding: 2, resource: { buffer: params } }, { binding: 3, resource: { buffer: r.cells } },
+            { binding: 8, resource: r.records.createView() },
+        ] });
+    }
+
+    /**
+     * Makes the heights of the stale pieces, after the frame's pages and records. A piece in view makes its plain
+     * terrain's corners whole in the frame: they read the drawn page, and on the old one they would tear from the
+     * terrain beside them. The rest of an `all` pass waits for CORNERS_PER_FRAME, in view first, near the eye first.
+     */
+    encode(encoder: GPUCommandEncoder, surface: GPUBindGroup, eye: Eye, time: () => GPUComputePassTimestampWrites | undefined = () => undefined): void {
+        const r = this.resources;
+        if (!r || this.resting) return;
+        // A pass's stamp data is spent once its commands went out.
+        for (const piece of this.pieces.values()) {
+            if (piece.stale || !piece.gpu?.stamps) continue;
+            r.gpu.destroy('plan', piece.gpu.stamps);
+            piece.gpu.stamps = piece.gpu.compute = piece.gpu.bound = undefined;
+            if (piece.gpu.storeys) piece.gpu.storeys.compute = undefined;
+        }
+        const shown = new Set(this.inView), near = (piece: Piece) => distances(eye, piece.node)[0];
+        const stale = [...this.pieces.values()].filter(piece => piece.stale && piece.gpu && piece.block >= 0).sort((a, b) => +shown.has(b) - +shown.has(a) || near(a) - near(b));
+        if (!stale.length) return;
+        const pass = encoder.beginComputePass({ label: 'plan corners', timestampWrites: time() });
+        pass.setPipeline(r.corners);
+        pass.setBindGroup(1, surface);
+        let budget = CORNERS_PER_FRAME;
+        for (const piece of stale) {
+            const n = piece.mesh.corners.length / 2;
+            if (shown.has(piece) && (piece.stale === 'terrain' || !piece.grounded)) {
+                this.dispatch(r, pass, piece, 'terrain', 0, n);
+                budget -= Math.ceil(n / TERRAIN_SHARE);
+                if (piece.stale === 'terrain') this.made(piece);
+                else piece.grounded = true;
+                continue;
+            }
+            // A labelled corner reads the stamp data: an `all` pass waits for it.
+            if (budget <= 0 || (piece.stale === 'all' && !piece.stamped)) continue;
+            const share = piece.stale === 'terrain' ? TERRAIN_SHARE : 1, count = Math.min(n - piece.done, budget * share);
+            budget -= Math.ceil(count / share);
+            this.dispatch(r, pass, piece, piece.stale!, piece.done, count);
+            piece.grounded ||= piece.done === 0;
+            piece.done += Math.ceil(count / GROUP_CORNERS) * GROUP_CORNERS;
+            if (piece.done < n) continue;
+            // An `all` pass that a new drawn page met on its way makes the plain terrain's corners again.
+            if (piece.grounded) this.made(piece);
+            else {
+                piece.stale = 'terrain';
+                piece.done = 0;
+            }
+        }
+        pass.end();
+    }
+
+    /** One dispatch of a piece's corners from `first`: a piece takes one a frame, since its parameters are one buffer. */
+    private dispatch(r: Resources, pass: GPUComputePassEncoder, piece: Piece, make: Make, first: number, count: number): void {
+        const gpu = piece.gpu!, n = piece.mesh.corners.length / 2, s = size(CELL_LEVEL);
+        const params = new ArrayBuffer(PARAMS_BYTES), ints = new Int32Array(params), words = new Uint32Array(params);
+        ints.set([piece.node.x * s, piece.node.y * s]);
+        words.set([n, 6 * n, 2 * n, piece.mesh.steps.length / 4 - piece.mesh.endFaces, piece.block, (first | (make === 'terrain' ? TERRAIN_BIT : 0)) >>> 0, 6 * n + piece.mesh.steps.length], 2);
+        r.gpu.device.queue.writeBuffer(gpu.params, 0, params);
+        if (first === 0 || gpu.bound !== make) this.bindStamps(r, piece, make === 'terrain');
+        gpu.bound = make;
+        pass.setBindGroup(0, gpu.compute!);
+        pass.dispatchWorkgroups(Math.ceil(count / GROUP_CORNERS));
+        // The storeys' corners carry labels only, and are few: all of them with the first dispatch of an `all` pass.
+        const storeys = gpu.storeys, mesh = piece.mesh.storeys;
+        if (make !== 'all' || first !== 0 || !storeys?.compute || !mesh) return;
+        const m = mesh.offsets.length, slots = mesh.slots.length, tris = 6 * m + slots;
+        // The storeys' slots are all plain concrete: their end faces start at 0.
+        words.set([m, 6 * m, 2 * m, 0, piece.block, 0, 0, tris + mesh.triangles.length, tris, mesh.top, mesh.railings, mesh.piers], 2);
+        r.gpu.device.queue.writeBuffer(storeys.params, 0, params);
+        pass.setBindGroup(0, storeys.compute);
+        pass.dispatchWorkgroups(Math.ceil(m / GROUP_CORNERS));
+        storeys.computed = true;
+    }
+
+    private made(piece: Piece): void {
+        piece.computed = true;
+        piece.stale = undefined;
+        piece.done = 0;
+        piece.grounded = false;
+    }
+
+    /** The stamp data of a cell's stampNodes, as corners.wgsl reads it: none for the plain terrain's corners, which read the drawn page. */
+    private bindStamps(r: Resources, piece: Piece, terrain: boolean): void {
+        const gpu = piece.gpu!, nodes = terrain ? [] : stampNodes(piece.node).map(this.stamps);
+        const table = new Uint32Array(NODES * NODES);
+        let words = table.length;
+        nodes.forEach((data, i) => {
+            if (!data) return;
+            table[i] = words + 1;
+            words += data.length;
+        });
+        const packed = new Uint32Array(words);
+        packed.set(table);
+        nodes.forEach((data, i) => data && packed.set(data, table[i] - 1));
+        if (gpu.stamps) r.gpu.destroy('plan', gpu.stamps);
+        gpu.stamps = r.gpu.buffer('plan', packed.byteLength, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);
+        r.gpu.device.queue.writeBuffer(gpu.stamps, 0, packed);
+        const compute = (data: GPUBuffer, params: GPUBuffer) => r.gpu.device.createBindGroup({ layout: r.computeLayout, entries: [
+            { binding: 0, resource: { buffer: data } }, { binding: 1, resource: { buffer: gpu.stamps! } }, { binding: 2, resource: { buffer: params } },
+            { binding: 4, resource: { buffer: r.profiles } }, { binding: 8, resource: r.records.createView() },
+        ] });
+        gpu.compute = compute(gpu.data, gpu.params);
+        if (gpu.storeys) gpu.storeys.compute = terrain ? undefined : compute(gpu.storeys.data, gpu.storeys.params);
+    }
+
+    /** For the determinism check, per computed piece: its mesh from the worker, and the GPU buffer range of the corners that the pass made. */
+    buffers(): { name: string; mesh: CellMesh; buffer: GPUBuffer; offset: number; bytes: number }[] {
+        return [...this.pieces].flatMap(([name, { mesh, gpu, computed }]) => (gpu && computed ? [{ name, mesh, buffer: gpu.data, offset: 4 * mesh.corners.length, bytes: 8 * mesh.corners.length }] : []));
+    }
+
+    /** Before the terrain, nearest first: early depth then rejects the terrain under the meshes. */
+    draw(pass: GPURenderPassEncoder, surface: GPUBindGroup, ground: GPUBindGroup, features: GPUBindGroup): void {
+        const r = this.resources;
+        if (!r || !this.inView.length) return;
+        pass.setBindGroup(1, surface);
+        pass.setBindGroup(2, ground);
+        pass.setBindGroup(3, features);
+        for (const cut of [false, true]) {
+            const pieces = this.inView.filter(piece => this.cut.has(piece) === cut);
+            if (!pieces.length) continue;
+            for (const mouth of [false, true]) {
+                pass.setPipeline(mouth ? (cut ? r.cutMouthTriangles : r.mouthTriangles) : cut ? r.cutTriangles : r.triangles);
+                for (const piece of pieces) {
+                    if (mouth && !piece.mouths.some(m => m > 0)) continue;
+                    pass.setBindGroup(0, piece.gpu!.draw);
+                    pass.setIndexBuffer(piece.gpu!.indices, 'uint16');
+                    // vertex_index includes the run's base. Over level-17 nodes the last runs do not draw.
+                    let first = 0;
+                    piece.mesh.runs.slice(0, this.drawnRuns(piece)).forEach(({ count, base }, k) => {
+                        const own = count - piece.mouths[k], n = mouth ? piece.mouths[k] : own;
+                        if (n) pass.drawIndexed(3 * n, 1, first + (mouth ? 3 * own : 0), base);
+                        first += 3 * count;
+                    });
+                }
+            }
+            pass.setPipeline(cut ? r.cutSlots : r.slots);
+            for (const piece of pieces) {
+                if (!piece.mesh.steps.length) continue;
+                pass.setBindGroup(0, piece.gpu!.draw);
+                pass.draw(6 * (piece.mesh.steps.length / 4));
+            }
+            pass.setPipeline(cut ? r.cutCulverts : r.culverts);
+            for (const piece of pieces) {
+                if (!piece.mesh.culverts.length) continue;
+                pass.setBindGroup(0, piece.gpu!.draw);
+                pass.draw(CULVERT_VERTICES * (piece.mesh.culverts.length / 4));
+            }
+            const storeyed = pieces.filter(piece => piece.gpu!.storeys?.computed);
+            pass.setPipeline(r.storeys[+cut]);
+            for (const piece of storeyed) {
+                pass.setBindGroup(0, piece.gpu!.storeys!.draw);
+                pass.draw(piece.mesh.storeys!.triangles.length);
+            }
+            pass.setPipeline(cut ? r.cutSlots : r.slots);
+            for (const piece of storeyed) {
+                if (!piece.mesh.storeys!.slots.length) continue;
+                pass.setBindGroup(0, piece.gpu!.storeys!.draw);
+                pass.draw(6 * (piece.mesh.storeys!.slots.length / 4));
+            }
+        }
+    }
+
+    /** Draws the storeys of the cells that draw into the shadow map as casters, with the sun's frame (`castWith`). */
+    cast(pass: GPURenderPassEncoder, surface: GPUBindGroup, empty: GPUBindGroup, features: GPUBindGroup): void {
+        const r = this.resources;
+        if (!r || !this.sun) return;
+        const storeyed = this.drawn.filter(piece => piece.gpu?.storeys?.computed);
+        if (!storeyed.length) return;
+        pass.setPipeline(r.storeyCaster);
+        pass.setBindGroup(1, surface);
+        pass.setBindGroup(2, empty);
+        pass.setBindGroup(3, features);
+        for (const piece of storeyed) {
+            const storeys = piece.gpu!.storeys!;
+            storeys.cast ??= this.drawGroup(r, storeys.data, storeys.params, this.sun);
+            pass.setBindGroup(0, storeys.cast);
+            pass.draw(piece.mesh.storeys!.triangles.length);
+        }
+    }
+
+    /** The runs of a piece that draw at this frame's level. */
+    private drawnRuns(piece: Piece): number {
+        return piece.mesh.runs.length - (this.meshLevel < 18 ? piece.mesh.level18Runs : 0);
+    }
+
+    /** The level of the terrain nodes that the meshes draw over, 0 for none. */
+    get level(): number {
+        return this.meshLevel;
+    }
+
+    /** Whether the meshes count calm frames to draw again: frames must go on until they draw, also in a still view. */
+    get returning(): boolean {
+        return this.meshLevel === 0 && this.calm > 0;
+    }
+
+    /** Whether a cell's mesh holds its corners' heights; undefined while the cell has no mesh. */
+    ready(cell: Node): boolean | undefined {
+        return this.pieces.get(key(cell))?.computed;
+    }
+
+    /** True while a cell that the terrain draws in part at level 18 has no mesh that draws. */
+    get loading(): boolean {
+        return this.readyFrom !== undefined;
+    }
+
+    get stats(): PiecesStats {
+        const storeyBytes = ({ storeys: s }: CellMesh) => (s ? 4 * (7 * s.offsets.length + s.slots.length + s.triangles.length) : 0);
+        const bytes = [...this.pieces.values()].reduce((sum, { mesh }) => sum + 4 * (3 * mesh.corners.length + mesh.steps.length + mesh.culverts.length) + 2 * mesh.triangles.length + storeyBytes(mesh), 0);
+        return {
+            cells: this.pieces.size, drawn: this.drawn.length, inView: this.inView.length,
+            triangles: this.inView.reduce((sum, piece) => sum + piece.mesh.runs.slice(0, this.drawnRuns(piece)).reduce((n, run) => n + run.count, 0), 0), steps: this.inView.reduce((sum, { mesh }) => sum + mesh.steps.length / 4, 0),
+            storeyTriangles: this.inView.reduce((sum, { mesh: { storeys: s } }) => sum + (s ? s.triangles.length / 3 + 2 * (s.slots.length / 4) : 0), 0),
+            bytes, ready: this.readyMs,
+        };
+    }
+}
+
+export async function piecePipelines(gpu: Gpu) {
+    const { device } = gpu, { surface, ground, features } = gpu.once(layouts);
+    const V = GPUShaderStage.VERTEX, F = GPUShaderStage.FRAGMENT, C = GPUShaderStage.COMPUTE;
+    // A stop arm's mouth reads the records in the fragment stage (plan/mouth-in.wgsl).
+    const drawLayout = device.createBindGroupLayout({ entries: [
+        { binding: 0, visibility: V | F, buffer: { type: 'uniform' } }, { binding: 1, visibility: V, buffer: { type: 'read-only-storage' } },
+        { binding: 2, visibility: V | F, buffer: { type: 'uniform' } }, { binding: 3, visibility: V, buffer: { type: 'read-only-storage' } },
+        { binding: 8, visibility: F, texture: { sampleType: 'uint' } },
+    ] });
+    const computeLayout = device.createBindGroupLayout({ entries: [
+        { binding: 0, visibility: C, buffer: { type: 'storage' } }, { binding: 1, visibility: C, buffer: { type: 'read-only-storage' } }, { binding: 2, visibility: C, buffer: { type: 'uniform' } },
+        { binding: 4, visibility: C, buffer: { type: 'uniform' } }, { binding: 8, visibility: C, texture: { sampleType: 'uint' } },
+    ] });
+    const modules = [false, true].map(mouth => device.createShaderModule({ label: `plan pieces${mouth ? ' mouth' : ''}`, code: wgsl('plan/piece.wgsl', mouth ? MOUTH : {}) }));
+    const render = (entryPoint: string, cullMode: GPUCullMode, cut: boolean, mouth = false) => device.createRenderPipelineAsync({
+        label: `plan ${entryPoint}${mouth ? ' mouth' : ''}${cut ? ' cut' : ''}`, layout: device.createPipelineLayout({ bindGroupLayouts: [drawLayout, surface, ground, features] }),
+        vertex: { module: modules[+mouth], entryPoint, constants: { MOUTH: +mouth } },
+        // The ground without the road paint, as the corridors' band.
+        fragment: { module: modules[+mouth], entryPoint: 'corridor_fragment', targets: [{ format: sceneFormat(gpu) }], constants: { BAND: 1, PIECE: 1, MODEL: 1, CUT: cut ? 1 : 0, MOUTH: +mouth } },
+        primitive: { topology: 'triangle-list', cullMode },
+        depthStencil: { format: DEPTH, depthWriteEnabled: true, depthCompare: 'greater' },
+    });
+    // The casters' vertices read no group 2, which holds the shadow map that they draw.
+    const empty = device.createBindGroupLayout({ entries: [] });
+    const caster = device.createRenderPipelineAsync({
+        label: 'plan storey caster', layout: device.createPipelineLayout({ bindGroupLayouts: [drawLayout, surface, empty, features] }),
+        vertex: { module: modules[0], entryPoint: 'storey_caster' }, primitive: CASTER_PRIMITIVE, depthStencil: CASTER_DEPTH,
+    });
+    // A step faces its lower side from either side of its edge.
+    const [triangles, slots, cutTriangles, cutSlots, mouthTriangles, cutMouthTriangles, culverts, cutCulverts, storeys, cutStoreys, storeyCaster, corners] = await Promise.all([
+        render('piece_vertex', 'back', false), render('slot_vertex', 'none', false), render('piece_vertex', 'back', true), render('slot_vertex', 'none', true),
+        render('piece_vertex', 'back', false, true), render('piece_vertex', 'back', true, true),
+        render('culvert_vertex', 'none', false), render('culvert_vertex', 'none', true),
+        render('storey_vertex', 'back', false), render('storey_vertex', 'back', true), caster,
+        device.createComputePipelineAsync({
+            label: 'plan corners', layout: device.createPipelineLayout({ bindGroupLayouts: [computeLayout, surface] }),
+            compute: { module: device.createShaderModule({ label: 'plan corners', code: wgsl('plan/corners.wgsl') }), entryPoint: 'corners' },
+        }),
+    ]);
+    return { triangles, slots, cutTriangles, cutSlots, mouthTriangles, cutMouthTriangles, culverts, cutCulverts, storeys: [storeys, cutStoreys], storeyCaster, corners, drawLayout, computeLayout };
+}
+
+/**
+ * Moves the triangles of a run whose first corner's label is in `mouths` to the run's end, in place, and returns their
+ * count per run. A triangle takes its look from its first corner (corridor.wgsl), so it keeps that corner first.
+ */
+export function splitMouths(mesh: CellMesh, mouths: Set): number[] {
+    let first = 0;
+    return mesh.runs.map(({ count, base }) => {
+        const tris = mesh.triangles.subarray(first, first + 3 * count), own: number[] = [], mouth: number[] = [];
+        for (let t = 0; t < count; t++) {
+            const k = tris[3 * t] + base, w0 = mesh.corners[2 * k], w1 = mesh.corners[2 * k + 1];
+            const label = (w0 >>> 19) | (((w1 >>> 19) & 0xfff) << 13);
+            (mouths.has(label) ? mouth : own).push(tris[3 * t], tris[3 * t + 1], tris[3 * t + 2]);
+        }
+        tris.set([...own, ...mouth]);
+        first += 3 * count;
+        return mouth.length / 3;
+    });
+}
diff --git a/builder/web/src/lib/trailview/plan/plan-worker.ts b/builder/web/src/lib/trailview/plan/plan-worker.ts
new file mode 100644
index 0000000000..d1948ad849
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/plan-worker.ts
@@ -0,0 +1,264 @@
+// The plan worker: builds cells of the ground plan in its own instance of the bridge. A worker blocked
+// in a build cannot read its inbox, so a cancel or a trap ends it (plan.ts and model.ts start another).
+import { imagePixels } from '../../planner/layers/terrain';
+import { tilePages, type PageData } from '../stream/heights';
+import { debugMesh, type DebugMesh, type Vocabulary } from './debug';
+import { meshBytes } from './mesh';
+import init, { build, build_bytes, CellRequest, far, vocabulary, type CellPlan, type InitOutput, type MeshInput } from './pkg/obc_ground_plan_bridge.js';
+
+/** Decoded stored tiles kept: 16 tiles of four 128 KiB pages, 8 MiB. */
+const TILES = 16;
+/** Mesh inputs kept for their cells' meshes: a town cell's faces take up to about 1 MiB of the heap. */
+const INPUTS = 32;
+
+/** A tile without `body` is one whose body went to the worker before: the bridge holds it parsed, or the answer is `Missing`. */
+type Inputs = { cell: { x: number; y: number }; tiles: { column: number; row: number; body?: ArrayBuffer }[]; terrain: { z: number; x: number; y: number; body: ArrayBuffer }[]; pages: Uint32Array };
+
+export type PlanRequest =
+    | { type: 'start'; module: WebAssembly.Module }
+    | ({ type: 'build'; id: number; debug: boolean } & Inputs)
+    /** A cell's records, rim and far block; with `mesh` the worker keeps its mesh input until a `mesh` or a `drop`. */
+    | ({ type: 'cell'; id: number; mesh: boolean } & Inputs)
+    /** A cell's far block alone. */
+    | ({ type: 'far'; id: number } & Inputs)
+    /** The mesh of a kept cell from the rims of the cell and its eight neighbours, one after another (`rim` of a `CellBuilt`). */
+    | { type: 'mesh'; id: number; cell: { x: number; y: number }; rims: Uint32Array }
+    | { type: 'drop'; cell: { x: number; y: number } }
+    | { type: 'time'; id: number; request: ArrayBuffer; runs: number };
+
+/** A built cell; `digest` and `debug` only for a build with the debug draw. */
+export interface Built { id: number; ok: true; stats: string; times: number[]; prepare: number; digest?: string; heap: number; debug?: DebugMesh }
+/** A failed build; `trapped` when the instance is not safe to use again (a panic, out of memory). */
+export interface Failed { id: number; ok: false; error: string; trapped: boolean }
+/** The worker no longer holds feature tiles that a job named without a body, as column, row pairs: the job goes again with their bodies. */
+export interface Missing { id: number; ok: true; missing: Uint32Array }
+/**
+ * A cell's near records (the words that the GPU reads, whose labels its mesh's corners name), its rim, its far block
+ * (`records/far.rs` of obc-ground-plan) or why the crate refused it, and the build's milliseconds.
+ */
+export interface CellBuilt { id: number; ok: true; words: Uint32Array; rim: Uint32Array; far: Uint32Array | { error: string }; ms: number; heap: number }
+/** A cell's far block from a `far` job: the `far` of its `cell` job. */
+export interface FarBuilt { id: number; ok: true; far: Uint32Array; ms: number; heap: number }
+/**
+ * A cell's near mesh (`mesh/mod.rs` of obc-ground-plan gives the bytes), then the meshes of its storeys over the
+ * ground (`mesh/shell.rs`) where it has any, or `gone` when the worker no longer keeps its input; `ms` is the mesh stage.
+ */
+export type Meshed = { id: number; ok: true; mesh: ArrayBuffer; ms: number } | { id: number; ok: true; gone: true };
+/**
+ * The times of a request: the first run, then `runs` runs, each with its stage times and the total;
+ * `mean`, the time of all `runs` over their count, holds where the clock is coarse (Safari: 1 ms).
+ */
+export interface Timed { id: number; ok: true; first: number[]; runs: number[][]; mean: number; digest: string; heap: number; stats: string }
+
+let output: InitOutput | undefined;
+let words: Vocabulary | undefined;
+const decoded = new Map>();
+const kept = new Map();
+
+const post = (message: unknown, transfer: Transferable[] = []) => self.postMessage(message, { transfer });
+const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
+/** A trap leaves the instance broken; an error that the bridge returns does not. */
+const trapped = (error: unknown) => error instanceof WebAssembly.RuntimeError || error instanceof RangeError;
+
+/** The plain bytes of a feature tile body: a tile service may hand over the gzip of the archive. */
+async function plain(body: ArrayBuffer): Promise {
+    const bytes = new Uint8Array(body);
+    if (bytes[0] !== 0x1f || bytes[1] !== 0x8b) return bytes;
+    return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'))).arrayBuffer());
+}
+
+/** The pages of a stored tile, decoded as the decode worker does, so the codes are the GPU's. */
+function pagesOf(name: string, body: ArrayBuffer): Promise<(PageData | null)[]> {
+    let pages = decoded.get(name);
+    if (pages) decoded.delete(name);
+    else pages = imagePixels(new Uint8Array(body)).then(rgba => tilePages(rgba.data, rgba.width));
+    pages.catch(() => decoded.delete(name));
+    decoded.set(name, pages);
+    for (const old of decoded.keys()) if (decoded.size > TILES) decoded.delete(old);
+    return pages;
+}
+
+function stageTimes(plan: CellPlan): number[] {
+    const times = [...plan.times()];
+    return [...times, times.reduce((sum, t) => sum + t, 0)];
+}
+
+/**
+ * The request of a cell's inputs, with the milliseconds of its gunzip and WebP decode. A tile without a body goes by
+ * name; the caller checks `missing()` before the build, with no await between them.
+ */
+async function requestOf({ cell, tiles, terrain, pages }: Inputs): Promise<{ request: CellRequest; prepare: number }> {
+    const start = performance.now();
+    const plains = await Promise.all(tiles.map(({ body }) => body && plain(body)));
+    const quadrants = new Map(await Promise.all(terrain.map(async ({ z, x, y, body }) => [`${z}/${x}/${y}`, await pagesOf(`${z}/${x}/${y}`, body)] as const)));
+    const request = new CellRequest(cell.x, cell.y);
+    try {
+        tiles.forEach(({ column, row }, i) => {
+            const bytes = plains[i];
+            if (bytes) request.add_tile(column, row, bytes);
+            else request.name_tile(column, row);
+        });
+        for (let i = 0; i < pages.length; i += words!.words.wanted) {
+            const page = quadrants.get(`${pages[i + 3]}/${pages[i + 4]}/${pages[i + 5]}`)?.[pages[i + 6]];
+            // StoredPage holds f32 offsets and scales.
+            if (page) request.add_page(pages[i], pages[i + 1], pages[i + 2], Math.fround(page.offset), Math.fround(page.scale), page.texels);
+        }
+    } catch (error) {
+        request.free();
+        throw error;
+    }
+    return { request, prepare: performance.now() - start };
+}
+
+const failed = (id: number, error: unknown) => post({ id, ok: false, error: message(error), trapped: trapped(error) } satisfies Failed);
+const nameOf = ({ x, y }: { x: number; y: number }) => `${x}-${y}`;
+
+/** The request of a job once the bridge holds its named tiles; undefined after the answer `Missing`. */
+async function held(job: Inputs & { id: number }): Promise {
+    const { request } = await requestOf(job);
+    const missing = request.missing();
+    if (!missing.length) return request;
+    request.free();
+    post({ id: job.id, ok: true, missing } satisfies Missing, [missing.buffer]);
+}
+
+/** A plan's far block, or why the crate refused it; a trap still ends the job. */
+function farOf(plan: CellPlan): CellBuilt['far'] {
+    try {
+        return plan.far();
+    } catch (error) {
+        if (trapped(error)) throw error;
+        return { error: message(error) };
+    }
+}
+
+async function buildCell(job: Extract): Promise {
+    const { id, cell, debug } = job;
+    let plan: CellPlan | undefined;
+    try {
+        const made = await requestOf(job);
+        plan = build(made.request, debug);
+        const mesh = debug
+            ? debugMesh({ samples: plan.samples(), ways: plan.ways(), points: plan.points(), crossings: plan.crossings(), vertices: plan.vertices(), faces: plan.faces(), rings: plan.rings(), ring_vertices: plan.ring_vertices(), edges: plan.edges() }, words!, cell)
+            : undefined;
+        const built: Built = { id, ok: true, stats: plan.stats(), times: [...plan.times()], prepare: made.prepare, heap: output!.memory.buffer.byteLength, ...(debug ? { digest: plan.digest(), debug: mesh } : {}) };
+        post(built, mesh ? [mesh.lines.buffer, mesh.fills.buffer] : []);
+    } catch (error) {
+        failed(id, error);
+    } finally {
+        plan?.free();
+    }
+}
+
+/** Builds a cell for the records and the mesh: the faces' records and rim, and with `mesh` its mesh input kept. */
+async function buildRecords(job: Extract): Promise {
+    let plan: CellPlan | undefined;
+    try {
+        const request = await held(job);
+        if (!request) return;
+        const start = performance.now();
+        // The build takes the request: nothing frees it after.
+        plan = build(request, false);
+        const name = nameOf(job.cell);
+        kept.get(name)?.free();
+        kept.delete(name);
+        const block = farOf(plan), input = plan.mesh_input();
+        const words = input.records(), rim = plan.rim();
+        if (job.mesh) {
+            kept.set(name, input);
+            for (const [old, value] of kept) if (kept.size > INPUTS) {
+                value.free();
+                kept.delete(old);
+            }
+        } else input.free();
+        const transfer = [words.buffer, rim.buffer, ...(block instanceof Uint32Array ? [block.buffer] : [])];
+        post({ id: job.id, ok: true, words, rim, far: block, ms: performance.now() - start, heap: output!.memory.buffer.byteLength } satisfies CellBuilt, transfer);
+    } catch (error) {
+        failed(job.id, error);
+    } finally {
+        plan?.free();
+    }
+}
+
+/** Builds a cell's far block alone: no faces, no records, no rim. */
+async function buildFar(job: Extract): Promise {
+    try {
+        const request = await held(job);
+        if (!request) return;
+        const start = performance.now();
+        // `far` takes the request: nothing frees it after.
+        const words = far(request);
+        post({ id: job.id, ok: true, far: words, ms: performance.now() - start, heap: output!.memory.buffer.byteLength } satisfies FarBuilt, [words.buffer]);
+    } catch (error) {
+        failed(job.id, error);
+    }
+}
+
+function meshCell({ id, cell, rims }: Extract): void {
+    const name = nameOf(cell), input = kept.get(name);
+    if (!input) return post({ id, ok: true, gone: true } satisfies Meshed);
+    const start = performance.now();
+    try {
+        // A first mesh of an input always gives its bytes.
+        const mesh = withStoreys(input.mesh(rims)!, input);
+        post({ id, ok: true, mesh, ms: performance.now() - start } satisfies Meshed, [mesh]);
+    } catch (error) {
+        failed(id, error);
+    } finally {
+        input.free();
+        kept.delete(name);
+    }
+}
+
+/** A cell's mesh bytes with its storeys' (`meshBytes`). A storey mesh that the crate refuses draws none. */
+function withStoreys(mesh: Uint8Array, input: MeshInput): ArrayBuffer {
+    try {
+        return meshBytes(mesh, input.storeys());
+    } catch (error) {
+        if (trapped(error)) throw error;
+        console.warn(`Ground plan storeys: ${message(error)}`);
+        return meshBytes(mesh);
+    }
+}
+
+function time({ id, request, runs }: Extract): void {
+    const bytes = new Uint8Array(request), all: number[][] = [];
+    let digest = '', stats = '', start = 0;
+    try {
+        for (let run = 0; run <= runs; run++) {
+            if (run === 1) start = performance.now();
+            const plan = build_bytes(bytes);
+            all.push(stageTimes(plan));
+            plan.free();
+        }
+        const mean = (performance.now() - start) / runs;
+        const plan = build_bytes(bytes);
+        try {
+            [digest, stats] = [plan.digest(), plan.stats()];
+        } finally {
+            plan.free();
+        }
+        post({ id, ok: true, first: all[0], runs: all.slice(1), mean, digest, heap: output!.memory.buffer.byteLength, stats } satisfies Timed);
+    } catch (error) {
+        failed(id, error);
+    }
+}
+
+self.onmessage = async ({ data }: MessageEvent) => {
+    if (data.type === 'start') {
+        try {
+            output = await init({ module_or_path: data.module });
+            words = JSON.parse(vocabulary());
+            post({ type: 'ready' });
+        } catch (error) {
+            post({ type: 'ready', error: message(error) });
+        }
+    } else if (data.type === 'build') await buildCell(data);
+    else if (data.type === 'cell') await buildRecords(data);
+    else if (data.type === 'far') await buildFar(data);
+    else if (data.type === 'mesh') meshCell(data);
+    else if (data.type === 'drop') {
+        kept.get(nameOf(data.cell))?.free();
+        kept.delete(nameOf(data.cell));
+    } else time(data);
+};
diff --git a/builder/web/src/lib/trailview/plan/plan.test.ts b/builder/web/src/lib/trailview/plan/plan.test.ts
new file mode 100644
index 0000000000..801e0ac1c6
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/plan.test.ts
@@ -0,0 +1,181 @@
+import { readFileSync } from 'node:fs';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { worldPixel } from '../../planner/layers/mercator';
+import { anchorAt, UNITS } from '../frame/space';
+import { distances, size } from '../terrain/lod';
+import { DEBUG_WORDS, debugMesh, EDGE_STEP_M, type Vocabulary } from './debug';
+import { metresPerUnit } from '../terrain/bins';
+import { AHEAD_M, BUILD_M, CELL_LEVEL, Plan, wantedCells, type PlanEye } from './plan';
+import type { Built, Failed, PlanRequest } from './plan-worker';
+import { build, CellRequest, initSync, vocabulary, wanted } from './pkg/obc_ground_plan_bridge.js';
+
+const [west, north] = worldPixel([8.37, 46.83], UNITS), [east, south] = worldPixel([8.46, 46.765], UNITS);
+const BOUNDS: [number, number, number, number] = [west, north, east, south];
+const eyeAt = (lon: number, lat: number, above: number): PlanEye => {
+    const [x, y] = worldPixel([lon, lat], UNITS);
+    return { x, y, unit: anchorAt(lon, lat).unit, above };
+};
+const metres = (eye: PlanEye, node: { level: number; x: number; y: number }) =>
+    distances({ anchor: { whole: [eye.x, eye.y], part: [0, 0], unit: eye.unit }, above: eye.above }, node)[0];
+
+describe('the wanted cells', () => {
+    const eye = eyeAt(8.405, 46.818, 1.6), east: [number, number] = [1, 0];
+
+    it('come near first by distance, then those ahead, none past the range and none outside the bounds', () => {
+        const cells = wantedCells(eye, east, BOUNDS), d = cells.map(cell => metres(eye, cell));
+        const near = d.filter(m => m < BUILD_M).length;
+        expect(near).toBeGreaterThan(4);
+        expect(cells.length).toBeGreaterThan(near);
+        expect(d.slice(0, near)).toEqual([...d.slice(0, near)].sort((a, b) => a - b));
+        expect(d.slice(near).every(m => m >= BUILD_M && m < BUILD_M + AHEAD_M)).toBe(true);
+        const s = size(CELL_LEVEL);
+        for (const cell of cells.slice(near)) expect((cell.x + 0.5) * s - eye.x).toBeGreaterThan(0);
+        expect(wantedCells(eye, undefined, BOUNDS)).toEqual(cells.slice(0, near));
+        // At the west edge of the bounds, no cell lies west of it.
+        const edge = eyeAt(8.3705, 46.8, 1.6);
+        expect(wantedCells(edge, [-1, 0], BOUNDS).every(({ x }) => (x + 1) * s > BOUNDS[0])).toBe(true);
+        expect(wantedCells(eyeAt(8.405, 46.818, 700), east, BOUNDS)).toEqual([]);
+    });
+});
+
+describe('the bridge', () => {
+    let words: Vocabulary;
+    beforeAll(() => {
+        initSync({ module: readFileSync(new URL('./pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url)) });
+        words = JSON.parse(vocabulary());
+    });
+    // The north-west cell of zoom-13 tile 4286/2888, the tile of the vector: its roads with heights lie there.
+    const cell = { x: 4286 * 8, y: 2888 * 8 };
+
+    it('names pages of levels 13 and 14, and builds a cell from a feature tile alone, twice the same', () => {
+        const pages = wanted(cell.x, cell.y);
+        expect(pages.length).toBeGreaterThan(0);
+        for (let i = 0; i < pages.length; i += 7) expect([13, 14]).toContain(pages[i]);
+        const plan = () => {
+            const request = new CellRequest(cell.x, cell.y);
+            request.add_tile(4286, 2888, readFileSync(new URL('../../../../../../specs/vectors/trailview-features.bin', import.meta.url)));
+            return build(request, true);
+        };
+        const [a, b] = [plan(), plan()];
+        try {
+            expect(JSON.parse(a.stats()).inputs).toMatchObject({ pages: 0, tiles: 1 });
+            const samples = a.samples().length / 2, ways = a.ways();
+            expect(ways.length).toBeGreaterThan(0);
+            for (let w = 0; w < ways.length; w += 6) expect(ways[w + 4] + ways[w + 5]).toBeLessThanOrEqual(samples);
+            expect(a.digest()).toBe(b.digest());
+            expect(a.times().length).toBe(words.stages.length);
+            // The debug mesh of the real plan: every vertex in the cell square, every segment within a step.
+            const vertices = a.vertices().length / 2, rings = a.rings(), ringVertices = a.ring_vertices();
+            expect(a.faces().length).toBeGreaterThan(0);
+            for (let r = 0; r < rings.length; r += 2) expect(rings[r] + rings[r + 1]).toBeLessThanOrEqual(ringVertices.length);
+            expect(ringVertices.every(v => v < vertices) && a.edges().every((v, i) => i % 6 > 1 || v < vertices)).toBe(true);
+            const mesh = debugMesh({ samples: a.samples(), ways, points: a.points(), crossings: a.crossings(), vertices: a.vertices(), faces: a.faces(), rings, ring_vertices: ringVertices, edges: a.edges() }, words, cell);
+            expect(mesh.fills.length).toBeGreaterThan(0);
+            expect(mesh.unfilled).toBe(0);
+            const s = size(CELL_LEVEL), unit = metresPerUnit((cell.y + 0.5) * s);
+            expect(mesh.lines.length).toBeGreaterThan(0);
+            for (let v = 0; v < mesh.lines.length; v += 2 * DEBUG_WORDS) {
+                const [ax, ay, , bx, by] = mesh.lines.subarray(v, v + 2 * DEBUG_WORDS);
+                for (const [x, y] of [[ax, ay], [bx, by]]) {
+                    expect(x >= cell.x * s && x <= (cell.x + 1) * s && y >= cell.y * s && y <= (cell.y + 1) * s).toBe(true);
+                }
+                expect(Math.hypot(bx - ax, by - ay) * unit).toBeLessThanOrEqual(EDGE_STEP_M + 0.1);
+            }
+        } finally {
+            a.free();
+            b.free();
+        }
+    });
+});
+
+/** A plan worker that answers `start` and keeps the build messages for the test to answer. */
+class FakeWorker {
+    static all: FakeWorker[] = [];
+    onmessage?: (event: { data: unknown }) => void;
+    onerror?: unknown;
+    builds: Extract[] = [];
+    terminated = false;
+
+    constructor() {
+        FakeWorker.all.push(this);
+    }
+
+    postMessage(message: PlanRequest): void {
+        if (message.type === 'start') queueMicrotask(() => this.onmessage?.({ data: { type: 'ready' } }));
+        if (message.type === 'build') this.builds.push(message);
+    }
+
+    answer(build: { id: number }, reply: Partial | Partial): void {
+        this.onmessage?.({ data: { id: build.id, ...reply } });
+    }
+
+    terminate(): void {
+        this.terminated = true;
+    }
+}
+
+describe('the plan', () => {
+    const settle = () => new Promise(resolve => setTimeout(resolve, 0));
+    const eye = eyeAt(8.405, 46.818, 1.6);
+    const built = (bytes: number, heap = 2 ** 20): Partial => ({
+        ok: true, stats: JSON.stringify({ inputs: { request: 'r' } }), times: [1, 2], prepare: 3, heap,
+        debug: { lines: new Int32Array(bytes / 4), fills: new Int32Array(0), unfilled: 0 },
+    });
+    const start = async () => {
+        FakeWorker.all = [];
+        vi.stubGlobal('Worker', FakeWorker);
+        vi.stubGlobal('fetch', async () => new Response(readFileSync(new URL('./pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url))));
+        const plan = new Plan(async () => new ArrayBuffer(4), async () => undefined, BOUNDS, () => {}, new AbortController().signal);
+        await settle();
+        // The plan builds only for its debug draw: until its first update it loads no bridge and starts no worker.
+        expect(FakeWorker.all.length).toBe(0);
+        plan.debug = true;
+        plan.update(eye, undefined, true);
+        for (let i = 0; i < 20 && !plan.vocabulary; i++) await settle();
+        await settle();
+        return plan;
+    };
+    afterEach(() => vi.unstubAllGlobals());
+
+    it('keeps the records inside their budget and asks no cell again that would not fit', async () => {
+        const plan = await start(), worker = FakeWorker.all[0], asked = new Map();
+        // Debug meshes of 12 MiB: two of them fit in the 32 MiB of the records.
+        for (let frame = 0; frame < 30; frame++) {
+            plan.update(eye, undefined, true);
+            await settle();
+            for (const build of worker.builds.splice(0)) {
+                const name = `${build.cell.x}-${build.cell.y}`;
+                asked.set(name, (asked.get(name) ?? 0) + 1);
+                worker.answer(build, built(12 * 2 ** 20));
+            }
+        }
+        // Two fit; the two jobs in flight when they arrived built once each and went.
+        expect(asked.size).toBeGreaterThan(2);
+        expect(asked.size).toBeLessThanOrEqual(4);
+        expect([...asked.values()].every(n => n === 1)).toBe(true);
+        expect(plan.stats.cells).toBe(2);
+        expect(plan.loading).toBe(false);
+        expect(plan.stats.build.prepare).toBe(3);
+    });
+
+    it('starts a new worker after a trap or a full heap, also for a cell that went out of range', async () => {
+        const plan = await start();
+        plan.update(eye, undefined, true);
+        await settle();
+        const [first, second] = FakeWorker.all[0].builds;
+        FakeWorker.all[0].answer(first, { ok: false, error: 'unreachable', trapped: true });
+        expect(FakeWorker.all.length).toBe(2);
+        expect(FakeWorker.all[0].terminated).toBe(true);
+        expect(plan.stats).toMatchObject({ restarts: 1, failed: 1 });
+        // A late answer of the ended worker counts no more.
+        FakeWorker.all[0].answer(second, built(4));
+        await settle();
+        plan.update(eye, undefined, true);
+        await settle();
+        const next = FakeWorker.all[1].builds[0];
+        plan.update(eyeAt(8.445, 46.818, 1.6), undefined, true);
+        FakeWorker.all[1].answer(next, built(4, 60 * 2 ** 20));
+        expect(FakeWorker.all.length).toBe(3);
+        expect(plan.stats.restarts).toBe(2);
+    });
+});
diff --git a/builder/web/src/lib/trailview/plan/plan.ts b/builder/web/src/lib/trailview/plan/plan.ts
new file mode 100644
index 0000000000..4546ffa91e
--- /dev/null
+++ b/builder/web/src/lib/trailview/plan/plan.ts
@@ -0,0 +1,313 @@
+// The ground plan about the eye, with `ground=plan`: picks the cells, collects their inputs, and builds
+// them in one plan worker. The main thread's instance of the bridge only names inputs; no build runs
+// here, because one synchronous build would block the frames.
+import { stopped } from '../stream/terrain';
+import { distances, key, size, type Node } from '../terrain/lod';
+import type { FeatureTiles } from '../terrain/stamps';
+import { failedMesh, type DebugMesh, type Vocabulary } from './debug';
+import { PlanDraw } from './draw';
+import { cellInputs, type StoredTiles } from './inputs';
+import { bridge, planWorker } from './bridge';
+import { feature_tiles, wanted } from './pkg/obc_ground_plan_bridge.js';
+import type { Built, Failed, PlanRequest } from './plan-worker';
+
+/** The level of the nodes that are cells: zoom 16. */
+export const CELL_LEVEL = 16;
+/** The mesh range of the ground plan. */
+export const BUILD_M = 600;
+/** A cell builds this far before it comes into range: as AHEAD_M of the roads, about 20 s of a car. */
+export const AHEAD_M = 300;
+/** "Ahead" is within 60° of the view direction. */
+const AHEAD_COS = 0.5;
+/** A cell drops past this: 100 m past BUILD_M + AHEAD_M, so a cell at the edge does not build again when the eye moves to and fro. */
+const KEEP_M = 1000;
+/** The CPU bytes of the records: as MESH_BYTES of the roads. */
+const KEPT_BYTES = 32 * 2 ** 20;
+/** The epic's worker heap. WASM memory never shrinks, so a worker past it ends after its job and a new one starts. */
+export const HEAP_LIMIT = 55 * 2 ** 20;
+/** Jobs that the worker holds: one runs and one waits, so it does not idle while the main thread collects inputs. */
+const JOBS = 2;
+/** The builds that the build times cover. */
+const TIMES = 32;
+/** What a record costs besides its debug mesh: its stats and times. */
+const RECORD_BYTES = 2048;
+
+/** The eye: world units, metres per unit, and its height above the ground. */
+export interface PlanEye { x: number; y: number; unit: number; above: number }
+
+type Entry = { node: Node; bytes: number } & (
+    | { state: 'built'; stats: string; times: number[]; digest?: string; request: string; debug?: DebugMesh }
+    | { state: 'empty' }
+    | { state: 'failed'; error: string });
+
+export interface PlanStats {
+    cells: number;
+    building: number;
+    failed: number;
+    restarts: number;
+    /** Milliseconds from a frame with a cell in range without its record to the next frame with them all. */
+    ready: number;
+    /**
+     * Over the last TIMES builds, in ms: the median and the 95th percentile of the WASM stages' total,
+     * the median of each stage, and the median of `prepare`, the worker's gunzip and WebP decode before them.
+     */
+    build: { median: number; p95: number; stages: Record; prepare: number };
+    /** The largest heap of a worker. */
+    heap: number;
+    debugVertices: number;
+    /** Faces of the drawn cells that `earcut` left unfilled. */
+    unfilled: number;
+    /** Per built cell with the debug draw, `x-y`: the digests of its request and its plan. */
+    digests: Record;
+    error?: string;
+}
+
+const quantile = (values: number[], q: number) => {
+    const sorted = [...values].sort((a, b) => a - b);
+    return sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] : 0;
+};
+
+/**
+ * The cells to build, by priority: every cell whose square meets `bounds` (world units: west, north,
+ * east, south) nearer than BUILD_M, by distance; then those up to BUILD_M + AHEAD_M whose middle lies
+ * ahead, by distance; none for an eye BUILD_M or more above the ground. `ahead` is the horizontal view direction in world units (x east, y south), or
+ * undefined when the view looks nearly straight down or up.
+ */
+export function wantedCells(eye: PlanEye, ahead: [number, number] | undefined, bounds: [number, number, number, number]): Node[] {
+    // An eye above the mesh range sees no plan.
+    if (eye.above >= BUILD_M) return [];
+    const s = size(CELL_LEVEL), reach = (BUILD_M + AHEAD_M) / eye.unit, last = 2 ** CELL_LEVEL - 1;
+    const anchor = { whole: [eye.x, eye.y] as [number, number], part: [0, 0] as [number, number], unit: eye.unit };
+    const near: [Node, number][] = [], far: [Node, number][] = [];
+    const span = (v: number) => [Math.max(0, Math.floor((v - reach) / s)), Math.min(last, Math.floor((v + reach) / s))];
+    const [x0, x1] = span(eye.x), [y0, y1] = span(eye.y);
+    for (let y = y0; y <= y1; y++) for (let x = x0; x <= x1; x++) {
+        if (x * s >= bounds[2] || (x + 1) * s <= bounds[0] || y * s >= bounds[3] || (y + 1) * s <= bounds[1]) continue;
+        const node = { level: CELL_LEVEL, x, y }, d = distances({ anchor, above: eye.above }, node)[0];
+        if (d < BUILD_M) near.push([node, d]);
+        else if (d < BUILD_M + AHEAD_M && ahead) {
+            const mx = (x + 0.5) * s - eye.x, my = (y + 0.5) * s - eye.y, length = Math.hypot(mx, my);
+            if (length > 0 && (mx * ahead[0] + my * ahead[1]) / length >= AHEAD_COS) far.push([node, d]);
+        }
+    }
+    const order = (list: [Node, number][]) => list.sort((a, b) => a[1] - b[1]).map(([node]) => node);
+    return [...order(near), ...order(far)];
+}
+
+export class Plan {
+    /** Whether the debug draw is on: builds then carry debug meshes and digests. */
+    debug = false;
+    readonly draw = new PlanDraw();
+    private records = new Map();
+    /** The bytes of each cell's last record, kept past an eviction so that the cell is not asked again while it would not fit. */
+    private sizes = new Map();
+    /** The cells that collect inputs or wait for the worker, with the generation of the worker. */
+    private pending = new Map();
+    private jobs = new Map();
+    private worker?: Worker;
+    /** The bridge's start, at the first update: the plan builds only for its debug draw. */
+    private started?: Promise;
+    private generation = 0;
+    private ready = false;
+    private module?: WebAssembly.Module;
+    private words?: Vocabulary;
+    private error?: string;
+    private next = 0;
+    private restarts = 0;
+    private heap = 0;
+    private times: { stages: number[]; prepare: number }[] = [];
+    private dirty = true;
+    private missing = true;
+    private readyFrom?: number;
+    private readyMs = 0;
+    private eye?: PlanEye;
+
+    /** `stored` gives the stored terrain tiles; an abort of `stop` ends the worker. */
+    constructor(private readonly features: FeatureTiles | undefined, private readonly stored: StoredTiles, private readonly bounds: [number, number, number, number], private readonly changed: () => void, private readonly stop: AbortSignal) {
+        stop.addEventListener('abort', () => this.worker?.terminate());
+        if (!features) this.error = 'the release has no feature tiles';
+    }
+
+    private async load(): Promise {
+        try {
+            ({ module: this.module, vocabulary: this.words } = await bridge());
+            this.spawn();
+        } catch (error) {
+            this.error = `the plan bridge did not start: ${error instanceof Error ? error.message : error}`;
+            this.changed();
+        }
+    }
+
+    private spawn(): void {
+        if (this.stop.aborted) return;
+        const worker = this.worker = planWorker();
+        this.ready = false;
+        this.generation++;
+        worker.onmessage = ({ data }) => this.receive(worker, data);
+        worker.onerror = event => {
+            this.error = `the plan worker failed: ${event.message}`;
+            this.changed();
+        };
+        worker.postMessage({ type: 'start', module: this.module! } satisfies PlanRequest);
+    }
+
+    /** Ends the worker and starts another; the jobs that it held go back to not asked. */
+    private restart(): void {
+        this.worker?.terminate();
+        this.restarts++;
+        this.pending.clear();
+        this.jobs.clear();
+        this.spawn();
+    }
+
+    private receive(worker: Worker, data: { type: 'ready'; error?: string } | Built | Failed): void {
+        if (worker !== this.worker) return;
+        if ('type' in data) {
+            if (data.error) this.error = `the plan worker did not start: ${data.error}`;
+            else this.ready = true;
+            return this.changed();
+        }
+        const name = this.jobs.get(data.id);
+        this.jobs.delete(data.id);
+        if (name === undefined) return;
+        this.pending.delete(name);
+        const node = nodeOf(name);
+        if (data.ok) {
+            this.times = [...this.times.slice(1 - TIMES), { stages: data.times, prepare: data.prepare }];
+            this.heap = Math.max(this.heap, data.heap);
+        }
+        // A trapped instance or a full heap ends the worker, whatever happens to the result.
+        if (data.ok ? data.heap > HEAP_LIMIT : data.trapped) this.restart();
+        if (!this.eye || distance(this.eye, node) > KEEP_M) return this.changed();
+        if (data.ok) {
+            const request = (JSON.parse(data.stats) as { inputs: { request: string } }).inputs.request;
+            this.store(name, { node, state: 'built', stats: data.stats, times: data.times, digest: data.digest, request, debug: data.debug, bytes: RECORD_BYTES + (data.debug ? data.debug.lines.byteLength + data.debug.fills.byteLength : 0) });
+        } else this.store(name, { node, state: 'failed', error: data.error, bytes: RECORD_BYTES });
+        this.dirty = true;
+        this.changed();
+    }
+
+    private store(name: string, record: Entry): void {
+        this.records.set(name, record);
+        this.sizes.set(name, record.bytes);
+    }
+
+    /** A record that serves: with the debug draw on, a build without its debug mesh counts as missing. */
+    private serves(record: Entry | undefined): boolean {
+        return !!record && !(this.debug && record.state === 'built' && !record.debug);
+    }
+
+    /**
+     * Picks the cells for the eye, drops the far records and asks the worker for the next cells while
+     * `build` lets it. Returns whether the drawn debug meshes changed.
+     */
+    update(eye: PlanEye, ahead: [number, number] | undefined, build: boolean): boolean {
+        this.eye = eye;
+        this.started ??= this.error ? undefined : this.load();
+        if (this.error && !this.module) return false;
+        const cells = wantedCells(eye, ahead, this.bounds);
+        for (const [name, record] of this.records) {
+            if (distance(eye, record.node) > KEEP_M) {
+                this.records.delete(name);
+                this.dirty = true;
+            }
+        }
+        for (const name of this.sizes.keys()) if (distance(eye, nodeOf(name)) > KEEP_M) this.sizes.delete(name);
+        // The records of the wanted cells first, by priority, then the others by distance. The kept
+        // records are a prefix of that order: from the first that does not fit, all go.
+        const wantedNames = cells.map(key), wantedSet = new Set(wantedNames);
+        const others = [...this.records.keys()].filter(name => !wantedSet.has(name)).sort((a, b) => distance(eye, nodeOf(a)) - distance(eye, nodeOf(b)));
+        let bytes = 0, full = false;
+        for (const name of [...wantedNames, ...others]) {
+            const record = this.records.get(name);
+            if (!record) continue;
+            if (full || bytes + record.bytes > KEPT_BYTES) {
+                full = true;
+                this.records.delete(name);
+                this.dirty = true;
+            } else bytes += record.bytes;
+        }
+        full = false;
+        let missing = false;
+        for (const node of cells) {
+            const name = key(node), record = this.records.get(name);
+            if (this.serves(record)) continue;
+            // A cell asks only while its last size fits: else it would build, go and build again every frame.
+            if (bytes + (this.sizes.get(name) ?? RECORD_BYTES) > KEPT_BYTES) {
+                full = true;
+                break;
+            }
+            if (distance(eye, node) < BUILD_M) missing = true;
+            if (!build || !this.ready || this.pending.has(name) || this.pending.size >= JOBS) continue;
+            void this.ask(node);
+        }
+        this.missing = missing && !full;
+        const now = performance.now();
+        if (this.missing) this.readyFrom ??= now;
+        else if (this.readyFrom !== undefined) {
+            this.readyMs = now - this.readyFrom;
+            this.readyFrom = undefined;
+        }
+        if (!this.dirty) return false;
+        this.dirty = false;
+        const meshes = [...this.records.values()].flatMap(record => (record.state === 'built' && record.debug ? [record.debug] : record.state === 'failed' ? [failedMesh(record.node)] : []));
+        this.draw.set(meshes);
+        return this.debug;
+    }
+
+    private async ask(node: Node): Promise {
+        const name = key(node), generation = this.generation;
+        this.pending.set(name, generation);
+        try {
+            const inputs = await cellInputs(node, { feature_tiles, wanted, words: this.words!.words.wanted }, this.features!, this.stored);
+            if (this.pending.get(name) !== generation) return;
+            if (inputs === 'empty') {
+                this.pending.delete(name);
+                this.store(name, { node, state: 'empty', bytes: RECORD_BYTES });
+            } else {
+                const id = this.next++;
+                this.jobs.set(id, name);
+                const message: PlanRequest = { type: 'build', id, cell: node, ...inputs, debug: this.debug };
+                this.worker!.postMessage(message, inputs.tiles.flatMap(({ body }) => (body ? [body] : [])));
+                return;
+            }
+        } catch (error) {
+            if (stopped(error) || this.pending.get(name) !== generation) return;
+            this.pending.delete(name);
+            this.store(name, { node, state: 'failed', error: error instanceof Error ? error.message : String(error), bytes: RECORD_BYTES });
+        }
+        this.dirty = true;
+        this.changed();
+    }
+
+    /** True while a cell in range has no record. False when the bridge failed to start, so a wait for an idle view ends. */
+    get loading(): boolean {
+        return !this.error && this.missing;
+    }
+
+    /** The bridge's names and colours, once it started. */
+    get vocabulary(): Vocabulary | undefined {
+        return this.words;
+    }
+
+    get stats(): PlanStats {
+        const records = [...this.records.values()], built = records.flatMap(r => (r.state === 'built' ? [r] : []));
+        const stages = Object.fromEntries((this.words?.stages ?? []).map((stage, i) => [stage, quantile(this.times.map(t => t.stages[i]), 0.5)]));
+        const totals = this.times.map(t => t.stages.reduce((sum, ms) => sum + ms, 0)), prepare = quantile(this.times.map(t => t.prepare), 0.5);
+        return {
+            cells: built.length, building: this.pending.size, failed: records.filter(r => r.state === 'failed').length, restarts: this.restarts, ready: this.readyMs,
+            build: { median: quantile(totals, 0.5), p95: quantile(totals, 0.95), stages, prepare }, heap: this.heap, debugVertices: this.draw.vertices,
+            unfilled: built.reduce((sum, r) => sum + (r.debug?.unfilled ?? 0), 0),
+            digests: Object.fromEntries(built.flatMap(r => (r.digest ? [[`${r.node.x}-${r.node.y}`, { request: r.request, plan: r.digest }]] : []))),
+            ...(this.error ? { error: this.error } : {}),
+        };
+    }
+}
+
+const nodeOf = (name: string): Node => {
+    const [level, x, y] = name.split('/').map(Number);
+    return { level, x, y };
+};
+
+/** The metres from the eye to a cell's square, with the eye's height above the ground. */
+const distance = (eye: PlanEye, node: Node) => distances({ anchor: { whole: [eye.x, eye.y], part: [0, 0], unit: eye.unit }, above: eye.above }, node)[0];
diff --git a/builder/web/src/lib/trailview/roads/cores.test.ts b/builder/web/src/lib/trailview/roads/cores.test.ts
index 9679afb48f..0a968698ad 100644
--- a/builder/web/src/lib/trailview/roads/cores.test.ts
+++ b/builder/web/src/lib/trailview/roads/cores.test.ts
@@ -10,7 +10,7 @@ describe('the cores of the ways', () => {
         const y = 2 ** 29, m = 1 / metresPerUnit(y);
         // A residential road east, 2.5 m each side; a sidewalk on its right (south) from its middle vertex on.
         const line = { kind: ROAD, xy: [-50 * m, y, 0, y, 50 * m, y], z: [0, 0, 0], h: 2.5, code: 2, ford: false, profile: Object.keys(PROFILES).indexOf('residential'), sidewalks: [0, RIGHT] } as Line;
-        const cores = coresOf({ lines: [line], lakes: [], seas: [], areas: [], buildings: [] } as unknown as Shapes), across = 2.5 + walkOf(line) - 0.2;
+        const cores = coresOf({ lines: [line], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes), across = 2.5 + walkOf(line) - 0.2;
         expect(across).toBeGreaterThan(2.9);
         expect(coreAt(cores, 0.5 * m, y + across * m)?.side).toBe(-1);
         expect(coreAt(cores, -1 * m, y + across * m)).toBeUndefined();
@@ -22,11 +22,21 @@ describe('the cores of the ways', () => {
         expect(coreAt(cores, -1 * m, y + across * m, 1)).toBeDefined();
         // A sidewalk that ends at the middle vertex: the step after it lies on the next segment.
         const ends = { ...line, sidewalks: [RIGHT, 0] };
-        const ended = coresOf({ lines: [ends], lakes: [], seas: [], areas: [], buildings: [] } as unknown as Shapes);
+        const ended = coresOf({ lines: [ends], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes);
         expect(coreAt(ended, -0.5 * m, y + across * m)?.side).toBe(-1);
         expect(coreAt(ended, 0.5 * m, y + across * m)).toBeUndefined();
     });
 
+    it('hold a point on a way\'s curve that lies far from its vertices', () => {
+        const y = 2 ** 29, m = 1 / metresPerUnit(y), turn = Math.PI / 2, flat = [0, 0];
+        // A road of two vertices 400 m apart that leaves north and comes in heading south: its curve passes 100 m, a quarter of
+        // the segment, north of its middle. The most that a curve can leave its segment.
+        const line = { kind: ROAD, xy: [-200 * m, y, 200 * m, y], z: flat, h: 2.5, code: 2, ford: false, profile: Object.keys(PROFILES).indexOf('residential'), plan: { tangent: [-turn, turn], grade: flat, bank: flat, widen: flat } } as Line;
+        const cores = coresOf({ lines: [line], lakes: [], seas: [], pads: [], areas: [], buildings: [] } as unknown as Shapes);
+        expect(coreAt(cores, 0, y - 100 * m)).toBeDefined();
+        expect(coreAt(cores, 0, y)).toBeUndefined();
+    });
+
     it('give the stand of points.wgsl the band rows that the corridor draws', () => {
         const wgsl = readFileSync(new URL('./band.wgsl', import.meta.url), 'utf8');
         const rows = (name: string) => [...new RegExp(`const ${name} = vec3f\\(([^)]*)\\);`).exec(wgsl)![1].split(',').map(Number)];
diff --git a/builder/web/src/lib/trailview/roads/cores.ts b/builder/web/src/lib/trailview/roads/cores.ts
index 292897a92b..da3a203bac 100644
--- a/builder/web/src/lib/trailview/roads/cores.ts
+++ b/builder/web/src/lib/trailview/roads/cores.ts
@@ -1,5 +1,5 @@
 // Where a model at a point stands beside the ways: the cores of a tile's ways as their corridors draw them, and the place out of them.
-import { insideRings, junctions, metresPerUnit, PATH, ringsDistance, RIVER, STREAM, type Line, type Shapes } from '../terrain/bins';
+import { insideRings, junctions, linesNear, metresPerUnit, nearBoxes, PATH, ringsDistance, RIVER, STREAM, tileIndex, type Line, type Shapes } from '../terrain/bins';
 import { halfAt, partnersOf } from '../terrain/corners';
 import { near, townOf, type Town } from '../terrain/town';
 import { direction } from './arms';
@@ -8,22 +8,32 @@ import { CF, corridorLine, sideOf, type Part } from './section';
 import { between, stationsOf, type Station } from './stations';
 
 /**
- * The ground of a tile that a model at a point keeps out of. `ways`: the roads, tracks, paths and railways
- * with a corridor on the ground; a deck stands over the ground, and the test is flat. `partners` set a
+ * The ground of a tile that a model at a point keeps out of. Its ways (`isWay`) are the roads, tracks, paths and
+ * railways with a corridor on the ground; a deck stands over the ground, and the test is flat. `partners` set a
  * road's half-width at its ends. `meetings`: the points where three ways or more meet, decks included.
  * And the buildings and the water.
  */
 export interface Cores {
-    ways: Line[];
+    shapes: Shapes;
+    /**
+     * How far the core of each line of the tile can lie from the box of its vertices. `half`: the widest half-width of
+     * the line and of its stations, in metres. `bulge`: the most that a way's curve leaves its segments, a quarter of
+     * its longest, in world units. `widest` holds the greatest of each.
+     */
+    half: Float64Array;
+    bulge: Float64Array;
+    widest: { half: number; bulge: number };
     partners: Map;
     meetings: { x: number; y: number; lines: Line[] }[];
     /** The points that two ways or more share, where a junction's corner can lie. */
     joints: { x: number; y: number }[];
-    buildings: Shapes['buildings'];
     town: Town;
-    water: { rings: number[][][]; lines: Line[] };
 }
 
+/** A way with a corridor on the ground, and a waterway. */
+const isWay = (line: Line) => corridorLine(line) && !isDeck(line) && line.z.length > 1;
+const isWater = ({ kind }: Line) => kind === STREAM || kind === RIVER;
+
 /**
  * How a model at a point keeps out of the ways: `half`, the metres that it reaches from its foot across the
  * way, `radius`, the most that it reaches any way (`half` without it), and whether it stands in a junction's
@@ -44,16 +54,24 @@ const coresByTile = new WeakMap(), stationsByLine = new WeakMap corridorLine(line) && !isDeck(line) && line.z.length > 1);
+    const { lines, buildings } = shapes, ways = lines.filter(isWay), partners = partnersOf(lines);
     const meet = [...ways, ...lines.filter(isDeck)], at = new Map();
     for (const line of meet) line.z.forEach((_, v) => {
         const key = `${line.xy[2 * v]},${line.xy[2 * v + 1]}`;
         (at.get(key) ?? at.set(key, []).get(key)!).push(line);
     });
     const meetings = [...junctions(meet)].filter(([, j]) => j.ways >= 3).map(([key, { x, y }]) => ({ x, y, lines: [...new Set(at.get(key))] }));
-    const water = { rings: [...shapes.lakes, ...shapes.seas, ...shapes.areas].map(({ rings }) => rings), lines: lines.filter(({ kind }) => kind === STREAM || kind === RIVER) };
     const joints = [...at].filter(([, here]) => new Set(here).size > 1).map(([key]) => key.split(',').map(Number)).map(([x, y]) => ({ x, y }));
-    coresByTile.set(shapes, (cores = { ways, partners: partnersOf(lines), meetings, joints, buildings, town: townOf(buildings), water }));
+    const half = Float64Array.from(lines, ({ h }) => h), bulge = new Float64Array(lines.length), widest = { half: 0, bulge: 0 };
+    lines.forEach((line, k) => {
+        if (isWay(line)) for (let v = 0; v < line.z.length; v++) {
+            half[k] = Math.max(half[k], halfAt(line, v, partners));
+            if (v) bulge[k] = Math.max(bulge[k], Math.hypot(line.xy[2 * v] - line.xy[2 * v - 2], line.xy[2 * v + 1] - line.xy[2 * v - 1]) / 4);
+        }
+        widest.half = Math.max(widest.half, half[k]);
+        widest.bulge = Math.max(widest.bulge, bulge[k]);
+    });
+    coresByTile.set(shapes, (cores = { shapes, half, bulge, widest, partners, meetings, joints, town: townOf(buildings) }));
     return cores;
 }
 
@@ -71,11 +89,12 @@ const WALL_M = 0.5, WATER_M = 0.3;
 /** The search out of the cores: its step, and the farthest a point moves. */
 const STEP_M = 0.1, FARTHEST_M = 30;
 
-/** Of `ways`, those whose side may reach within `metres` of world point x, y. */
-function waysNear(ways: Line[], x: number, y: number, metres: number): Line[] {
-    const unit = metresPerUnit(y);
-    return ways.filter(({ xy, h }) => {
-        const r = (h + PAST_HALF_M + metres) / unit;
+/** The numbers of the tile's lines of a kind (`of`) whose side may reach within `metres` of world point x, y, in their order. */
+function sidesNear(cores: Cores, of: (line: Line) => boolean, x: number, y: number, metres: number): number[] {
+    const unit = metresPerUnit(y), { lines } = cores.shapes;
+    return linesNear(cores.shapes, x, y, (cores.widest.half + PAST_HALF_M + metres) / unit).filter(k => {
+        if (!of(lines[k])) return false;
+        const { xy, h } = lines[k], r = (h + PAST_HALF_M + metres) / unit;
         for (let i = 0; i + 3 < xy.length; i += 2) {
             if (Math.min(xy[i], xy[i + 2]) - r < x && Math.max(xy[i], xy[i + 2]) + r > x && Math.min(xy[i + 1], xy[i + 3]) - r < y && Math.max(xy[i + 1], xy[i + 3]) + r > y) return true;
         }
@@ -100,17 +119,22 @@ function beyond(s: Station, dx: number, dy: number, x: number, y: number): numbe
 export interface Foot { line: Line; foot: Station; side: 1 | -1; metres: number; parts: Part[]; edge: number }
 
 /**
- * Of `ways`, the side that holds world point x, y most deeply, out to `reach` metres from the line, as the
- * corridors draw it: each step between two stations with its own width, and a round cap at each end.
+ * Of the tile's lines with the numbers `ways`, the side that holds world point x, y most deeply, out to `reach` metres
+ * from the line, as the corridors draw it: each step between two stations with its own width, and a round cap at each end.
  */
-function deepest(cores: Cores, ways: Line[], x: number, y: number, reach: (parts: Part[], edge: number) => number): Foot | undefined {
-    const unit = metresPerUnit(y);
+function deepest(cores: Cores, ways: number[], x: number, y: number, reach: (parts: Part[], edge: number) => number): Foot | undefined {
+    const unit = metresPerUnit(y), { lines } = cores.shapes, { boxes } = tileIndex(cores.shapes).lines;
     let most = 0, found: Foot | undefined;
-    for (const line of ways) {
-        const st = stationsIn(cores, line);
+    for (const way of ways) {
+        // A station lies on the line's curve, within `bulge` of the box of its vertices, and a step holds no point farther
+        // than PAST_HALF_M past its half-width: a line whose box lies farther off has no step for the point, and a step
+        // whose box lies farther off does not hold it. One unit more for the rounding.
+        const box = boxes[way], r = cores.bulge[way] + (cores.half[way] + PAST_HALF_M) / unit + 1;
+        if (x < box[0] - r || x > box[2] + r || y < box[1] - r || y > box[3] + r) continue;
+        const line = lines[way], st = stationsIn(cores, line);
         for (let k = 0; k + 1 < st.length; k++) {
-            const s = st[k], t = st[k + 1], dx = t.x - s.x, dy = t.y - s.y, l = dx * dx + dy * dy;
-            if (!l) continue;
+            const s = st[k], t = st[k + 1], dx = t.x - s.x, dy = t.y - s.y, l = dx * dx + dy * dy, far = (s.h + PAST_HALF_M) / unit + 1;
+            if (!l || x < Math.min(s.x, t.x) - far || x > Math.max(s.x, t.x) + far || y < Math.min(s.y, t.y) - far || y > Math.max(s.y, t.y) + far) continue;
             // A step's faces lie between the cross-sections of its stations, so steps meet with no wedge in a
             // bend. A way's end has a round cap (mesh.ts), or a joint where another way goes on.
             if ((beyond(s, dx, dy, x, y) < 0 && k > 0) || (beyond(t, dx, dy, x, y) > 0 && k + 2 < st.length)) continue;
@@ -126,12 +150,14 @@ function deepest(cores: Cores, ways: Line[], x: number, y: number, reach: (parts
 }
 
 /** The core of the ways that holds world point x, y most deeply, widened by `past` metres; undefined outside every core. */
-export function coreAt(cores: Cores, x: number, y: number, past = 0, ways = cores.ways): Foot | undefined {
+export function coreAt(cores: Cores, x: number, y: number, past = 0): Foot | undefined {
+    const { lines } = cores.shapes, { half, bulge } = cores.widest;
+    const ways = linesNear(cores.shapes, x, y, bulge + (half + PAST_HALF_M) / metresPerUnit(y)).filter(k => isWay(lines[k]));
     return deepest(cores, ways, x, y, (_, edge) => edge + past);
 }
 
 /** The way whose band reaches world point x, y past its core, out to the row that sinks under the mesh. */
-function besideAt(cores: Cores, x: number, y: number, ways: Line[]): Beside | undefined {
+function besideAt(cores: Cores, x: number, y: number, ways: number[]): Beside | undefined {
     const hit = deepest(cores, ways, x, y, parts => parts[parts.length - 1].a);
     if (!hit || hit.metres < hit.edge) return undefined;
     const { line, foot, side, metres, parts, edge } = hit, sampled = Math.max(edge, ...parts.filter(({ flags }) => flags === CF.SAMPLE).map(({ a }) => a));
@@ -151,12 +177,29 @@ function lineMetres({ xy }: Line, x: number, y: number): number {
 
 /** Whether the box of a ring comes within `reach` world units of world point x, y. */
 function boxNear(ring: number[], x: number, y: number, reach: number): boolean {
-    const xs = ring.filter((_, i) => i % 2 === 0), ys = ring.filter((_, i) => i % 2 === 1);
-    return Math.min(...xs) - reach < x && Math.max(...xs) + reach > x && Math.min(...ys) - reach < y && Math.max(...ys) + reach > y;
+    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+    for (let i = 0; i < ring.length; i += 2) {
+        x0 = Math.min(x0, ring[i]);
+        y0 = Math.min(y0, ring[i + 1]);
+        x1 = Math.max(x1, ring[i]);
+        y1 = Math.max(y1, ring[i + 1]);
+    }
+    return x0 - reach < x && x1 + reach > x && y0 - reach < y && y1 + reach > y;
+}
+
+/** The rings of the tile's lakes, seas and river areas that have a ring whose box comes within `reach` world units of world point x, y, in the tile's order. */
+function waterNear({ shapes }: Cores, x: number, y: number, reach: number): number[][][] {
+    const { outlines } = tileIndex(shapes), { seasFrom, padsFrom, areasFrom, buildingsFrom } = outlines, found: number[][][] = [];
+    // The outlines hold the pads between the seas and the river areas, and the buildings after them. One unit more for the rounding.
+    for (const k of nearBoxes(outlines, [x, y, x, y], reach + 1)) {
+        const area = k < seasFrom ? shapes.lakes[k] : k < padsFrom ? shapes.seas[k - seasFrom] : k >= areasFrom && k < buildingsFrom ? shapes.areas[k - areasFrom] : undefined;
+        if (area?.rings.some(ring => boxNear(ring, x, y, reach))) found.push(area.rings);
+    }
+    return found;
 }
 
-/** What lies near a point that a model keeps out of: the ways, and the water. */
-interface Near { ways: Line[]; rings: number[][][]; streams: Line[] }
+/** What lies near a point that a model keeps out of: the numbers of the ways, and the water. */
+interface Near { ways: number[]; rings: number[][][]; streams: Line[] }
 
 /**
  * A model keeps out to the band's first row: from the core's edge to there the corridor's face falls from a
@@ -171,7 +214,7 @@ function groundAt(cores: Cores, { ways, rings, streams }: Near, cornered: (x: nu
     const unit = metresPerUnit(y);
     if (rings.some(ring => insideRings(ring, x, y)) || streams.some(line => lineMetres(line, x, y) < line.h + WATER_M)) return 'blocked';
     let walled = false;
-    near(cores.town, x, y, x, y, WALL_M / unit, b => (walled ||= insideRings(cores.buildings[b].rings, x, y) || ringsDistance(cores.buildings[b].rings, x, y) * unit < WALL_M));
+    near(cores.town, x, y, x, y, WALL_M / unit, b => (walled ||= insideRings(cores.shapes.buildings[b].rings, x, y) || ringsDistance(cores.shapes.buildings[b].rings, x, y) * unit < WALL_M));
     if (walled) return 'blocked';
     return deepest(cores, ways, x, y, firstRow) || cornered(x, y) ? 'way' : 'free';
 }
@@ -208,7 +251,7 @@ function placeAlong(cores: Cores, nearby: Near, cornered: (x: number, y: number)
  */
 export function besideWays(cores: Cores, cornered: (x: number, y: number) => boolean, x: number, y: number, stand: Stand, taken: Taken[] = []): { x: number; y: number; yaw?: number; beside?: Beside } {
     const { corner = false } = stand;
-    const ways = waysNear(cores.ways, x, y, FARTHEST_M), unit = metresPerUnit(y), core = deepest(cores, ways, x, y, firstRow);
+    const ways = sidesNear(cores, isWay, x, y, FARTHEST_M), unit = metresPerUnit(y), core = deepest(cores, ways, x, y, firstRow);
     const stay = { x, y, beside: besideAt(cores, x, y, ways) };
     if (!core && !cornered(x, y)) return stay;
     const meeting = nearest(cores.meetings, x, y), leaves: Leave[] = [];
@@ -226,10 +269,7 @@ export function besideWays(cores: Cores, cornered: (x: number, y: number) => boo
             leaves.push(away([(x - joint.x) / l, (y - joint.y) / l]));
         }
     }
-    const reach = FARTHEST_M / unit, nearby: Near = {
-        ways, streams: waysNear(cores.water.lines, x, y, FARTHEST_M),
-        rings: cores.water.rings.filter(rings => rings.some(ring => boxNear(ring, x, y, reach))),
-    };
+    const nearby: Near = { ways, streams: sidesNear(cores, isWater, x, y, FARTHEST_M).map(k => cores.shapes.lines[k]), rings: waterNear(cores, x, y, FARTHEST_M / unit) };
     for (const leave of leaves) {
         const at = placeAlong(cores, nearby, cornered, leave, stand, taken);
         if (at) return { x: at[0], y: at[1], yaw: Math.atan2(leave.front[0], leave.front[1]), beside: besideAt(cores, at[0], at[1], ways) };
diff --git a/builder/web/src/lib/trailview/roads/corridor-in.wgsl b/builder/web/src/lib/trailview/roads/corridor-in.wgsl
new file mode 100644
index 0000000000..622a1f1d27
--- /dev/null
+++ b/builder/web/src/lib/trailview/roads/corridor-in.wgsl
@@ -0,0 +1,24 @@
+// The corridors' varyings, and the hooks of a stop arm's mouth (plan/mouth-in.wgsl takes this file's place in the
+// pieces of a stop arm's junction): no other pixel pays for the mouth.
+
+struct CorridorOut {
+    @builtin(position) @invariant clip: vec4f,
+    // Units about the anchor.
+    @location(0) u: vec2f,
+    @location(1) relative: vec3f,
+    @location(2) altitude: f32,
+    @location(3) @interpolate(flat) word: u32,
+    // Metres across and the half-width.
+    @location(4) road: vec2f,
+    @location(5) along: f32,
+    // A piece's normal in LOD-space axes; zero on a corridor.
+    @location(6) normal: vec3f,
+}
+
+// The pixel as it shades: here as it comes.
+fn corridor_in(in: CorridorOut) -> CorridorOut {
+    return in;
+}
+
+// A piece corner's label in its cell's records: here none is kept.
+fn corridor_label(out: ptr, label: u32) {}
diff --git a/builder/web/src/lib/trailview/roads/corridor.wgsl b/builder/web/src/lib/trailview/roads/corridor.wgsl
index 894bf4bcc7..2e1a11d54e 100644
--- a/builder/web/src/lib/trailview/roads/corridor.wgsl
+++ b/builder/web/src/lib/trailview/roads/corridor.wgsl
@@ -5,10 +5,13 @@ diagnostic(off, derivative_uniformity);
 // the ground's colour into the way, so an edge stays in place as the eye moves and fades as the paint's does. What is
 // all ground, and the share that the paint takes near the end of the corridors' reach, discard: the terrain draws
 // those pixels once. The paint's share draws by a dither, and the frames resolve it. The parts of parts.ts are
-// instances that share the fragment stage.
+// instances that share the fragment stage. So do the pieces of the ground plan's mesh (plan/piece.wgsl), with PIECE.
 // #include ../ground/look.wgsl
+// #include ../terrain/drawn-mesh.wgsl
 // #include band.wgsl
 // #include looks.wgsl
+// #include corridor-in.wgsl
+// #include ../terrain/water-look.wgsl
 
 // As Frame of terrain.wgsl, which shares its buffer.
 struct Frame {
@@ -21,10 +24,11 @@ struct Frame {
 }
 
 @group(0) @binding(0) var frame: Frame;
+// The debug view `owned` of DEBUG_VIEWS (view.ts).
+const OWNED_VIEW: u32 = 11u;
 
 // As piece.ts.
 const CORRIDOR_STEP: f32 = 0.083333336;
-const HALF_STEP_M: f32 = 0.025;
 const ACROSS_STEP_M: f32 = 0.0078163;
 const ALONG_STEP: f32 = 0.015625;
 const MAT_BITS: u32 = 127u;
@@ -35,8 +39,20 @@ const PRIO_SHIFT: u32 = 16u;
 const HALF_SHIFT: u32 = 19u;
 const HALF_BITS: u32 = 511u;
 const FINE_SHIFT: u32 = 28u;
-// As MAT, LOOK and CF of section.ts.
+// As MAT, LOOK and CF of section.ts. A piece's water face, and a step slot whose upper side is water: the
+// water's look (water-look.wgsl).
 const MAT_GROUND: u32 = 1u;
+const MAT_WATER: u32 = 50u;
+// In a piece's wall's word, the code bit (1 << CODE_SHIFT) that its look does not read: its road stands on its higher
+// side (plan/piece.wgsl).
+const WALL_FILL: u32 = 128u;
+// In a piece's concrete word, the next code bit, which its look does not read: the dark inside of a culvert's mouth
+// (plan/piece.wgsl), this colour.
+const CULVERT_DARK: u32 = 256u;
+// In a piece's word, the fine offset's top bit, which no corner of a cell's mesh sets: a storey's top
+// (plan/piece.wgsl), whose way paints its details at any distance (DETAIL_EVERYWHERE).
+const STOREY_TOP: u32 = 2147483648u;
+const CULVERT_INSIDE: vec3f = vec3f(0.018, 0.02, 0.018);
 const CF_SAMPLE: u32 = 1u;
 const CF_MESH: u32 = 2u;
 const CF_FILL: u32 = 3u;
@@ -55,6 +71,19 @@ const CORRIDOR_BIAS_SHARE: f32 = 0.003;
 // A wall's face and capstone draw this far nearer still: a coarse triangle of the terrain can cut the crease at a
 // wall's foot and stand in front of it.
 const WALL_BIAS_M: f32 = 0.3;
+// A piece of the ground plan's mesh: no paint hands over to it and no terrain stands under it, so it draws
+// every pixel, its ground too, lit by its own normal.
+override PIECE: bool = false;
+// A stop arm's junction faces of the ground plan's mesh (plan/pieces.ts): their pixels find the mouth (corridor_in).
+override MOUTH: bool = false;
+// A piece that reaches past the level-18 plateau of the LOD fades out by a dither across the band where the
+// terrain morphs to level 17, and the terrain's far look shows through: the frames resolve the two.
+override CUT: bool = false;
+// A piece's edge looks (lines, fray, grass) lie within this of its frame's edge. Its edge opens by how much farther
+// the paved area goes on past the frame's edge, from the first to the second.
+const EDGE_LOOK_M: f32 = 0.6;
+const OPEN_FROM_M: f32 = 0.15;
+const OPEN_TO_M: f32 = 0.35;
 // Moves the dither of a detail's fade off the paint's.
 const DETAIL_DITHER: vec2f = vec2f(61.0, 7.0);
 // As piece.ts: an instance's fine place, turn and grade.
@@ -75,18 +104,6 @@ struct CorridorIn {
     @location(4) middle: vec2i,
 }
 
-struct CorridorOut {
-    @builtin(position) clip: vec4f,
-    // Units about the anchor.
-    @location(0) u: vec2f,
-    @location(1) relative: vec3f,
-    @location(2) altitude: f32,
-    @location(3) @interpolate(flat) word: u32,
-    // Metres across and the half-width.
-    @location(4) road: vec2f,
-    @location(5) along: f32,
-}
-
 struct PartIn {
     // Metres across to the left, ahead and up from the instance's point.
     @location(0) at: vec3f,
@@ -152,6 +169,7 @@ fn corridor_vertex(v: CorridorIn) -> CorridorOut {
     out.word = v.word;
     out.road = vec2f(across, half);
     out.along = f32(v.place >> 12u) * ALONG_STEP;
+    out.normal = vec3f(0.0);
     return out;
 }
 
@@ -196,6 +214,7 @@ fn part_vertex(v: PartIn) -> CorridorOut {
     out.word = v.word;
     out.road = vec2f(v.at.x, 0.0);
     out.along = v.at.y;
+    out.normal = vec3f(0.0);
     return out;
 }
 
@@ -204,34 +223,213 @@ fn part_caster(v: PartIn) -> @builtin(position) vec4f {
     return frame.view_proj * vec4f(part_at(v, part_point(v)).xyz, 1.0);
 }
 
-// The ground at a pixel of a corridor; a path's band reads no mask.
+// The ground at a pixel of a corridor; a path's band reads no mask. A piece's ground is the terrain's: the
+// pages' normal and the texels of how far the heights moved the ground, which the stamp made from the same
+// heights, so it shades as the terrain beside it does. A slope's daylight line runs through the mesh's
+// triangles, whose vertices would draw it as a sawtooth. Its nearest way is its corners': a ground corner
+// holds the metres past that way's edge and its half-width (plan/corners.wgsl), a paved face's pixel its own
+// way's. The mask's texels give no half-width far from a way's middle.
 fn corridor_ground(in: CorridorOut, su: vec2f, d: mat2x3f) -> vec3f {
-    return ground_colour(su, in.relative, d, in.altitude, u32(ceil(lod(su))), in.clip.xy, select(0.0, 1.0, in.road.y < PATH_HALF_M));
+    if (PIECE) {
+        // A step's bank: its level normal, as long as its share of the light (slot_vertex of plan/piece.wgsl).
+        var n = drawn_relief(su);
+        let share = length(in.normal);
+        if (abs(in.normal.z) < 0.01 && share > 0.0) {
+            n = vec4f(normalize(mix(n.xyz, in.normal / share, min(share, 1.0))), n.w);
+        }
+        return piece_ground(in, su, d, n, 0.0);
+    }
+    return ground_colour(su, in.relative, d, in.altitude, u32(ceil(lod(su))), in.clip.xy, band_road(select(0.0, 1.0, in.road.y < PATH_HALF_M)), drawn_relief(su));
+}
+
+// A piece's ground at a pixel, lit and looked by the normal `n` in LOD-space axes and its turn per texel in w
+// (ground_colour); `wall` 1 for a wall that stands as rock (wall_rock), which ground_colour draws all rock.
+fn piece_ground(in: CorridorOut, su: vec2f, d: mat2x3f, n: vec4f, wall: f32) -> vec3f {
+    let level = lod(su);
+    let edge = select(abs(in.road.x) - in.road.y, in.road.x, (in.word & MAT_BITS) == MAT_GROUND);
+    let g = model_reach(level, length(in.relative.xy)) * ground_terms(moved_at(su, u32(ceil(level))), edge, in.road.y);
+    return ground_colour(su, in.relative, d, in.altitude, u32(ceil(level)), in.clip.xy, Road(vec3f(0.0), 0.0, 0.0, max(g.x, wall), g.y, g.z), n);
+}
+
+// The face beside a piece's wall at a point of the wall, on the side `out` (a unit vector of LOD space from the wall
+// into it): x its rise per metre from one to three texels from the wall, of the finest level up to `top` that knows both
+// points, and y the metres that the heights moved it WALL_MOVED_M out, from the masks of `level`. A nearer texel would
+// hold the wall's own step; over two texels the read passes the round at the face's foot (`round_m`, 0.5 m).
+fn side_read(s: vec2f, out: vec2f, top: u32, level: u32) -> vec2f {
+    for (var k = top; k >= COARSEST; k--) {
+        let t = f32(1 << (22u - k)) * surface.unit;
+        let a = bilinear_rise(k, texel_of(s + t * out, k)).x;
+        let b = bilinear_rise(k, texel_of(s + 3.0 * t * out, k)).x;
+        if (known(a) && known(b)) {
+            return vec2f((b - a) / (2.0 * t), moved_at(s + WALL_MOVED_M * out, level));
+        }
+    }
+    return vec2f(0.0);
+}
+
+// A wall reads how far the heights moved its face this far out, in metres so that levels 17 and 18 read the same ground.
+const WALL_MOVED_M: f32 = 1.0;
+
+// A wall reads its face at knots this far apart along the world axis nearer to the wall, and between two knots its rock
+// share and its light run linearly: they change along a wall over metres, never at each bump of the ground or at each
+// edge of a cut face, and the knots stay where they are as the eye moves. (Three reads a knot gave the same walls and
+// cost 0.12 to 0.18 ms more on the portal flights.)
+const WALL_KNOT_M: f32 = 8.0;
+
+// What a wall needs of its face that rock_share does not read from the wall's own ground: the wall's ground `g`, the z
+// of its coarse normal, the reach of the one road model there and the half-width of its word.
+struct WallGround {
+    g: Ground,
+    coarse_z: f32,
+    reach: f32,
+    half: f32,
+}
+
+// The face beside a piece's wall at `s` (`world` its world metres), on the side `out`, `along` the wall's direction: x
+// the rock share that rock_share gives it and y its rise per metre, from the knots about it on the world axis nearer to
+// the wall (y, x, or both cross-faded within about 6° of 45°, as the masonry's).
+fn wall_side(s: vec2f, world: vec2f, out: vec2f, along: vec2f, top: u32, level: u32, w: WallGround) -> vec2f {
+    let north = smoothstep(-0.1, 0.1, (abs(along.y) - abs(along.x)) / (abs(along.x) + abs(along.y) + 1e-6));
+    var face = vec2f(0.0);
+    if (north < 1.0) {
+        face = knot_face(s, world.x, along.x, out, along, top, level, w);
+    }
+    if (north > 0.0) {
+        face = mix(face, knot_face(s, world.y, along.y, out, along, top, level, w), north);
+    }
+    return face;
+}
+
+// wall_side between the two knots about `u` (the world axis's metres at s), `du` the axis's share of `along`: the rock
+// share of each knot from its own read, blended linearly, so the share changes over metres whatever thresholds lie in
+// rock_share; and the rise, blended alike.
+fn knot_face(s: vec2f, u: f32, du: f32, out: vec2f, along: vec2f, top: u32, level: u32, w: WallGround) -> vec2f {
+    let u0 = floor(u / WALL_KNOT_M) * WALL_KNOT_M;
+    let step = along / select(du, 1e-3, abs(du) < 1e-3);
+    let a = side_read(s + (u0 - u) * step, out, top, level);
+    let b = side_read(s + (u0 + WALL_KNOT_M - u) * step, out, top, level);
+    let f = (u - u0) / WALL_KNOT_M;
+    return vec2f(mix(knot_rock(a, out, w), knot_rock(b, out, w), f), mix(a.x, b.x, f));
+}
+
+// The rock share of a knot's read (side_read) as rock_share.
+fn knot_rock(read: vec2f, out: vec2f, w: WallGround) -> f32 {
+    let z = render_normal(normalize(vec3f(-read.x * out, 1.0))).z;
+    return rock_share(w.g, z, w.coarse_z, w.reach * ground_terms(read.y, 0.0, w.half).y);
+}
+
+// A piece's wall continues the face beside it away from its road: below a wall that holds its road up, above a wall
+// that its road cuts. It stands as rock where rock_share draws that face partly as rock, so a vertical face beside rock
+// holds no soil and no wall is half of masonry. The share is taken at each knot from that knot's own read (the moved
+// ground WALL_MOVED_M out) and blended between the knots, so it changes along a wall only over metres. A rock wall is
+// lit by that face's normal. Under trees and between the legs of a hairpin a wall stays masonry. Only on steep land:
+// elsewhere the wall reads one texel of the coarse relief.
+struct WallRock {
+    share: f32,
+    face: vec3f,
+}
+
+fn wall_rock(in: CorridorOut, su: vec2f) -> WallRock {
+    var out = WallRock(0.0, vec3f(0.0, 0.0, 1.0));
+    let lambda = lod(su);
+    let level = u32(ceil(lambda));
+    let coarse_z = coarse_z_at(level, su);
+    if (coarse_steep_of(coarse_z) <= 0.0) {
+        return out;
+    }
+    let top = min(surface.finest, 18u);
+    let lower = normalize(in.normal.xy + vec2f(1e-9, 0.0));
+    let side = select(-lower, lower, (in.word & WALL_FILL) != 0u);
+    let world = look.place.xy + in.relative.xy;
+    let w = WallGround(ground_at(level, su, world, 1e9), coarse_z, model_reach(lambda, length(in.relative.xy)), in.road.y);
+    let face = wall_side(su, world, side, vec2f(-lower.y, lower.x), top, level, w);
+    out.face = normalize(vec3f(-face.y * side, 1.0));
+    out.share = smoothstep(0.1, 0.4, face.x);
+    return out;
 }
 
 @fragment
-fn corridor_fragment(in: CorridorOut) -> @location(0) vec4f {
-    if (paint_draws(length(in.relative.xy), in.clip.xy)) {
+fn corridor_fragment(raw: CorridorOut) -> @location(0) vec4f {
+    var in = raw;
+    if (MOUTH) {
+        in = corridor_in(raw);
+    }
+    if (!PIECE && paint_draws(length(in.relative.xy), in.clip.xy)) {
         discard;
     }
+    // Whole two level-17 cells past where the terrain sinks (level 18's morph start), as far as its sunk
+    // corners' triangles reach and the terrain takes no snap (PLAN_TRIANGLE_UNITS of cells.wgsl); gone
+    // where level 18 ends. In metres, so the same at the finest level 17.
+    if (PIECE && CUT) {
+        let sink = surface.range * exp2(-18.0 - MORPH);
+        let d = length(vec3f(lod_space(in.u), surface.above));
+        if (dither(in.clip.xy + DETAIL_DITHER) >= 1.0 - smoothstep(sink + 256.0 * surface.unit, surface.range * exp2(-18.0), d)) {
+            discard;
+        }
+    }
     let mat = in.word & MAT_BITS;
-    if (mat >= LOOK_TREAD && mat <= LOOK_LOG && dither(in.clip.xy + DETAIL_DITHER) < detail_fade(length(in.relative.xy))) {
+    DETAIL_EVERYWHERE = PIECE && (in.word & STOREY_TOP) != 0u;
+    if (!PIECE && mat >= LOOK_TREAD && mat <= LOOK_LOG && dither(in.clip.xy + DETAIL_DITHER) < detail_fade(length(in.relative.xy))) {
         discard;
     }
     let su = lod_space(in.u);
     let d = mat2x3f(dpdx(in.relative), dpdy(in.relative));
+    // The owned view: a piece in green.
+    if (PIECE && frame.debug == OWNED_VIEW) {
+        return vec4f(0.0, 0.5, 0.0, 1.0);
+    }
+    // The crack view: a piece in grey, as the terrain.
+    if (PIECE && frame.debug == 3u) {
+        return vec4f(vec3f(0.25 + 0.5 * (max(dot(render_normal(select(normalize(in.normal), drawn_normal(su), (in.word & MAT_BITS) == MAT_GROUND)), frame.sun.xyz), 0.0) * frame.sun.w + 0.3) / 1.3), 1.0);
+    }
+    if (PIECE && (in.word & (MAT_BITS | CULVERT_DARK)) == (MAT_CAP | CULVERT_DARK)) {
+        return vec4f(atmosphere(CULVERT_INSIDE, in.relative, in.altitude), 1.0);
+    }
     if (mat == MAT_GROUND) {
         return vec4f(corridor_ground(in, su, d), 1.0);
     }
+    // The fall of a piece's water is the slope of its surface, which is level across its line: a step's
+    // slot stands upright, so it foams.
+    if (PIECE && mat == MAT_WATER) {
+        let wn = normalize(in.normal);
+        let fall = length(wn.xy) / max(wn.z, 1e-3);
+        return vec4f(atmosphere(water_look(in.relative, su, fall, false, frame.pixel, frame.curvature), in.relative, in.altitude), 1.0);
+    }
+    // A piece's wall in a cliff is a rock cut (wall_rock).
+    var rock = WallRock(0.0, vec3f(0.0, 0.0, 1.0));
+    if (PIECE && mat == MAT_WALL) {
+        rock = wall_rock(in, su);
+        if (rock.share >= 1.0) {
+            return vec4f(piece_ground(in, su, d, vec4f(rock.face, 0.0), 1.0), 1.0);
+        }
+    }
     var n = normalize(cross(d[0], d[1]));
     n *= -sign(dot(n, in.relative));
+    if (PIECE) {
+        n = render_normal(normalize(in.normal));
+    }
     let p = look.place.xy + in.relative.xy;
     let pw = max(length(d[0]), length(d[1])) * look.screen.z;
     let cw = max(length(vec2f(dpdx(in.road.x), dpdy(in.road.x))), 1e-4);
     let aw = max(length(vec2f(dpdx(in.along), dpdy(in.along))), 1e-4);
-    let way = WayPixel(p, in.road.x, in.road.y, in.along, pw, cw, aw);
+    // A piece's carriageway keeps its pixels within the half-width (PIECE_INSIDE of plan/corners.wgsl). A pixel past
+    // it lies where the face goes on past its frame's edge, as in a junction's mouth: that edge opens there.
+    let past = PIECE && ((in.word >> PRIO_SHIFT) & 1u) == 1u && abs(in.road.x) > in.road.y;
+    let across = select(in.road.x, clamp(in.road.x, -in.road.y, in.road.y), past);
+    // A face edge between two paved faces, as a way's toward a junction's mouth, lies inside the paved area: a piece
+    // draws its edge only where the frame's edge is the paved outline's, which the far look draws too (the paint).
+    var open = 0.0;
+    let inside = in.road.y - abs(in.road.x);
+    if (PIECE && inside < EDGE_LOOK_M) {
+        open = smoothstep(OPEN_FROM_M, OPEN_TO_M, -paved_edge(su, u32(ceil(lod(su)))) - inside);
+    }
+    let way = WayPixel(p, across, in.road.y, in.along, pw, cw, aw, open);
     let code = (in.word >> CODE_SHIFT) & 15u;
-    let l = way_look(mat, code, region_at(su), su, way, (in.word >> FLAGS_SHIFT) & FLAGS_BITS, n.z, in.altitude);
+    let flags = ((in.word >> FLAGS_SHIFT) & FLAGS_BITS) | select(0u, CF_NO_LEFT_LINE | CF_NO_RIGHT_LINE, past);
+    let l = way_look(mat, code, region_at(su), su, way, flags, n.z, in.altitude, PIECE);
+    if (PIECE && l.ground >= 1.0) {
+        return vec4f(corridor_ground(in, su, d), 1.0);
+    }
     if (l.ground >= 1.0) {
         discard;
     }
@@ -241,5 +439,8 @@ fn corridor_fragment(in: CorridorOut) -> @location(0) vec4f {
     if (mat == LOOK_LOG) {
         return vec4f(log_lit(l, n, su, in.relative, in.altitude), 1.0);
     }
+    if (rock.share > 0.0) {
+        return vec4f(mix(way_lit(l, n, su, in.relative, in.altitude), piece_ground(in, su, d, vec4f(rock.face, 0.0), 1.0), rock.share), 1.0);
+    }
     return vec4f(way_lit(l, n, su, in.relative, in.altitude), 1.0);
 }
diff --git a/builder/web/src/lib/trailview/roads/decks.ts b/builder/web/src/lib/trailview/roads/decks.ts
index 807def7b1a..4b29eb0a1f 100644
--- a/builder/web/src/lib/trailview/roads/decks.ts
+++ b/builder/web/src/lib/trailview/roads/decks.ts
@@ -107,18 +107,32 @@ const frameOf = (list: Station[]) => (x: number, y: number): [number, number] =>
 
 const pointKey = (line: Line, v: number) => `${line.xy[2 * v]},${line.xy[2 * v + 1]}`;
 
-/** Given a bridge line of `total` metres, the metres from its start where its deck starts and ends: short of an end that leaves a road or a deck at a T. */
+const tees = new WeakMap [number, number]>();
+
+/**
+ * Given a bridge line of `total` metres, the metres from its start where its deck starts and ends: short of an end that
+ * leaves a road or a deck at a T. Made once for a tile's lines.
+ */
 export function teesOf(all: Line[]): (line: Line, total: number) => [number, number] {
-    // The inner vertices of the roads on the ground and of the decks, with the half-width that a deck leaving them starts past.
+    const known = tees.get(all);
+    if (known) return known;
+    // The bridges' ends, with the widest half-width of a road on the ground or a deck that runs through them: a deck
+    // leaving there starts past it. The map stays with the tile, so it holds only the keys that `made` reads.
     const through = new Map();
+    for (const line of all) if (line.kind === BRIDGE) for (const v of [0, line.z.length - 1]) through.set(pointKey(line, v), 0);
     for (const line of all) {
         const half = line.kind === BRIDGE ? deckHalf(line) : line.kind === ROAD || line.kind === PATH ? line.h : 0;
-        for (let v = 1; half && v + 1 < line.z.length; v++) through.set(pointKey(line, v), Math.max(through.get(pointKey(line, v)) ?? 0, half));
+        for (let v = 1; half && v + 1 < line.z.length; v++) {
+            const most = through.get(pointKey(line, v));
+            if (most !== undefined) through.set(pointKey(line, v), Math.max(most, half));
+        }
     }
-    return (line, total) => {
+    const made = (line: Line, total: number): [number, number] => {
         const cuts = [through.get(pointKey(line, 0)) ?? 0, through.get(pointKey(line, line.z.length - 1)) ?? 0];
         return cuts[0] + cuts[1] < TEE_SHARE * total ? [cuts[0], total - cuts[1]] : [0, total];
     };
+    tees.set(all, made);
+    return made;
 }
 
 /** The decks wider than `line` that it may run on: not those that it runs on into at a joint, and only those whose road comes within its box. */
diff --git a/builder/web/src/lib/trailview/roads/details.wgsl b/builder/web/src/lib/trailview/roads/details.wgsl
index 6964643c75..3ccaf12f62 100644
--- a/builder/web/src/lib/trailview/roads/details.wgsl
+++ b/builder/web/src/lib/trailview/roads/details.wgsl
@@ -12,6 +12,18 @@ const MAT_DELI_BAND: u32 = 45u;
 const MAT_REFLECTOR: u32 = 46u;
 const MAT_WALL: u32 = 48u;
 const MAT_CAP: u32 = 49u;
+// A storey's shell of dark timber or of steel, a deck's top of planks across it and a railing of wood (plan/piece.wgsl):
+// the colours of the decks of structures/bridges.ts, squared as structures.wgsl squares them.
+const MAT_TIMBER: u32 = 51u;
+const MAT_STEEL: u32 = 52u;
+const MAT_PLANKS: u32 = 53u;
+const MAT_WOOD: u32 = 54u;
+const TIMBER: vec3f = vec3f(0.133, 0.071, 0.035);
+const STEEL: vec3f = vec3f(0.084, 0.091, 0.098);
+const PLANK: vec3f = vec3f(0.24, 0.13, 0.057);
+// A plank's width along the deck, and the share of it that the gap to the next one takes.
+const PLANK_M: f32 = 0.2;
+const PLANK_GAP: f32 = 0.06;
 // A stone of a wall: its cell along and up. Stones lie flat.
 const STONE_LONG_M: f32 = 0.267;
 const STONE_HIGH_M: f32 = 0.125;
@@ -106,6 +118,24 @@ fn detail_look(mat: u32, su: vec2f, w: WayPixel, altitude: f32) -> WayLook {
         case MAT_REFLECTOR: {
             out.albedo = vec3f(1.0, 0.47, 0.06);
         }
+        case MAT_TIMBER: {
+            out.albedo = TIMBER * (0.85 + 0.3 * noise(p / 0.4));
+        }
+        case MAT_WOOD: {
+            out.albedo = PLANK * (0.9 + 0.2 * noise(p / 0.4));
+        }
+        case MAT_STEEL: {
+            out.albedo = STEEL;
+            out.spec = 0.3;
+        }
+        case MAT_PLANKS: {
+            // Each plank its own tone; the gaps fade into the mean tone once a pixel spans a plank.
+            let n = w.along / PLANK_M;
+            let gap = 1.0 - smoothstep(PLANK_GAP - w.aw / PLANK_M, PLANK_GAP + w.aw / PLANK_M, fract(n));
+            let tone = 0.85 + 0.3 * hash(vec2f(floor(n), 0.0));
+            let shown = 1.0 - smoothstep(0.3, 1.0, w.aw / PLANK_M);
+            out.albedo = PLANK * mix(1.0, tone * (1.0 - 0.6 * gap), shown) * (0.9 + 0.2 * noise(p / 0.5));
+        }
         default: {
             // The local rock's brightness and a hint of its hue.
             let cell = cell_at(su, u32(ceil(lod(su))));
diff --git a/builder/web/src/lib/trailview/roads/lamps.ts b/builder/web/src/lib/trailview/roads/lamps.ts
index d938b977a8..4265820242 100644
--- a/builder/web/src/lib/trailview/roads/lamps.ts
+++ b/builder/web/src/lib/trailview/roads/lamps.ts
@@ -1,7 +1,7 @@
 // Street lamps from the stations of a lit road: where the corridor draws its sidewalk or behind its shoulder.
-import { BRIDGE, cores, insideRings, junctions, metresPerUnit, PATH, ringsDistance, ROAD, TUNNEL, walkOf, type Line } from '../terrain/bins';
+import { BRIDGE, cores, insideRings, isCore, junctions, linesNear, metresPerUnit, PATH, ringsDistance, ROAD, TUNNEL, walkOf, type Line, type Shapes } from '../terrain/bins';
 import { halfAt, partnersOf } from '../terrain/corners';
-import { along, BUILT_M, builtNear, LEFT, near, RIGHT, townOf, type Town } from '../terrain/town';
+import { add, along, BUILT_M, builtNear, gridOf, LEFT, near, RIGHT, townOf, type Grid, type Town } from '../terrain/town';
 import { LANTERN, streetLamp } from '../models/amenities';
 import { unitModel, type Build, type Kind, type Placement } from '../kinds/kind';
 import { classOf, shoulderOf } from './section';
@@ -29,18 +29,35 @@ export const lampKind: Kind = {
 };
 
 /** The lamps of each tile, made once: the stations of its lit roads are many, its lamps few. */
-const planned = new WeakMap();
+const planned = new WeakMap();
 
-/** What decides the place of a lamp. */
-interface Places { out: Pick; town: Town; ways: Line[]; mouths: { x: number; y: number; h: number }[]; lamps: Placement[] }
+/** Points in a grid, in their order: a point that comes later takes its place with `add`. */
+interface Spots { points: T[]; grid: Grid }
+
+const spotsOf = (points: T[]): Spots => ({ points, grid: gridOf(points.map(({ x, y }) => [x, y, x, y])) });
+
+/** Whether `hit` holds for a point that lies within `metres` of world point x, y: `hit` takes no point farther off. */
+function within({ points, grid }: Spots, x: number, y: number, metres: number, unit: number, hit: (point: T) => boolean): boolean {
+    let found = false;
+    // One unit more for the rounding of a distance.
+    near(grid, x, y, x, y, metres / unit + 1, k => (found ||= hit(points[k])));
+    return found;
+}
+
+/**
+ * What decides the place of a lamp: the tile's shapes, the widest half-width of its carriageways (`half`), its junctions
+ * and the ends of its decks and bores with the widest among them (`wide`), and the lamps that stand.
+ */
+interface Places { out: Pick; town: Town; half: number; mouths: Spots<{ x: number; y: number; h: number }>; wide: number; lamps: Spots }
 
 /** Whether a point lies within OFF_ROAD_M of a carriageway other than `own`. */
-function inTraffic(ways: Line[], own: Line, x: number, y: number, unit: number): boolean {
-    return ways.some(line => {
-        if (line === own) return false;
-        const reach = (line.h + OFF_ROAD_M) / unit;
+function inTraffic(shapes: Shapes, half: number, own: Line, x: number, y: number, unit: number): boolean {
+    return linesNear(shapes, x, y, (half + OFF_ROAD_M) / unit).some(k => {
+        const line = shapes.lines[k];
+        if (line === own || !isCore(line)) return false;
+        const reach = (line.h + OFF_ROAD_M) / unit, { xy } = line;
         for (let v = 0; v + 1 < line.z.length; v++) {
-            const [ax, ay, bx, by] = line.xy.slice(2 * v, 2 * v + 4);
+            const ax = xy[2 * v], ay = xy[2 * v + 1], bx = xy[2 * v + 2], by = xy[2 * v + 3];
             if (Math.min(ax, bx) > x + reach || Math.max(ax, bx) < x - reach || Math.min(ay, by) > y + reach || Math.max(ay, by) < y - reach) continue;
             const t = along(ax, ay, bx, by, x, y);
             if (Math.hypot(ax + t * (bx - ax) - x, ay + t * (by - ay) - y) < reach) return true;
@@ -50,12 +67,13 @@ function inTraffic(ways: Line[], own: Line, x: number, y: number, unit: number):
 }
 
 /** Whether a lamp may stand at world point x, y beside `line`, whose sidewalk is `walk` metres wide. */
-function free({ out, town, ways, mouths, lamps }: Places, line: Line, walk: number, x: number, y: number, unit: number): boolean {
-    if (out.cornered(x, y) || mouths.some(j => Math.hypot(j.x - x, j.y - y) * unit < j.h + walk + MOUTH_M)) return false;
-    if (lamps.some(lamp => Math.hypot(lamp.x - x, lamp.y - y) * unit < APART_M)) return false;
-    if (inTraffic(ways, line, x, y, unit)) return false;
+function free({ out, town, half, mouths, wide, lamps }: Places, line: Line, walk: number, x: number, y: number, unit: number): boolean {
+    if (out.cornered(x, y) || within(mouths, x, y, wide + walk + MOUTH_M, unit, j => Math.hypot(j.x - x, j.y - y) * unit < j.h + walk + MOUTH_M)) return false;
+    if (within(lamps, x, y, APART_M, unit, lamp => Math.hypot(lamp.x - x, lamp.y - y) * unit < APART_M)) return false;
+    if (inTraffic(out.shapes, half, line, x, y, unit)) return false;
+    const { buildings } = out.shapes;
     let walled = false;
-    near(town, x, y, x, y, CLEAR_M / unit, b => (walled ||= insideRings(out.buildings[b].rings, x, y) || ringsDistance(out.buildings[b].rings, x, y) * unit < CLEAR_M));
+    near(town, x, y, x, y, CLEAR_M / unit, b => (walled ||= insideRings(buildings[b].rings, x, y) || ringsDistance(buildings[b].rings, x, y) * unit < CLEAR_M));
     return !walled;
 }
 
@@ -74,12 +92,14 @@ function spot(places: Places, line: Line, st: Station[], metres: number): Placem
 }
 
 /** The lamps of a tile's lit roads. */
-function lampsOf(out: Pick, lines: Line[]): Placement[] {
+function lampsOf(out: Pick): Placement[] {
+    const { lines, buildings } = out.shapes;
     const partners = partnersOf(lines), ways = cores(lines), roads = lines.filter(line => line.kind === ROAD && !line.gallery && LIT.has(classOf(line)) && line.z.length > 1);
     // A road can run straight into a bridge or a tunnel, a node of two ways: each end of one is a mouth.
     const ends = lines.filter(({ kind }) => kind === BRIDGE || kind === TUNNEL).flatMap(({ xy, h }) => [{ x: xy[0], y: xy[1], h }, { x: xy[xy.length - 2], y: xy[xy.length - 1], h }]);
-    const joins = [...junctions([...ways, ...lines.filter(({ kind }) => kind === PATH)]).values()].filter(j => j.ways > 2), lamps: Placement[] = [];
-    const places = { out, town: townOf(out.buildings), ways, mouths: [...joins, ...ends], lamps };
+    const joins = [...junctions([...ways, ...lines.filter(({ kind }) => kind === PATH)]).values()].filter(j => j.ways > 2), mouths = [...joins, ...ends], lamps: Placement[] = [];
+    const widest = (list: { h: number }[]) => list.reduce((most, { h }) => Math.max(most, h), 0);
+    const places: Places = { out, town: townOf(buildings), half: widest(ways), mouths: spotsOf(mouths), wide: widest(mouths), lamps: spotsOf(lamps) };
     for (const line of roads) {
         const st = stationsOf(line, v => halfAt(line, v, partners)), total = st[st.length - 1].along;
         for (let metres = SPACING_M / 2; metres < total; ) {
@@ -89,6 +109,7 @@ function lampsOf(out: Pick, lines: Line[]): Pla
                     placed = spot(places, line, st, m);
                     if (placed) {
                         lamps.push(placed);
+                        add(places.lamps.grid, [placed.x, placed.y, placed.x, placed.y]);
                         metres = m;
                         break;
                     }
@@ -100,8 +121,8 @@ function lampsOf(out: Pick, lines: Line[]): Pla
     return lamps;
 }
 
-/** Stands the lamps of a tile that a node owns. `lines` are the tile's. */
-export function streetLamps(out: Pick, lines: Line[]): void {
-    const lamps = planned.get(lines) ?? planned.set(lines, lampsOf(out, lines)).get(lines)!;
+/** Stands the lamps of a tile that a node owns. */
+export function streetLamps(out: Pick): void {
+    const lamps = planned.get(out.shapes) ?? planned.set(out.shapes, lampsOf(out)).get(out.shapes)!;
     for (const lamp of lamps) if (out.owns(lamp.x, lamp.y)) out.place(lamp);
 }
diff --git a/builder/web/src/lib/trailview/roads/look-codes.wgsl b/builder/web/src/lib/trailview/roads/look-codes.wgsl
new file mode 100644
index 0000000000..d678d24492
--- /dev/null
+++ b/builder/web/src/lib/trailview/roads/look-codes.wgsl
@@ -0,0 +1,26 @@
+// The looks of a way's top, as LOOK of section.ts, a look word's half-width field, as piece.ts, and the materials of
+// a top: the corridors (looks.wgsl), the pieces of the ground plan (plan/line-look.wgsl) and the terrain's paint
+// (ground/roads.wgsl) read them.
+
+const LOOK_ASPHALT: u32 = 20u;
+const LOOK_MAIN: u32 = 21u;
+const LOOK_MOTORWAY: u32 = 22u;
+const LOOK_CONCRETE: u32 = 23u;
+const LOOK_SETT: u32 = 24u;
+const LOOK_PAVERS: u32 = 25u;
+const LOOK_GRAVEL: u32 = 26u;
+const LOOK_DIRT: u32 = 27u;
+const LOOK_TRAIL: u32 = 28u;
+const LOOK_BALLAST: u32 = 29u;
+const LOOK_STRIPS: u32 = 30u;
+const HALF_STEP_M: f32 = 0.025;
+// As sections::Material.
+const MATERIAL_SETT: u32 = 1u;
+const MATERIAL_PAVERS: u32 = 2u;
+const MATERIAL_CONCRETE: u32 = 3u;
+const MATERIAL_STRIPS: u32 = 4u;
+
+// A piece's look word: the look, the drawn code and the half-width.
+fn look_word(mat: u32, code: u32, half: f32) -> u32 {
+    return mat | (code << 7u) | (min(511u, u32(round(max(half, 0.0) / HALF_STEP_M))) << 19u);
+}
diff --git a/builder/web/src/lib/trailview/roads/looks.wgsl b/builder/web/src/lib/trailview/roads/looks.wgsl
index b914c00da2..4cd65b2af7 100644
--- a/builder/web/src/lib/trailview/roads/looks.wgsl
+++ b/builder/web/src/lib/trailview/roads/looks.wgsl
@@ -7,20 +7,11 @@
 // #include ../ground/look.wgsl
 // #include track-looks.wgsl
 // #include details.wgsl
+// #include look-codes.wgsl
 
-// As MAT and LOOK of section.ts.
+// As MAT of section.ts.
 const MAT_KERB: u32 = 2u;
 const MAT_SIDEWALK: u32 = 3u;
-const LOOK_ASPHALT: u32 = 20u;
-const LOOK_MOTORWAY: u32 = 22u;
-const LOOK_CONCRETE: u32 = 23u;
-const LOOK_SETT: u32 = 24u;
-const LOOK_PAVERS: u32 = 25u;
-const LOOK_GRAVEL: u32 = 26u;
-const LOOK_DIRT: u32 = 27u;
-const LOOK_TRAIL: u32 = 28u;
-const LOOK_BALLAST: u32 = 29u;
-const LOOK_STRIPS: u32 = 30u;
 // As CF of section.ts.
 const CF_NO_LEFT_LINE: u32 = 8u;
 const CF_NO_RIGHT_LINE: u32 = 16u;
@@ -82,6 +73,8 @@ struct WayPixel {
     pw: f32,
     cw: f32,
     aw: f32,
+    // The share by which its edge opens whatever its flags: a piece's, where its face goes on past its frame's edge.
+    open: f32,
 }
 
 fn surface_colour(region: u32, code: u32) -> vec3f {
@@ -128,17 +121,18 @@ fn asphalt(code: u32, region: u32, p: vec2f, pw: f32) -> vec3f {
     return base * asphalt_grain(p, pw);
 }
 
-// Whether a pixel lies on a side of its way that opens into a junction's faces: `flags` are the face's (CF of
-// section.ts). That edge has no line, and it does not fray.
-fn opens(w: WayPixel, flags: u32) -> bool {
-    return (w.across > 0.0 && (flags & CF_NO_LEFT_LINE) != 0u) || (w.across < 0.0 && (flags & CF_NO_RIGHT_LINE) != 0u);
+// The share by which a pixel's edge opens: on a side of its way that opens into a junction's faces (`flags` are the
+// face's, CF of section.ts), or by the pixel's own share. An open edge has no line, and it does not fray.
+fn opens(w: WayPixel, flags: u32) -> f32 {
+    let side = (w.across > 0.0 && (flags & CF_NO_LEFT_LINE) != 0u) || (w.across < 0.0 && (flags & CF_NO_RIGHT_LINE) != 0u);
+    return select(w.open, 1.0, side);
 }
 
 // The lines of a way, by class: `mat` LOOK_MAIN or LOOK_MOTORWAY, `oneway` without a middle line.
 fn markings(mat: u32, oneway: bool, region: u32, w: WayPixel, flags: u32) -> f32 {
     let inside = w.half - abs(w.across);
     let dash = rule(region, slot_dashes());
-    let edge = select(1.0, 0.0, opens(w, flags));
+    let edge = 1.0 - opens(w, flags);
     var m = 0.0;
     if (mat == LOOK_MOTORWAY) {
         m = band(inside, 0.25, 0.45, w.cw) * edge;
@@ -197,8 +191,8 @@ fn paved_look(mat: u32, code: u32, region: u32, w: WayPixel, flags: u32) -> WayL
     }
     out.albedo = c;
     // A narrow way without a shoulder: grass creeps over its edges.
-    if (w.half < 2.0 && !opens(w, flags)) {
-        out.ground = 1.0 - smoothstep(0.0, 0.1, edge + 0.08 * (noise(p / 0.3) - 0.5) + 0.04 * seen(0.07, w.pw) * (noise(p / 0.07) - 0.5));
+    if (w.half < 2.0) {
+        out.ground = (1.0 - opens(w, flags)) * (1.0 - smoothstep(0.0, 0.1, edge + 0.08 * (noise(p / 0.3) - 0.5) + 0.04 * seen(0.07, w.pw) * (noise(p / 0.07) - 0.5)));
     }
     return out;
 }
@@ -208,8 +202,9 @@ fn paint_wear(p: vec2f) -> f32 {
     return 0.82 + 0.18 * noise(p / 0.7);
 }
 
-// A zebra over its road's own surface: `across` is metres off the straight line through its crossing node.
-fn zebra_look(mat: u32, code: u32, region: u32, w: WayPixel) -> WayLook {
+// A zebra over its road's own surface: `across` is metres off the straight line through its crossing node; `piece` on
+// a mesh of the ground plan.
+fn zebra_look(mat: u32, code: u32, region: u32, w: WayPixel, piece: bool) -> WayLook {
     var out = WayLook(vec3f(0.0), vec2f(0.0), 0.0, 0.0, 0.0);
     switch mat {
         case LOOK_ZEBRA_SETT: {
@@ -219,7 +214,11 @@ fn zebra_look(mat: u32, code: u32, region: u32, w: WayPixel) -> WayLook {
             out = pavers_look(region, w);
         }
         case LOOK_ZEBRA_CONCRETE: {
-            out = concrete_look(code, region, w, false);
+            if (piece) {
+                out = concrete_look(code, region, w, false, false);
+            } else {
+                out = corridor_concrete_look(code, region, w, false);
+            }
         }
         default: {
             out.albedo = asphalt(code, region, w.p, w.pw);
@@ -244,13 +243,45 @@ fn give_way_look(code: u32, region: u32, w: WayPixel) -> WayLook {
     return WayLook(c, vec2f(0.0), 0.0, 0.0, 0.0);
 }
 
-// Concrete: slabs 5 m long with sealed joints; on a narrow track two strips on the way's asphalt.
-fn concrete_look(code: u32, region: u32, w: WayPixel, track: bool) -> WayLook {
+// A lane's width, by which a concrete way counts its lanes for the tyre tracks.
+const CONCRETE_LANE_M: f32 = 4.0;
+
+// Concrete: one pale grey with fine grain and faint tyre tracks; on a narrow track two strips on the way's asphalt.
+// Its tone is a function of the place, so the faces of a junction show one surface; only the tracks read the frame,
+// `framed` where `across` is the lanes of a road, not a zebra's or a path's. Every detail but the tracks has a mean of
+// 1, so the far paint keeps about the slot's colour.
+fn concrete_look(code: u32, region: u32, w: WayPixel, track: bool, framed: bool) -> WayLook {
+    var out = WayLook(vec3f(0.0), vec2f(0.0), 0.0, 0.0, 0.0);
+    let p = w.p;
+    // The tracks fade where the frame runs faster than the world, as in a triangle between two arms' frames in a
+    // junction. The rate is constant over a triangle, thus a track can end on a triangle's edge in a junction face.
+    let frame = select(0.0, 1.0 - smoothstep(2.5, 5.0, max(w.aw, w.cw) * look.screen.z / max(w.pw, 1e-5)), framed);
+    var c = rule(region, slot_concrete()).rgb * concrete_tone(p);
+    // Cement paste and aggregate: mottled at a few cm, grains at 1 cm, each its mean once a pixel spans it.
+    c *= 1.0 + 0.05 * seen(0.15, w.pw) * (noise(p / 0.07 + 5.0) - 0.5) + 0.1 * seen(0.03, w.pw) * (noise(p / 0.011) - 0.5);
+    c *= 1.0 + seen(0.02, w.pw) * (0.25 * step(0.93, hash(floor(p / 0.009))) - 0.0175);
+    // Worn tyre tracks, soft bands about 1 m wide 0.8 m each side of a lane's middle, faint and darker in long patches.
+    let lanes = max(1.0, round(2.0 * w.half / CONCRETE_LANE_M));
+    let lane = 2.0 * w.half / lanes;
+    let u = (fract((w.across + w.half) / lane) - 0.5) * lane;
+    let tyre = smoothstep(0.55, 0.05, abs(abs(u) - 0.8));
+    c *= 1.0 - 0.028 * frame * tyre * (0.6 + 0.8 * noise(p / 7.0 + 3.0));
+    out.albedo = c;
+    if (track && w.half <= STRIPS_HALF_M) {
+        // 0.55 m wide, their middles 0.75 m out.
+        out.albedo = mix(asphalt(code, region, p, w.pw), out.albedo, on_strips(w.across, w.cw));
+    }
+    return out;
+}
+
+// The corridors' concrete: slabs 5 m long with sealed joints and a tone of its own; on a narrow track two strips on the
+// way's asphalt. It keeps the default path as it is and goes with the corridors.
+fn corridor_concrete_look(code: u32, region: u32, w: WayPixel, track: bool) -> WayLook {
     var out = WayLook(vec3f(0.0), vec2f(0.0), 0.0, 0.0, 0.0);
     let p = w.p;
     let across = w.across;
     let along = w.along;
-    let wide = w.half > 2.2;
+    let wide = w.half > STRIPS_HALF_M;
     let slab = vec2f(floor(along / 5.0), select(0.0, sign(across), wide));
     var c = rule(region, slot_concrete()).rgb * (0.95 + 0.1 * hash(slab)) * (0.95 + 0.1 * noise(p / 3.0));
     // Brushed across, fine.
@@ -265,7 +296,7 @@ fn concrete_look(code: u32, region: u32, w: WayPixel, track: bool) -> WayLook {
     out.albedo = c;
     if (track && !wide) {
         // 0.55 m wide, their middles 0.75 m out.
-        out.albedo = mix(asphalt(code, region, p, w.pw), out.albedo * (0.95 + 0.1 * smoothstep(0.2, 0.0, abs(abs(across) - 0.75))), band(abs(across), 0.48, 1.03, w.cw));
+        out.albedo = mix(asphalt(code, region, p, w.pw), out.albedo * (0.95 + 0.1 * smoothstep(0.2, 0.0, abs(abs(across) - 0.75))), on_strips(across, w.cw));
     }
     return out;
 }
@@ -300,7 +331,7 @@ fn pavers_look(region: u32, w: WayPixel) -> WayLook {
     let edge = min(0.5 - abs(local.x), (0.5 - abs(local.y)) * 0.5);
     let bevel = smoothstep(0.0, 0.035, edge);
     let tone = base * (0.86 + 0.24 * hash(cell)) * mix(vec3f(1.0), vec3f(1.05, 1.0, 0.92), step(0.7, hash(cell + 2.0)));
-    out.albedo = base * (0.97 + 0.06 * noise(p / 4.0));
+    out.albedo = base * pavers_tone(p);
     out.albedo = mix(out.albedo, tone * mix(0.45, 1.0, bevel) * (1.0 + 0.1 * (noise(p / 0.02) - 0.5)), s);
     out.bump = s * (1.0 - bevel) * 0.6 * sign(local) * vec2f(step(abs(local.y) * 0.5, abs(local.x) - 0.25), step(abs(local.x) - 0.25, abs(local.y) * 0.5));
     return out;
@@ -331,7 +362,7 @@ fn gravel_look(region: u32, w: WayPixel, flags: u32) -> WayLook {
     let track = w.half > 1.3;
     // A few tufts in the middle of a track, never a patch: a patch of shaded meadow reads as a hole.
     let middle = select(0.0, smoothstep(0.3, 0.1, x + 0.1 * (noise(p / 0.3) - 0.5)) * smoothstep(0.45, 0.7, noise(vec2f(w.along / 20.0, 6.0))), track);
-    let edge = select(soil_gives_way(1.0 - smoothstep(0.0, 0.3, frayed(p, w.half - x, 0.35, w.pw)), w), 0.0, opens(w, flags));
+    let edge = (1.0 - opens(w, flags)) * soil_gives_way(1.0 - smoothstep(0.0, 0.3, frayed(p, w.half - x, 0.35, w.pw)), w);
     // Past a pixel's reach the tufts are their mean.
     out.ground = max(edge, 0.35 * middle * mix(GRAVEL_TUFT_MEAN, smoothstep(0.55, 0.75, noise(p / 0.07)), seen(0.07, w.pw)));
     if (out.ground >= 1.0) {
@@ -463,8 +494,9 @@ fn ballast_look(code: u32, w: WayPixel) -> WayLook {
     return out;
 }
 
-// The look of a face of material `mat`; `slope` is its normal's z and `altitude` its height.
-fn way_look(mat: u32, code: u32, region: u32, su: vec2f, w: WayPixel, flags: u32, slope: f32, altitude: f32) -> WayLook {
+// The look of a face of material `mat`; `slope` is its normal's z and `altitude` its height, `piece` on a mesh of the
+// ground plan.
+fn way_look(mat: u32, code: u32, region: u32, su: vec2f, w: WayPixel, flags: u32, slope: f32, altitude: f32, piece: bool) -> WayLook {
     if (mat >= DETAIL_MATS) {
         return detail_look(mat, su, w, altitude);
     }
@@ -476,13 +508,16 @@ fn way_look(mat: u32, code: u32, region: u32, su: vec2f, w: WayPixel, flags: u32
             return WayLook(paving(region, w.p, w.pw), vec2f(0.0), 0.0, 0.0, 0.0);
         }
         case LOOK_ZEBRA, LOOK_ZEBRA_SETT, LOOK_ZEBRA_PAVERS, LOOK_ZEBRA_CONCRETE: {
-            return zebra_look(mat, code, region, w);
+            return zebra_look(mat, code, region, w, piece);
         }
         case LOOK_GIVE_WAY: {
             return give_way_look(code, region, w);
         }
         case LOOK_CONCRETE, LOOK_STRIPS: {
-            return concrete_look(code, region, w, mat == LOOK_STRIPS);
+            if (piece) {
+                return concrete_look(code, region, w, mat == LOOK_STRIPS, code != CODE_PATH);
+            }
+            return corridor_concrete_look(code, region, w, mat == LOOK_STRIPS);
         }
         case LOOK_SETT: {
             return sett_look(region, w);
diff --git a/builder/web/src/lib/trailview/roads/mesh.test.ts b/builder/web/src/lib/trailview/roads/mesh.test.ts
index d076109f1d..d0032c8b12 100644
--- a/builder/web/src/lib/trailview/roads/mesh.test.ts
+++ b/builder/web/src/lib/trailview/roads/mesh.test.ts
@@ -1,7 +1,6 @@
 import { readFileSync } from 'node:fs';
 import { describe, expect, it } from 'vitest';
-import baseline from '../../../../test-support/trailview/census-baseline.json' with { type: 'json' };
-import { countLine, fixtureTiles, gaps, objectsOnWays, shortSidewalks, tornFaces, vertices } from '../../../../test-support/trailview/census';
+import { fixtureTiles, vertices } from '../../../../test-support/trailview/census';
 import { functionOf, shaderFunctions } from '../gpu/shader-functions';
 import { cramped, features, FORD, marked, MARKED, metresPerUnit, mitre, PATH, PROFILES, RAIL, ROAD, SHOULDER_M, SURFACES, walkOf, type Line, type Node } from '../terrain/bins';
 import { DEEPEST } from '../stream/features';
@@ -21,7 +20,7 @@ import { cap, sweep, type Run } from './sweep';
 import { onWay, waysOf } from './ways';
 
 const shader = readFileSync(new URL('./corridor.wgsl', import.meta.url), 'utf8');
-const looks = ['looks', 'track-looks', 'details'].map(name => readFileSync(new URL(`./${name}.wgsl`, import.meta.url), 'utf8')).join('');
+const looks = ['looks', 'look-codes', 'track-looks', 'details'].map(name => readFileSync(new URL(`./${name}.wgsl`, import.meta.url), 'utf8')).join('');
 const tiles = fixtureTiles();
 /** The ways of a tile: each line's stations and those that its far range keeps. */
 const waysIn = ({ tile, list }: typeof tiles[number]) => planOf(features(list, tile)).runs;
@@ -108,22 +107,6 @@ describe('the corridor meshes of the fixture', () => {
             expect(stepSide(line, st[k + 1], st[k], 1).edge, `the step at ${middle.toFixed(1)} m`).toBe(middle < 40 ? walked : bare);
         }
     });
-
-    it('count the faults of the census on the fixture of format 4: 17645 gap samples (develop, where a face of no area covers none), no object on a way, 116 short sidewalks (develop 107: the 9 more lie beside tight bends, where the viewer still places its own sidewalks)', () => {
-        const counts = { gaps: gaps(tiles), 'objects-on-ways': objectsOnWays(tiles), 'short-sidewalks': shortSidewalks(tiles) };
-        for (const [count, points] of Object.entries(counts)) console.log(countLine(count, points));
-        expect(counts.gaps.length / 2).toBeLessThanOrEqual(17645);
-        expect(counts['objects-on-ways']).toEqual([]);
-        expect(counts['short-sidewalks'].length / 2).toBeLessThanOrEqual(116);
-    }, 60_000);
-
-    it('hold the torn faces of the census at census-baseline.json', () => {
-        const torn = tornFaces(pieces), counts = Object.fromEntries(Object.entries(torn).map(([kind, points]) => [kind, points.length / 2]));
-        for (const [kind, points] of Object.entries(torn)) console.log(countLine(`torn-${kind}`, points));
-        for (const [kind, most] of Object.entries(baseline)) expect(counts[kind], `a change added torn ${kind}: fix the faces, do not raise the baseline`).toBeLessThanOrEqual(most);
-        // A kind's count can hide a new torn face where a change also removes one: look at the worst places of road-census.ts.
-        expect(counts, 'a change removed torn faces: lower census-baseline.json in the same commit').toEqual(baseline);
-    }, 60_000);
 });
 
 describe('where a way leaves a child', () => {
@@ -236,7 +219,7 @@ describe('a junction that two tiles hold', () => {
 });
 
 describe('the joints of the fixture', () => {
-    it('hold a split road\'s edges on one height: at most 1 cm by the final stations, with the lifts; 5.5 mm measured on the fixture of format 3', () => {
+    it('hold a split road\'s edges on one height: at most 1.81 cm by the final stations, with the lifts, as measured on the fixture, where a tight bend widens a minor road', () => {
         let joints = 0, worst = 0;
         for (const fixtureTile of tiles) {
             const { runs } = planOf(features(fixtureTile.list, fixtureTile.tile)), edges = (run: Run, s: Station, side: number) => s.z + run.lift + s.bank * side * s.h;
@@ -251,7 +234,7 @@ describe('the joints of the fixture', () => {
             }
         }
         expect(joints).toBeGreaterThan(400);
-        expect(worst).toBeLessThanOrEqual(0.01);
+        expect(worst).toBeLessThanOrEqual(0.0181);
     });
 });
 
@@ -561,8 +544,8 @@ describe('corridor.wgsl', () => {
         scope.masks = { held: 0 };
         expect(share(100)).toBe(1);
         delete scope.masks;
-        expect(functionOf(shader, 'corridor_fragment')).toMatch(/if \(paint_draws\(.*\)\) \{\s+discard;/);
-        expect(functionOf(paint, 'road_at')).toContain('!paint_draws(distance, pixel)');
+        expect(functionOf(shader, 'corridor_fragment')).toMatch(/if \(!PIECE && paint_draws\(.*\)\) \{\s+discard;/);
+        expect(functionOf(paint, 'mask_paint')).toContain('!paint_draws(distance, pixel)');
     });
 
     it('dives a band only on a face steeper than the cones, measured from the core\'s edge', () => {
diff --git a/builder/web/src/lib/trailview/roads/roads.ts b/builder/web/src/lib/trailview/roads/roads.ts
index b62b3d5c60..8a1fefe37e 100644
--- a/builder/web/src/lib/trailview/roads/roads.ts
+++ b/builder/web/src/lib/trailview/roads/roads.ts
@@ -112,8 +112,10 @@ export class Roads {
         };
     }
 
+    /** Without feature tiles nothing draws, and the pools take no memory. */
     async attach(gpu: Gpu, [frame, sunFrame]: GPUBuffer[]): Promise {
         this.resources = undefined;
+        if (!this.tiles) return;
         const { device } = gpu, { layout, pipeline, caster, parts, partCaster } = await gpu.once(roadPipelines);
         const group = (buffer: GPUBuffer) => device.createBindGroup({ layout, entries: [{ binding: 0, resource: { buffer } }] });
         const partVertices = gpu.buffer('roads', PARTS.vertices.byteLength, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST), partIndices = gpu.buffer('roads', PARTS.indices.byteLength, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST);
diff --git a/builder/web/src/lib/trailview/roads/section.ts b/builder/web/src/lib/trailview/roads/section.ts
index 9b70de6a2f..c2bbbf6453 100644
--- a/builder/web/src/lib/trailview/roads/section.ts
+++ b/builder/web/src/lib/trailview/roads/section.ts
@@ -13,8 +13,8 @@ export const drawnCode = (line: Line) => (line.oneway !== undefined && surfaceNa
 
 export { KERB_RISE_M, LIFT_M };
 
-/** Face materials, as MAT_* of corridor.wgsl and details.wgsl: the ground under the face, the stone of a town street, and what stands beside a road. */
-export const MAT = { GROUND: 1, KERB: 2, SIDEWALK: 3, RAIL: 40, RAIL_POST: 41, RAIL_BLOCK: 42, DELI: 44, DELI_BAND: 45, REFLECTOR: 46, WALL: 48, CAP: 49 } as const;
+/** Face materials, as MAT_* of corridor.wgsl and details.wgsl: the ground under the face, the stone of a town street, what stands beside a road, and a ground plan piece's water. */
+export const MAT = { GROUND: 1, KERB: 2, SIDEWALK: 3, RAIL: 40, RAIL_POST: 41, RAIL_BLOCK: 42, DELI: 44, DELI_BAND: 45, REFLECTOR: 46, WALL: 48, CAP: 49, WATER: 50 } as const;
 /** The looks of the ways, as LOOK_* of looks.wgsl. */
 export const LOOK = { GIVE_WAY: 15, ZEBRA: 16, ZEBRA_SETT: 17, ZEBRA_PAVERS: 18, ZEBRA_CONCRETE: 19, ASPHALT: 20, MAIN: 21, MOTORWAY: 22, CONCRETE: 23, SETT: 24, PAVERS: 25, GRAVEL: 26, DIRT: 27, TRAIL: 28, BALLAST: 29, STRIPS: 30, TREAD: 31, RISER: 32, SLEEPER: 33, TIMBER: 34, RAIL: 35, RAIL_HEAD: 36, RACK: 37, CABLE: 38, LOG: 39 } as const;
 /**
diff --git a/builder/web/src/lib/trailview/roads/track-looks.wgsl b/builder/web/src/lib/trailview/roads/track-looks.wgsl
index c12765d23a..5add577a2b 100644
--- a/builder/web/src/lib/trailview/roads/track-looks.wgsl
+++ b/builder/web/src/lib/trailview/roads/track-looks.wgsl
@@ -42,8 +42,12 @@ fn detail_fade(distance: f32) -> f32 {
 }
 
 // Whether a way paints these faces `distance` metres off: nearer, they hide all that it could paint.
+// A pixel of a storey's top (plan/piece.wgsl): no faces of tracks.ts stand on a deck, so its way paints them at any
+// distance.
+var DETAIL_EVERYWHERE: bool = false;
+
 fn detail_painted(distance: f32) -> bool {
-    return distance >= DETAIL_M;
+    return distance >= DETAIL_M || DETAIL_EVERYWHERE;
 }
 
 fn narrow_gauge(code: u32) -> bool {
diff --git a/builder/web/src/lib/trailview/still-view.ts b/builder/web/src/lib/trailview/still-view.ts
index 5e18038ee3..5e299be4b0 100644
--- a/builder/web/src/lib/trailview/still-view.ts
+++ b/builder/web/src/lib/trailview/still-view.ts
@@ -184,7 +184,7 @@ export async function coverView(line: readonly [number, number][], config: Plann
     }
     const sun = solarPosition(centre, solarTerms(instant)).bearing / RAD;
     const camera = chooseView(line, grid, { width, height, sun });
-    return camera && { ...camera, date, time, weather, debug: 'off' };
+    return camera && { ...camera, date, time, weather, debug: 'off', plan: 'off' };
 }
 
 /** The heights of a rectangle of tiles at zoom `z`, decoded into one grid. */
diff --git a/builder/web/src/lib/trailview/still.ts b/builder/web/src/lib/trailview/still.ts
index a12e35e7d4..6170715110 100644
--- a/builder/web/src/lib/trailview/still.ts
+++ b/builder/web/src/lib/trailview/still.ts
@@ -54,7 +54,7 @@ export async function still(gpu: Gpu, config: PlannerConfig, job: StillJob, { si
         signal?.addEventListener('abort', aborted, { signal: done.signal });
         void gpu.device.lost.then(info => fail('device-lost', `The WebGPU device was lost: ${info.message}`));
     });
-    const started = TrailView.start(document.createElement('canvas'), gpu, config, job.view, MAX_SCALE, [job.width, job.height]);
+    const started = TrailView.start(document.createElement('canvas'), gpu, config, job.view, MAX_SCALE, { size: [job.width, job.height] });
     try {
         return await Promise.race([failed, started.then(async engine => {
             await engine.waitForIdle();
diff --git a/builder/web/src/lib/trailview/stream/features.test.ts b/builder/web/src/lib/trailview/stream/features.test.ts
index 91ad1fbc64..e79b7de0e9 100644
--- a/builder/web/src/lib/trailview/stream/features.test.ts
+++ b/builder/web/src/lib/trailview/stream/features.test.ts
@@ -1,6 +1,6 @@
 import { readFileSync } from 'node:fs';
 import { describe, expect, it } from 'vitest';
-import { decodeFeatures, type Feature } from './features';
+import { decodedTile, decodeFeatures, heldTile, tileBudget, wantTiles, type Feature } from './features';
 
 const vector = (name: string) => readFileSync(new URL(`../../../../../../specs/vectors/${name}`, import.meta.url));
 
@@ -29,4 +29,14 @@ describe('feature tiles', () => {
         expect(() => decodeFeatures(new Uint8Array([...bytes, 0]))).toThrow('after its last feature');
         expect(decodeFeatures(new Uint8Array([0, 0]))).toEqual([]);
     });
+
+    it('keep a wanted tile past the budget, and let it go as soon as no job wants it', async () => {
+        tileBudget(1);
+        wantTiles(['13/1/1']);
+        for (const name of ['13/1/1', '13/1/2']) await decodedTile(name, bytes.slice().buffer);
+        expect([heldTile('13/1/1') !== undefined, heldTile('13/1/2') !== undefined]).toEqual([true, true]);
+        wantTiles([]);
+        expect([heldTile('13/1/1'), heldTile('13/1/2')]).toEqual([undefined, undefined]);
+        tileBudget(32 * 2 ** 20);
+    });
 });
diff --git a/builder/web/src/lib/trailview/stream/features.ts b/builder/web/src/lib/trailview/stream/features.ts
index 40f99224b3..0da901303a 100644
--- a/builder/web/src/lib/trailview/stream/features.ts
+++ b/builder/web/src/lib/trailview/stream/features.ts
@@ -30,7 +30,7 @@ export const WALK_LEFT = 1, WALK_RIGHT = 2;
  * that decodes to about 8 MB. The four quarters of a tile reach a worker far apart in its queue.
  */
 let budget = 32 * 2 ** 20;
-const kept = new Map; bytes: number; charged: number }>();
+const kept = new Map; bytes: number; charged: number; pinned?: boolean }>();
 let held = 0;
 
 /** Sets the bytes that this worker keeps, for a worker that hangs more than decoded features on its tiles. */
@@ -38,16 +38,37 @@ export function tileBudget(bytes: number): void {
     budget = bytes;
 }
 
-/** Past the budget, the tiles that have gone longest without use go, but for `newest`. */
-function trim(newest: { bytes: number; charged: number }): void {
+/** The tiles that jobs on their way or still wished read: see wantTiles. */
+let wanted = new Set();
+
+/** Names the tiles that jobs on their way or still wished read: `trim` keeps them, as it keeps the newest. The others fall back under the budget at once. */
+export function wantTiles(names: Iterable): void {
+    wanted = new Set(names);
+    trim();
+}
+
+/**
+ * The tiles that have gone longest without use go, but never `newest` or a wanted one: an unpinned one past the
+ * budget, a pinned one past a third of it, so the unpinned tiles always keep the rest.
+ */
+function trim(newest?: { bytes: number; charged: number }): void {
+    let pins = 0;
+    for (const item of kept.values()) if (item.pinned) pins += item.bytes + item.charged;
     for (const [old, item] of kept) {
-        if (held <= budget) break;
-        if (item === newest) continue;
+        if (held <= budget && pins <= budget / 3) break;
+        if (item === newest || wanted.has(old) || (item.pinned ? pins <= budget / 3 : held <= budget)) continue;
         kept.delete(old);
         held -= item.bytes + item.charged;
+        if (item.pinned) pins -= item.bytes + item.charged;
     }
 }
 
+/** Keeps a kept tile through `trim` while `pinned`, within a third of the budget. A failed decode leaves `kept` at once, pinned or not. */
+export function pinTile(name: string, pinned: boolean): void {
+    const entry = kept.get(name);
+    if (entry) entry.pinned = pinned;
+}
+
 /** Counts `bytes` that hang from the features of a kept tile, in place of what was counted for it before. */
 export function chargeTile(name: string, bytes: number): void {
     const entry = kept.get(name);
@@ -57,24 +78,31 @@ export function chargeTile(name: string, bytes: number): void {
     trim(entry);
 }
 
-/** The features of tile body `body`, gzip or not, named `name`: decoded once while it is among the last bytes of the budget. */
-export function decodedTile(name: string, body: ArrayBuffer): Promise {
-    let entry = kept.get(name);
-    if (entry) kept.delete(name);
-    else {
-        // The Promise is kept at once, so a second message for the tile waits for this decode.
-        const created = entry = { features: decodeBody(body), bytes: 0, charged: 0 };
-        created.features.then(features => {
-            if (kept.get(name) !== created) return;
-            created.bytes = decodedBytes(features);
-            held += created.bytes;
-            trim(created);
-        }, () => { if (kept.get(name) === created) kept.delete(name); });
-    }
+/** The features of tile `name` while it is among the last bytes of the budget; undefined after it left. */
+export function heldTile(name: string): Promise | undefined {
+    const entry = kept.get(name);
+    if (!entry) return undefined;
+    kept.delete(name);
     kept.set(name, entry);
     return entry.features;
 }
 
+/** The features of tile body `body`, gzip or not, named `name`: decoded once while it is among the last bytes of the budget. */
+export function decodedTile(name: string, body: ArrayBuffer): Promise {
+    const known = heldTile(name);
+    if (known) return known;
+    // The Promise is kept at once, so a second message for the tile waits for this decode.
+    const created = { features: decodeBody(body), bytes: 0, charged: 0 };
+    created.features.then(features => {
+        if (kept.get(name) !== created) return;
+        created.bytes = decodedBytes(features);
+        held += created.bytes;
+        trim(created);
+    }, () => { if (kept.get(name) === created) kept.delete(name); });
+    kept.set(name, created);
+    return created.features;
+}
+
 async function decodeBody(body: ArrayBuffer): Promise {
     let bytes = new Uint8Array(body);
     // A tile service may hand over the gzip of the archive as it is.
diff --git a/builder/web/src/lib/trailview/stream/ground-pages.ts b/builder/web/src/lib/trailview/stream/ground-pages.ts
index 8dd3a5a958..3825a956e9 100644
--- a/builder/web/src/lib/trailview/stream/ground-pages.ts
+++ b/builder/web/src/lib/trailview/stream/ground-pages.ts
@@ -71,10 +71,18 @@ const clampIndex = (v: number, size: number) => Math.min(size - 1, Math.max(0, v
 /** Values per raster pixel, resampled bilinearly onto the grid; the raster's edge repeats. */
 function bilinear(raster: Raster, values: Float32Array, z: number, x: number, y: number): Float32Array {
     const u = axis(raster, z, x, 'x'), v = axis(raster, z, y, 'y'), n = raster.size, out = new Float32Array(TILE * TILE);
+    // The columns are the same in every row.
+    const fxs = new Float64Array(TILE), c0s = new Int32Array(TILE), c1s = new Int32Array(TILE);
+    for (let i = 0; i < TILE; i++) {
+        const i0 = Math.floor(u[i]);
+        fxs[i] = u[i] - i0;
+        c0s[i] = clampIndex(i0, n);
+        c1s[i] = clampIndex(i0 + 1, n);
+    }
     for (let j = 0; j < TILE; j++) {
         const j0 = Math.floor(v[j]), fy = v[j] - j0, r0 = clampIndex(j0, n) * n, r1 = clampIndex(j0 + 1, n) * n;
         for (let i = 0; i < TILE; i++) {
-            const i0 = Math.floor(u[i]), fx = u[i] - i0, c0 = clampIndex(i0, n), c1 = clampIndex(i0 + 1, n);
+            const fx = fxs[i], c0 = c0s[i], c1 = c1s[i];
             const top = values[r0 + c0] + (values[r0 + c1] - values[r0 + c0]) * fx;
             const bottom = values[r1 + c0] + (values[r1 + c1] - values[r1 + c0]) * fx;
             out[j * TILE + i] = top + (bottom - top) * fy;
@@ -91,17 +99,16 @@ function bilinear(raster: Raster, values: Float32Array, z: number, x: number, y:
 export function dateColour(a: Raster | undefined, b: Raster | undefined, weight: number): { rgb: Float32Array[]; ndvi: Float32Array; seen: Float32Array; mark: Float32Array } {
     const raster = a ?? b!, count = raster.size * raster.size;
     const rgb = [0, 1, 2].map(() => new Float32Array(count)), ndvi = new Float32Array(count), seen = new Float32Array(count), mark = new Float32Array(count);
-    const at = (q: Raster | undefined, i: number, c: number) => (q ? q.data[4 * i + c] : 0);
+    // A missing quarter reads as zeros. Scalars per pixel, not arrays: this runs for every pixel of every tile.
+    const da = a?.data ?? new Uint8Array(4 * count), db = b?.data ?? new Uint8Array(4 * count);
     for (let i = 0; i < count; i++) {
-        const codes = [at(a, i, 3), at(b, i, 3)];
-        const marked = codes.map(code => +(code === SNOW_MARK));
-        const looked = [a, b].map((q, k) => +(codes[k] !== UNSEEN && Math.max(at(q, i, 0), at(q, i, 1), at(q, i, 2)) > 0));
-        const w = [looked[0] * (1 - weight + weight * (1 - looked[1])), looked[1] * (weight + (1 - weight) * (1 - looked[0]))];
-        const sum = w[0] + w[1];
-        for (let c = 0; c < 3; c++) rgb[c][i] = (w[0] * at(a, i, c) + w[1] * at(b, i, c)) / 255;
-        ndvi[i] = sum > 0 ? w.reduce((s, wk, k) => s + wk * (marked[k] ? 0 : (codes[k] - 1) / 127 - 1), 0) : 0.45;
+        const p = 4 * i, codeA = da[p + 3], codeB = db[p + 3], markedA = +(codeA === SNOW_MARK), markedB = +(codeB === SNOW_MARK);
+        const lookedA = +(codeA !== UNSEEN && Math.max(da[p], da[p + 1], da[p + 2]) > 0), lookedB = +(codeB !== UNSEEN && Math.max(db[p], db[p + 1], db[p + 2]) > 0);
+        const wA = lookedA * (1 - weight + weight * (1 - lookedB)), wB = lookedB * (weight + (1 - weight) * (1 - lookedA)), sum = wA + wB;
+        for (let c = 0; c < 3; c++) rgb[c][i] = (wA * da[p + c] + wB * db[p + c]) / 255;
+        ndvi[i] = sum > 0 ? wA * (markedA ? 0 : (codeA - 1) / 127 - 1) + wB * (markedB ? 0 : (codeB - 1) / 127 - 1) : 0.45;
         seen[i] = +(sum > 0);
-        mark[i] = weight < 0.5 ? marked[0] : marked[1];
+        mark[i] = weight < 0.5 ? markedA : markedB;
     }
     return { rgb, ndvi, seen, mark };
 }
@@ -142,7 +149,9 @@ export function groundPages(input: GroundInputs): (GroundPage | null)[] {
         const raster = (a ?? b)!, day = dateColour(a, b, date.weight), resample = (values: Float32Array) => bilinear(raster, values, z, x, y);
         const [r, g, bl] = day.rgb.map(resample), ndvi = resample(day.ndvi), seen = resample(day.seen), mark = resample(day.mark);
         for (let t = 0; t < n; t++) {
-            colour.set([r[t], g[t], bl[t]].map(c => Math.round(255 * c)), 4 * t);
+            colour[4 * t] = Math.round(255 * r[t]);
+            colour[4 * t + 1] = Math.round(255 * g[t]);
+            colour[4 * t + 2] = Math.round(255 * bl[t]);
             colour[4 * t + 3] = seen[t] < 0.5 ? UNSEEN : Math.min(255, Math.max(2, Math.round((ndvi[t] + 1) * 127 + 1)));
             snow[4 * t + 2] = Math.round(255 * mark[t]);
         }
diff --git a/builder/web/src/lib/trailview/stream/terrain.ts b/builder/web/src/lib/trailview/stream/terrain.ts
index ee5528ab78..62956e120b 100644
--- a/builder/web/src/lib/trailview/stream/terrain.ts
+++ b/builder/web/src/lib/trailview/stream/terrain.ts
@@ -1,4 +1,5 @@
 import { PMTiles } from 'pmtiles';
+import STAMP_VERSION from 'virtual:stamp-version';
 import type { PlannerConfig } from '../../planner/config';
 import { decodedTiles, fetchTile, openSource, requestSignal, type Source } from '../../planner/layers/archive';
 import { worldPixel } from '../../planner/layers/mercator';
@@ -76,6 +77,7 @@ export function releaseTiles(config: PlannerConfig, stop = new AbortController()
 export interface EyeTiles {
     terrain: TerrainSource['fetch'];
     features: ReturnType;
+    stamps: ReturnType;
     /** Settles when both tiles under the eye have arrived or failed. */
     arrived: Promise;
 }
@@ -96,7 +98,7 @@ export function eyeTiles(config: PlannerConfig, lonLat: [number, number], stop:
         if (body) early = undefined;
         return body ?? fetch(z, x, y);
     };
-    return { terrain, features, arrived };
+    return { terrain, features, stamps: bakedNodes(config, stop), arrived };
 }
 
 /** The pages of tile bodies, decoded in workers until `stop` aborts. */
@@ -144,3 +146,27 @@ export function featureTiles(config: PlannerConfig, stop = new AbortController()
     }, body => body.buffer, FEATURE_BODIES, body => body.byteLength);
     return async (z, x, y) => (await tiles.tile(z, x, y))?.slice(0);
 }
+
+/**
+ * The nodes of a release's stamp layer: the bytes of node z/x/y as the stamp worker posts them (terrain/node-bytes.ts),
+ * undefined where the layer holds none. Undefined when the release has no stamp layer. A layer of another stamp
+ * version holds none. An abort of `stop` ends every request.
+ */
+export function bakedNodes(config: PlannerConfig, stop: AbortSignal): ((z: number, x: number, y: number) => Promise) | undefined {
+    const url = (config.layers as Record)['trailview-stamps'];
+    if (!url) return undefined;
+    const open = async () => {
+        const opened = await openSource(url);
+        if (opened.metadata.stamp_version === STAMP_VERSION) return opened;
+        console.warn(`The TrailView stamp layer has stamp_version ${opened.metadata.stamp_version}, not ${STAMP_VERSION}. The stamp worker makes every node.`);
+        return undefined;
+    };
+    // A layer that fails to open holds nothing: the stamp worker makes every node.
+    const source = open().catch(() => undefined);
+    return async (z, x, y) => {
+        const opened = await source;
+        if (!opened || z < opened.minZoom || z > opened.maxZoom) return undefined;
+        const body = await opened.get(z, x, y, stop).catch(() => undefined);
+        return body && new Uint8Array(body);
+    };
+}
diff --git a/builder/web/src/lib/trailview/structures/bridges.ts b/builder/web/src/lib/trailview/structures/bridges.ts
index 1d531655b6..53af41f602 100644
--- a/builder/web/src/lib/trailview/structures/bridges.ts
+++ b/builder/web/src/lib/trailview/structures/bridges.ts
@@ -104,7 +104,8 @@ export function bridges(b: MeshBuilder, list: Feature[], tile: Node, all: Line[]
             }
             if (line.abut?.[v ? 1 : 0]) {
                 const depth = Math.min(ABUTMENT_M, (to - from) / 2);
-                abutment(b, s, point(v ? to - depth : from + depth), Math.max(wl, wr), t, out);
+                // The ground plan's end faces stand under the deck ends instead.
+                b.offPlan(() => abutment(b, s, point(v ? to - depth : from + depth), Math.max(wl, wr), t, out));
             }
         }
     }
@@ -195,16 +196,21 @@ function railing(b: MeshBuilder, s: Station, t: Station, h: number, length: numb
     }
 }
 
-/** A covered bridge from station s to t: a wooden wall on each side, posts up to the eaves, and a pitched roof with its underside. */
+/**
+ * A covered bridge from station s to t: a wooden wall on each side, posts up to the eaves, and a pitched roof with its
+ * underside. No storey of the ground plan draws them: they draw beside its deck.
+ */
 function covered(b: MeshBuilder, s: Station, t: Station, h: number, length: number): void {
     const w = h + 0.1, eave = w + OVERHANG_M, ridge = EAVES_M + PITCH * eave;
-    for (const side of [1, -1]) {
-        b.strip(s, t, [side * w, LIFT_M], [side * w, COVER_WALL_M], WOOD_DARK, [-side, 0]);
-        b.strip(s, t, [side * w, COVER_WALL_M], [side * w, LIFT_M], WOOD_DARK, [side, 0]);
-        b.strip(s, t, [0, ridge], [side * eave, EAVES_M], ROOF, [0, 1]);
-        b.strip(s, t, [side * eave, EAVES_M], [0, ridge], ROOF_UNDER, [0, -1]);
-    }
-    railing(b, s, t, w, length, WOOD_DARK, 0.15, EAVES_M, COVER_WALL_M);
+    b.beside(() => {
+        for (const side of [1, -1]) {
+            b.strip(s, t, [side * w, LIFT_M], [side * w, COVER_WALL_M], WOOD_DARK, [-side, 0]);
+            b.strip(s, t, [side * w, COVER_WALL_M], [side * w, LIFT_M], WOOD_DARK, [side, 0]);
+            b.strip(s, t, [0, ridge], [side * eave, EAVES_M], ROOF, [0, 1]);
+            b.strip(s, t, [side * eave, EAVES_M], [0, ridge], ROOF_UNDER, [0, -1]);
+        }
+        railing(b, s, t, w, length, WOOD_DARK, 0.15, EAVES_M, COVER_WALL_M);
+    });
 }
 
 /** A pier at each `bridge-pier` point near the node, across its bridge line, from under the deck down into the drawn surface. */
diff --git a/builder/web/src/lib/trailview/structures/house-records.ts b/builder/web/src/lib/trailview/structures/house-records.ts
index 8094013be2..471d167f78 100644
--- a/builder/web/src/lib/trailview/structures/house-records.ts
+++ b/builder/web/src/lib/trailview/structures/house-records.ts
@@ -2,7 +2,7 @@
 // and a mesh of walls and a flat roof for the footprints that no template fits. A worker uses it.
 import earcut from 'earcut';
 import { EXTENT, square, unitScale, type Feature } from '../stream/features';
-import { features, metresPerUnit, type Node } from '../terrain/bins';
+import { fronts, metresPerUnit, type Node } from '../terrain/bins';
 
 /** Words of a record, as `House` in houses.wgsl. */
 export const RECORD_WORDS = 8;
@@ -17,7 +17,7 @@ export const TEMPLATE = 0, OUTLINE = 1;
 const ROOFS: Record = { gabled: 1, hipped: 2, pyramidal: 2, 'half-hipped': 3 };
 
 /** OSM building values that draw nothing, draw as a barn or shed, as a church or as a block, from the prototype's nearfield.ts. */
-export const SKIPPED = new Set(['roof', 'ruins', 'construction', 'carport', 'storage_tank', 'bunker']);
+const SKIPPED = new Set(['roof', 'ruins', 'construction', 'carport', 'storage_tank', 'bunker']);
 const SHEDS = new Set(['barn', 'farm_auxiliary', 'shed', 'garage', 'garages', 'stable', 'cowshed', 'hut', 'sty', 'boathouse']);
 /** Granaries this small stand raised on pillars, as hórreos and stabbur do; larger ones are barns. */
 const GRANARY_M2 = 60;
@@ -179,12 +179,12 @@ export function tileHouses(list: Feature[], tile: Node, owned: Node = tile): Til
     const scale = unitScale(tile.level), [west, north, size] = square(tile, owned);
     const records: number[] = [], outlines: number[] = [], floats = new Float32Array(1), word = new Uint32Array(floats.buffer);
     const f32 = (v: number) => ((floats[0] = v), word[0]);
-    const left = tile.x * EXTENT, top = tile.y * EXTENT, { buildings } = features(list, tile);
+    const left = tile.x * EXTENT, top = tile.y * EXTENT, faces = fronts(list, tile);
     let building = -1;
     for (const feature of list) {
         if (feature.kind !== 'building') continue;
-        // The outward direction of the wall that faces its road, in world units; features() lists the buildings in this order.
-        const front = buildings[++building].front;
+        // The wall that faces its road; fronts() lists the buildings in this order.
+        const front = faces[++building];
         const tag = feature.tags.building ?? 'yes', part = feature.parts.find(p => p.outer);
         if (SKIPPED.has(tag) || !part || part.xy.length < 6) continue;
         // Metres east and north of the first vertex.
diff --git a/builder/web/src/lib/trailview/structures/houses.ts b/builder/web/src/lib/trailview/structures/houses.ts
index 67dfc95ef1..38e80daa3f 100644
--- a/builder/web/src/lib/trailview/structures/houses.ts
+++ b/builder/web/src/lib/trailview/structures/houses.ts
@@ -11,6 +11,7 @@ import { DEPTH, sceneFormat } from '../resolve/targets';
 import type { FeatureTiles } from '../terrain/stamps';
 import { OUTLINE_WORDS, RECORD_WORDS, type TileHouses } from './house-records';
 import { stopped } from '../stream/terrain';
+import { CAPS, DeviceCache } from '../terrain/device-cache';
 
 /** Houses on the GPU at most, and the bytes of outline vertices. */
 const HOUSES = 2 ** 16, OUTLINE_BYTES = 2 * 2 ** 20;
@@ -168,9 +169,15 @@ export class Houses {
     /** Whether the last update put other houses on the GPU. */
     newContent = false;
 
-    /** An abort of `stop` ends the worker. */
-    constructor(private readonly frame: Frame, private readonly features: FeatureTiles | undefined, private readonly rules: Rules, private readonly changed: () => void, stop: AbortSignal) {
+    private readonly cache?: Promise;
+
+    /**
+     * An abort of `stop` ends the worker. With `cache`, the release and the version of the house worker's code,
+     * a tile's records come from the device cache where it holds them, and go there once made.
+     */
+    constructor(private readonly frame: Frame, private readonly features: FeatureTiles | undefined, private readonly rules: Rules, private readonly changed: () => void, stop: AbortSignal, cache?: { release: string; version: string }) {
         if (!features) return;
+        if (cache) this.cache = DeviceCache.open('houses', cache.release, cache.version, CAPS.houses).catch(() => undefined);
         const worker = this.worker = new Worker(new URL('./house-worker.ts', import.meta.url), { type: 'module' });
         stop.addEventListener('abort', () => worker.terminate());
         this.worker.onmessage = ({ data }) => {
@@ -479,13 +486,17 @@ export class Houses {
     }
 
     private async load(x: number, y: number): Promise {
+        const key = `${ZOOM}/${x}/${y}`, cache = await this.cache, kept = await cache?.read(key).catch(() => undefined);
+        if (kept) return { records: kept[0], outlines: kept[1] };
         const up = ZOOM - DEEPEST, tile = { level: DEEPEST, x: x >> up, y: y >> up }, body = await this.features!(tile.level, tile.x, tile.y);
         if (!body) return null;
         const id = this.next++;
-        return new Promise(resolve => {
+        const made = await new Promise(resolve => {
             this.waiting.set(id, resolve);
             this.worker!.postMessage({ id, tile, owned: { level: ZOOM, x, y }, body }, [body]);
         });
+        if (made) void cache?.write(key, [made.records, made.outlines]).catch(() => {});
+        return made;
     }
 
     private keep(name: string, result: TileHouses | null): void {
diff --git a/builder/web/src/lib/trailview/structures/houses.wgsl b/builder/web/src/lib/trailview/structures/houses.wgsl
index cac932f1c3..7dfc798bcf 100644
--- a/builder/web/src/lib/trailview/structures/houses.wgsl
+++ b/builder/web/src/lib/trailview/structures/houses.wgsl
@@ -255,6 +255,9 @@ const PARAPET_M: vec2f = vec2f(0.25, 0.6);
 const GREENHOUSE_RISE_M: f32 = 1.0;
 const BEAM_M: f32 = 0.2;
 const BALCONY_M: f32 = 0.9;
+// The size of a pixel in metres where a facade's windows start to give way to their mean, and where only the mean
+// is left: there a window of about a metre is a pixel wide, and drawn sharp it would shimmer in motion.
+const WINDOWS_FADE_M = vec2f(0.3, 1.0);
 // A roof rises at most this much above the eaves.
 const ROOF_M: f32 = 7.0;
 // At night this share of the windows shines in this colour, and this share of the houses stays dark.
@@ -818,10 +821,10 @@ fn facade(d: Drawn, wall: u32, first: u32, u: f32, len: f32, z: f32, front: bool
         let beam = fract(z / d.storey) * d.storey < BEAM_M || z > d.wall - BEAM_M;
         base = select(base, wood, post || beam);
     }
-    // Far off, the cells are smaller than a pixel: their mean.
+    // Far off, a window is about a pixel wide: the cell's mean.
     let glass = select(0.0, share, z >= 0.0);
     let mean = vec4f(mix(select(base, plinth, z < PLINTH_M), GLASS, glass), lit * share);
-    if (w > 0.5) {
+    if (w > WINDOWS_FADE_M.y) {
         return mean;
     }
     var colour = base;
@@ -851,7 +854,7 @@ fn facade(d: Drawn, wall: u32, first: u32, u: f32, len: f32, z: f32, front: bool
             colour = plinth;
         }
     }
-    return mix(vec4f(colour, glow), mean, smoothstep(0.15, 0.5, w));
+    return mix(vec4f(colour, glow), mean, smoothstep(WINDOWS_FADE_M.x, WINDOWS_FADE_M.y, w));
 }
 
 // A church tower's face: plinth, wall, the belfry and the wall over it, in three columns.
diff --git a/builder/web/src/lib/trailview/structures/mesh.ts b/builder/web/src/lib/trailview/structures/mesh.ts
index 913b9eef69..29132ba995 100644
--- a/builder/web/src/lib/trailview/structures/mesh.ts
+++ b/builder/web/src/lib/trailview/structures/mesh.ts
@@ -23,6 +23,10 @@ export const GROUND = 1, PAINT = 2, VOID = 4, INSIDE = 8, LAMP = 16, BORE = 128;
 export interface StructureMesh {
     vertices: ArrayBuffer;
     indices: Uint32Array;
+    /** The count of the last indices, which the ground plan does not draw: a bridge's abutments, where its end faces stand. None: 0. */
+    offPlan?: number;
+    /** The count of the indices before those: a bridge's other faces, which the ground plan's storeys draw where its meshes draw. None: 0. */
+    decks?: number;
 }
 
 /** A point of a cross-section: metres across to the left of the line, and metres up. */
@@ -83,7 +87,10 @@ export function curveStops(line: Line): (Station & { along: number })[] {
  */
 export class MeshBuilder {
     private readonly words: number[] = [];
-    private readonly indices: number[] = [];
+    private readonly onPlan: number[] = [];
+    private readonly decks: number[] = [];
+    private readonly late: number[] = [];
+    private indices = this.onPlan;
 
     /** A vertex at a station's corner, or at a point. */
     vertex(x: number, y: number, z: number, colour: number, across = 0, half = 0, sleepers = NO_SLEEPERS): number {
@@ -112,8 +119,30 @@ export class MeshBuilder {
         this.quad([this.at(s, a, colour), this.at(s, b, colour), this.at(t, b, colour), this.at(t, a, colour)], o);
     }
 
+    /** Builds the faces of `make` as faces that the ground plan does not draw (StructureMesh.offPlan). */
+    offPlan(make: () => void): void {
+        this.within(this.late, make);
+    }
+
+    /** Builds the faces of `make` as a bridge's, which the ground plan's storeys draw where its meshes draw (StructureMesh.decks). */
+    bridge(make: () => void): void {
+        this.within(this.decks, make);
+    }
+
+    /** Builds the faces of `make` of a bridge as faces that no storey draws: they draw with the ground plan too. */
+    beside(make: () => void): void {
+        this.within(this.onPlan, make);
+    }
+
+    private within(list: number[], make: () => void): void {
+        const was = this.indices;
+        this.indices = list;
+        make();
+        this.indices = was;
+    }
+
     mesh(): StructureMesh | null {
-        if (!this.indices.length) return null;
+        if (!this.onPlan.length && !this.decks.length && !this.late.length) return null;
         const vertices = new ArrayBuffer(this.words.length * 4), floats = new Float32Array(vertices), ints = new Int32Array(vertices), uints = new Uint32Array(vertices);
         this.words.forEach((word, i) => {
             const k = i % STRUCTURE_VERTEX;
@@ -121,7 +150,7 @@ export class MeshBuilder {
             else if (k === 3 || k === 4) uints[i] = word;
             else floats[i] = word;
         });
-        return { vertices, indices: new Uint32Array(this.indices) };
+        return { vertices, indices: new Uint32Array([...this.onPlan, ...this.decks, ...this.late]), offPlan: this.late.length, decks: this.decks.length };
     }
 
     /** The direction east, north, up of a direction [across, up] at the middle of two stations. */
diff --git a/builder/web/src/lib/trailview/structures/node.ts b/builder/web/src/lib/trailview/structures/node.ts
index 6712a83256..f59fe0c8c0 100644
--- a/builder/web/src/lib/trailview/structures/node.ts
+++ b/builder/web/src/lib/trailview/structures/node.ts
@@ -4,7 +4,7 @@ import { coresOf } from '../roads/cores';
 import { packPoints, type Point } from '../instances/points';
 import type { Feature } from '../stream/features';
 import { AnchoredBuilder, anchorBytes, type AnchoredMesh } from './anchored';
-import { BRIDGE, features, LIFT_M, metresPerUnit, PATH, ROAD, TUNNEL, type Node } from '../terrain/bins';
+import { BRIDGE, features, LIFT_M, metresPerUnit, TUNNEL, type Node } from '../terrain/bins';
 import { OWNER } from '../terrain/lod';
 import { cornerAt } from '../terrain/corners';
 import { deckHalf } from '../roads/decks';
@@ -73,30 +73,33 @@ export interface Meshes { structures: StructureMesh | null; anchored: AnchoredMe
  */
 export interface NodeMeshes { far: Meshes; near: Meshes; anchors: ArrayBuffer | null; points: Uint32Array | null }
 
-/** The meshes of a node of the OWNER level from the features of its feature tile: the structures, then the kinds of the registry. */
-export function structureMeshes(list: Feature[], tile: Node, node: Node): NodeMeshes {
+/**
+ * The meshes of a node of the OWNER level from the features of its feature tile: the structures, then the kinds of the
+ * registry. With the ground plan (`plan`) the plan's mesh draws the culverts' mouths (plan/piece.wgsl): none stands here.
+ */
+export function structureMeshes(list: Feature[], tile: Node, node: Node, plan = false): NodeMeshes {
     const none = { structures: null, anchored: null };
     if (node.level !== OWNER) return { far: none, near: none, anchors: null, points: null };
     const side = 2 ** (30 - node.level), x0 = node.x * side, y0 = node.y * side;
     const owns: Owns = (x, y) => x >= x0 && x < x0 + side && y >= y0 && y < y0 + side;
     const words: number[] = [], far = { mesh: new MeshBuilder(), anchored: new AnchoredBuilder(words) }, near = { mesh: new MeshBuilder(), anchored: new AnchoredBuilder(words) };
-    const shapes = features(list, tile), { lines, buildings } = shapes;
-    bridges(far.mesh, list, tile, lines, owns);
+    const shapes = features(list, tile), { lines } = shapes;
+    far.mesh.bridge(() => bridges(far.mesh, list, tile, lines, owns));
     tunnels(far.mesh, lines, owns);
     galleries(far.mesh, lines, owns);
     rails(far.mesh, far.anchored, list, tile, lines, owns, [x0, y0, x0 + side, y0 + side]);
     const points: Point[] = [];
     let kind = '';
     const place = ({ model, tint = 1, ...at }: Placement) => points.push({ ...at, tint, model: POINT_MODELS.indexOf(`${kind}/${model}`) });
-    const out: Build = { far, near, owns, place, ways: lines.filter(line => line.kind === ROAD || line.kind === PATH), cores: coresOf(shapes), taken: [], buildings, cornered: (x, y) => !!cornerAt(lines, x, y) };
+    const out: Build = { far, near, owns, place, shapes, cores: coresOf(shapes), taken: [], cornered: (x, y) => !!cornerAt(lines, x, y) };
     for (const feature of list) {
         kind = feature.kind;
         KINDS.get(kind)?.build(placed(feature, tile), out);
     }
     kind = 'road';
-    streetLamps(out, lines);
+    streetLamps(out);
     kind = 'stream';
-    culvertMouths(out, shapes);
+    if (!plan) culvertMouths(out, shapes);
     const meshes = ({ mesh, anchored }: typeof far): Meshes => ({ structures: mesh.mesh(), anchored: anchored.mesh() });
     return { far: meshes(far), near: meshes(near), anchors: words.length ? anchorBytes(words) : null, points: points.length ? packPoints(points.filter(p => p.model >= 0)) : null };
 }
diff --git a/builder/web/src/lib/trailview/structures/plan-cells.wgsl b/builder/web/src/lib/trailview/structures/plan-cells.wgsl
new file mode 100644
index 0000000000..555b2cdd9a
--- /dev/null
+++ b/builder/web/src/lib/trailview/structures/plan-cells.wgsl
@@ -0,0 +1,2 @@
+// The cells whose ground-plan meshes draw (plan/cells.wgsl), at the binding of the structures' group.
+@group(0) @binding(6) var plan_cells: array;
diff --git a/builder/web/src/lib/trailview/structures/structures.test.ts b/builder/web/src/lib/trailview/structures/structures.test.ts
new file mode 100644
index 0000000000..2a43191a36
--- /dev/null
+++ b/builder/web/src/lib/trailview/structures/structures.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+import { OWNER, size, type Node } from '../terrain/lod';
+import type { Stamps } from '../terrain/stamps';
+import type { NodeMeshes } from './node';
+import { Structures } from './structures';
+
+describe('the structures', () => {
+    it('give the pools the meshes of the nearest owner first, whatever node the terrain draws first', () => {
+        const meshes = new Map(), side = size(OWNER);
+        const stamps = {
+            get: ({ x }: Node) => {
+                if (!meshes.has(x)) meshes.set(x, { far: { structures: { vertices: new ArrayBuffer(4), indices: new Uint32Array(1) }, anchored: null }, near: { structures: null, anchored: null }, anchors: null, points: null });
+                return { meshes: meshes.get(x) };
+            },
+        } as unknown as Stamps;
+        const structures = new Structures(stamps);
+        // The eye stands in owner 100's square. The reach of the near casters is tiny at this unit: only that square is added.
+        const node = (x: number): Node => ({ level: OWNER, x, y: 0 });
+        structures.update([node(120), node(103), node(100)], { x: 100.5 * side, y: 0.5 * side, unit: 1e6 });
+        const order = (structures as unknown as { draws: unknown[] }).draws.map(mesh => [...meshes].find(([, m]) => m.far.structures === mesh)?.[0]);
+        expect(order).toEqual([100, 103, 120]);
+    });
+});
diff --git a/builder/web/src/lib/trailview/structures/structures.ts b/builder/web/src/lib/trailview/structures/structures.ts
index acbe49bdd1..9746a55cb2 100644
--- a/builder/web/src/lib/trailview/structures/structures.ts
+++ b/builder/web/src/lib/trailview/structures/structures.ts
@@ -7,7 +7,7 @@ import { metresPerUnit } from '../terrain/bins';
 import { key, OWNER, size, type Node } from '../terrain/lod';
 import type { Stamps } from '../terrain/stamps';
 import { ANCHOR_WORDS, ANCHORED_VERTEX } from './anchored';
-import { STRUCTURE_VERTEX } from './mesh';
+import { STRUCTURE_VERTEX, type StructureMesh } from './mesh';
 import { FLOOR, type NodeMeshes } from './node';
 import { Pool, type Mesh } from './pool';
 
@@ -15,7 +15,7 @@ import { Pool, type Mesh } from './pool';
  * The structure meshes and the anchored meshes on the GPU, fixed pools; the anchors of the anchored
  * meshes that a frame draws, and their heights.
  */
-const VERTEX_BYTES = 8 * 2 ** 20, INDEX_BYTES = 4 * 2 ** 20, ANCHORED_BYTES = 6 * 2 ** 20, ANCHORED_INDEX_BYTES = 3 * 2 ** 20, ANCHORS = 2 ** 16;
+const VERTEX_BYTES = 16 * 2 ** 20, INDEX_BYTES = 8 * 2 ** 20, ANCHORED_BYTES = 6 * 2 ** 20, ANCHORED_INDEX_BYTES = 3 * 2 ** 20, ANCHORS = 2 ** 16;
 /**
  * A floor reaches this far past the ends of its segments: off a deck or out of a tunnel the ground holds
  * the road's height, and the probe of the ground under the eye, a few frames late, catches up meanwhile.
@@ -30,6 +30,9 @@ interface Resources {
     device: GPUDevice;
     pipeline: GPURenderPipeline;
     anchoredPipeline: GPURenderPipeline;
+    /** A bridge's faces with the ground plan: gone where its meshes draw the storeys (structures.wgsl), and as casters. */
+    bridges: GPURenderPipeline;
+    bridgeCaster: GPURenderPipeline;
     /** The pipelines of the structure and the anchored meshes as casters of the shadow map, with the group of the sun's frame. */
     casters: [GPURenderPipeline, GPURenderPipeline];
     sunGroup: GPUBindGroup;
@@ -50,7 +53,7 @@ interface Resources {
  */
 export class Structures {
     private resources?: Resources;
-    private draws: Mesh[] = [];
+    private draws: StructureMesh[] = [];
     /** The anchored meshes of the frame, with the first anchor of their node. */
     private hung: { mesh: Mesh; anchor: number }[] = [];
     private anchorWords = new Uint32Array(0);
@@ -58,6 +61,8 @@ export class Structures {
     points: Uint32Array[] = [];
     /** The meshes of the drawn owners, and whether each is near: the last frame's, to compare. */
     private drawn: { meshes: NodeMeshes; near: boolean }[] = [];
+    /** The far structure mesh of each owner node of the frame that has its meshes, by key. */
+    private owned = new Map();
     /** The anchored meshes of the frame whose anchors did not fit. */
     private unanchored = 0;
     /** Whether the anchors of the frame are not on the GPU yet. */
@@ -70,10 +75,13 @@ export class Structures {
         return (this.resources?.structures.dropped ?? 0) + (this.resources?.anchored.dropped ?? 0) + this.unanchored;
     }
 
-    /** `frames` are the frame uniforms of the eye's view and of the sun's (light/shadow.ts); `portals` the terrain's boxes of the tunnels' portals. */
-    async attach(gpu: Gpu, [frame, sunFrame]: GPUBuffer[], portals: GPUBuffer): Promise {
+    /**
+     * `frames` are the frame uniforms of the eye's view and of the sun's (light/shadow.ts); `portals` the terrain's boxes of the tunnels'
+     * portals; `cells` the cells whose ground-plan meshes draw (plan/cells.wgsl).
+     */
+    async attach(gpu: Gpu, [frame, sunFrame]: GPUBuffer[], portals: GPUBuffer, cells: GPUBuffer): Promise {
         this.resources = undefined;
-        const { device } = gpu, { layout, empty, computeLayout, pipelines: [pipeline, anchoredPipeline, heightsPipeline, structureCaster, anchoredCaster] } = await gpu.once(structurePipelines);
+        const { device } = gpu, { layout, empty, computeLayout, pipelines: [pipeline, anchoredPipeline, heightsPipeline, structureCaster, anchoredCaster, bridges, bridgeCaster] } = await gpu.once(structurePipelines);
         const anchors = gpu.buffer('kinds', ANCHORS * ANCHOR_WORDS * 4, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST);
         const heights = gpu.buffer('kinds', ANCHORS * 8, GPUBufferUsage.STORAGE);
         const count = gpu.buffer('kinds', 16, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST);
@@ -81,9 +89,9 @@ export class Structures {
             new Pool(device, gpu.buffer(label, vertexBytes, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST), gpu.buffer(label, indexBytes, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST), 4 * stride);
         this.drawn = [];
         this.fresh = true;
-        const frameGroup = (frame: GPUBuffer) => device.createBindGroup({ layout, entries: [[0, frame], [1, anchors], [4, heights], [5, portals]].map(([binding, buffer]) => ({ binding: binding as number, resource: { buffer: buffer as GPUBuffer } })) });
+        const frameGroup = (frame: GPUBuffer) => device.createBindGroup({ layout, entries: [[0, frame], [1, anchors], [4, heights], [5, portals], [6, cells]].map(([binding, buffer]) => ({ binding: binding as number, resource: { buffer: buffer as GPUBuffer } })) });
         this.resources = {
-            device, pipeline, anchoredPipeline, casters: [structureCaster, anchoredCaster], heightsPipeline, anchors, count,
+            device, pipeline, anchoredPipeline, bridges, bridgeCaster, casters: [structureCaster, anchoredCaster], heightsPipeline, anchors, count,
             group: frameGroup(frame), sunGroup: frameGroup(sunFrame),
             emptyGroup: device.createBindGroup({ layout: empty, entries: [] }),
             computeGroup: device.createBindGroup({ layout: computeLayout, entries: [frame, anchors, heights, count].map((buffer, binding) => ({ binding, resource: { buffer } })) }),
@@ -108,10 +116,16 @@ export class Structures {
         for (let y = Math.floor((eye.y - reach) / side); y <= Math.floor((eye.y + reach) / side); y++) {
             for (let x = Math.floor((eye.x - reach) / side); x <= Math.floor((eye.x + reach) / side); x++) owners.set(key({ level: OWNER, x, y }), { node: { level: OWNER, x, y }, near: true });
         }
+        // Nearest first: the pools and the anchors give room in this order, so where they are full the farthest meshes drop,
+        // whatever node the terrain draws first.
+        const away = ({ x, y }: Node) => Math.hypot(Math.max(x * side - eye.x, 0, eye.x - (x + 1) * side), Math.max(y * side - eye.y, 0, eye.y - (y + 1) * side));
         const now: { meshes: NodeMeshes; near: boolean }[] = [];
-        for (const { node, near } of owners.values()) {
+        this.owned = new Map();
+        for (const { node, near } of [...owners.values()].sort((a, b) => away(a.node) - away(b.node))) {
             const meshes = this.stamps.get(node)?.meshes;
-            if (meshes) now.push({ meshes, near });
+            if (!meshes) continue;
+            now.push({ meshes, near });
+            this.owned.set(key(node), meshes.far.structures);
         }
         if (now.length === this.drawn.length && now.every((o, i) => o.meshes === this.drawn[i].meshes && o.near === this.drawn[i].near)) return false;
         this.drawn = now;
@@ -164,6 +178,15 @@ export class Structures {
         return best;
     }
 
+    /**
+     * Whether the owner node at world point x, y has its far structure mesh in the pool after this frame's `write`: the mesh
+     * with its tunnels' bores and portals.
+     */
+    holds(x: number, y: number): boolean {
+        const side = size(OWNER), mesh = this.owned.get(key({ level: OWNER, x: Math.floor(x / side), y: Math.floor(y / side) }));
+        return !!mesh && !!this.resources?.structures.at(mesh);
+    }
+
     /** Uploads the meshes that the pools lack, and the anchors of the frame. */
     write(): void {
         const r = this.resources;
@@ -190,25 +213,34 @@ export class Structures {
 
     draw(pass: GPURenderPassEncoder, surfaceGroup: GPUBindGroup, ground: GPUBindGroup, features: GPUBindGroup): void {
         const r = this.resources;
-        if (r) this.drawWith(pass, [r.group, surfaceGroup, ground, features], r.pipeline, r.anchoredPipeline);
+        if (r) this.drawWith(pass, [r.group, surfaceGroup, ground, features], r.pipeline, r.anchoredPipeline, r.bridges);
     }
 
     /** Draws the meshes into the shadow map (light/shadow.ts) as casters. */
     cast(pass: GPURenderPassEncoder, surfaceGroup: GPUBindGroup, features: GPUBindGroup): void {
         const r = this.resources;
-        if (r) this.drawWith(pass, [r.sunGroup, surfaceGroup, r.emptyGroup, features], ...r.casters);
+        if (r) this.drawWith(pass, [r.sunGroup, surfaceGroup, r.emptyGroup, features], ...r.casters, r.bridgeCaster);
     }
 
-    private drawWith(pass: GPURenderPassEncoder, groups: GPUBindGroup[], structures: GPURenderPipeline, anchored: GPURenderPipeline): void {
+    private drawWith(pass: GPURenderPassEncoder, groups: GPUBindGroup[], structures: GPURenderPipeline, anchored: GPURenderPipeline, bridges: GPURenderPipeline): void {
         const r = this.resources!;
         if (!this.draws.length && !this.hung.length) return;
         groups.forEach((group, k) => pass.setBindGroup(k, group));
-        pass.setPipeline(structures);
         pass.setVertexBuffer(0, r.structures.vertices);
         pass.setIndexBuffer(r.structures.indices, 'uint32');
+        // With the ground plan, a bridge's faces draw with their own pipeline and its abutments not at all.
+        const plan = this.stamps.plan, own = (mesh: StructureMesh) => mesh.indices.length - (plan ? (mesh.offPlan ?? 0) + (mesh.decks ?? 0) : 0);
+        pass.setPipeline(structures);
         for (const mesh of this.draws) {
             const at = r.structures.at(mesh);
-            if (at) pass.drawIndexed(mesh.indices.length, 1, at.first, at.base);
+            if (at && own(mesh)) pass.drawIndexed(own(mesh), 1, at.first, at.base);
+        }
+        if (plan) {
+            pass.setPipeline(bridges);
+            for (const mesh of this.draws) {
+                const at = r.structures.at(mesh);
+                if (at && mesh.decks) pass.drawIndexed(mesh.decks, 1, at.first + own(mesh), at.base);
+            }
         }
         pass.setPipeline(anchored);
         pass.setVertexBuffer(0, r.anchored.vertices);
@@ -228,16 +260,18 @@ async function structurePipelines(gpu: Gpu) {
     const layout = device.createBindGroupLayout({ entries: [
         { binding: 0, visibility: VF, buffer: { type: 'uniform' } }, { binding: 1, visibility: GPUShaderStage.VERTEX, buffer: { type: 'read-only-storage' } },
         { binding: 4, visibility: GPUShaderStage.VERTEX, buffer: { type: 'read-only-storage' } }, { binding: 5, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'read-only-storage' } },
+        { binding: 6, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'read-only-storage' } },
     ] });
     const empty = device.createBindGroupLayout({ entries: [] }), computeLayout = device.createBindGroupLayout({ entries: [
         { binding: 0, visibility: C, buffer: { type: 'uniform' } }, { binding: 1, visibility: C, buffer: { type: 'read-only-storage' } },
         { binding: 2, visibility: C, buffer: { type: 'storage' } }, { binding: 3, visibility: C, buffer: { type: 'uniform' } },
     ] });
-    const module = device.createShaderModule({ label: 'structures', code: wgsl('structures/structures.wgsl') });
+    // The cells whose ground-plan meshes draw, at a binding of the structures' group.
+    const module = device.createShaderModule({ label: 'structures', code: wgsl('structures/structures.wgsl', { 'plan/cells-buffer.wgsl': 'structures/plan-cells.wgsl' }) });
     const pipelineLayout = device.createPipelineLayout({ bindGroupLayouts: [layout, surface, ground, features] });
-    const render = (entryPoint: string, buffers: GPUVertexBufferLayout[], cullMode: GPUCullMode) => device.createRenderPipelineAsync({
-        label: entryPoint, layout: pipelineLayout, vertex: { module, entryPoint, buffers },
-        fragment: { module, entryPoint: 'structure_fragment', targets: [{ format: sceneFormat(gpu) }] },
+    const render = (entryPoint: string, buffers: GPUVertexBufferLayout[], cullMode: GPUCullMode, bridges = false) => device.createRenderPipelineAsync({
+        label: `${entryPoint}${bridges ? ' bridges' : ''}`, layout: pipelineLayout, vertex: { module, entryPoint, buffers },
+        fragment: { module, entryPoint: 'structure_fragment', targets: [{ format: sceneFormat(gpu) }], constants: { BRIDGES: +bridges } },
         primitive: { topology: 'triangle-list', cullMode },
         depthStencil: { format: DEPTH, depthWriteEnabled: true, depthCompare: 'greater' },
     });
@@ -267,6 +301,11 @@ async function structurePipelines(gpu: Gpu) {
             compute: { module, entryPoint: 'anchor_heights' },
         }),
         caster('structure_vertex', structureVertices), caster('anchored_caster', anchoredVertices),
+        render('structure_vertex', structureVertices, 'back', true),
+        device.createRenderPipelineAsync({
+            label: 'structure_vertex bridges caster', layout: casterLayout, vertex: { module, entryPoint: 'structure_vertex', buffers: structureVertices },
+            fragment: { module, entryPoint: 'bridge_caster', targets: [] }, primitive: CASTER_PRIMITIVE, depthStencil: CASTER_DEPTH,
+        }),
     ]);
     return { layout, empty, computeLayout, pipelines };
 }
diff --git a/builder/web/src/lib/trailview/structures/structures.wgsl b/builder/web/src/lib/trailview/structures/structures.wgsl
index 610955a7ae..9a1bcadfbf 100644
--- a/builder/web/src/lib/trailview/structures/structures.wgsl
+++ b/builder/web/src/lib/trailview/structures/structures.wgsl
@@ -6,6 +6,7 @@
 // #include ../terrain/drawn-mesh.wgsl
 // #include ../terrain/portal-box.wgsl
 // #include ../ground/look.wgsl
+// #include ../plan/cells.wgsl
 
 // As Frame and Node of terrain.wgsl, which share their buffers.
 struct Frame {
@@ -233,8 +234,15 @@ fn stones(p: vec3f, n: vec3f, pixel: f32) -> f32 {
     return mix(stone, 0.77, smoothstep(0.02, 0.08, pixel));
 }
 
+// A bridge's faces with the ground plan: where its meshes draw, their storeys draw the bridge, and these hand over to
+// them by the dither of a cut piece's fade.
+override BRIDGES: bool = false;
+
 @fragment
 fn structure_fragment(in: StructureOut) -> @location(0) vec4f {
+    if (BRIDGES && dither(in.clip.xy + PLAN_DITHER) < plan_share(in.u)) {
+        discard;
+    }
     var n = normalize(cross(dpdx(in.relative), dpdy(in.relative)));
     n *= -sign(dot(n, in.relative));
     let flags = u32(round(in.colour.a * 255.0));
@@ -275,3 +283,11 @@ fn structure_fragment(in: StructureOut) -> @location(0) vec4f {
     }
     return vec4f(atmosphere(lit, in.relative, in.altitude), 1.0);
 }
+
+// A bridge's faces as casters with the ground plan: none where the storeys of its meshes cast.
+@fragment
+fn bridge_caster(in: StructureOut) {
+    if (plan_share(in.u) > 0.5) {
+        discard;
+    }
+}
diff --git a/builder/web/src/lib/trailview/structures/tunnels.ts b/builder/web/src/lib/trailview/structures/tunnels.ts
index ac6c2e46d7..117b18565e 100644
--- a/builder/web/src/lib/trailview/structures/tunnels.ts
+++ b/builder/web/src/lib/trailview/structures/tunnels.ts
@@ -45,12 +45,17 @@ const TWIN_M = 8;
  */
 export type Twin = { shift: number; widen: number } | null;
 
+/** The twins of each tile's lines, made once: each node of the tile reads them. */
+const paired = new WeakMap>();
+
 /**
  * Per tunnel line of a track, the twins of its two ends that meet the ground: two such ends of two tracks'
  * tunnels that lie side by side within TWIN_M and lead the same way are one portal, which the end that
  * comes first by its point draws. The nearest pairs pair first, and an end has at most one twin.
  */
 export function twins(lines: Line[]): Map {
+    const known = paired.get(lines);
+    if (known) return known;
     const ends = lines.filter(line => line.kind === TUNNEL && line.abut && line.code >= RAIL_CODE).flatMap(line => [0, 1].filter(end => line.abut![end]).map(end => {
         const n = line.z.length, v = end ? n - 1 : 0, w = end ? n - 2 : 1, x = line.xy[2 * v], y = line.xy[2 * v + 1];
         const dx = line.xy[2 * w] - x, dy = line.xy[2 * w + 1] - y, l = Math.hypot(dx, dy) || 1;
@@ -69,6 +74,7 @@ export function twins(lines: Line[]): Map {
         (out.get(a.line) ?? out.set(a.line, [undefined, undefined]).get(a.line)!)[a.end] = { shift: across / 2, widen: Math.abs(across) / 2 };
         (out.get(b.line) ?? out.set(b.line, [undefined, undefined]).get(b.line)!)[b.end] = null;
     }
+    paired.set(lines, out);
     return out;
 }
 
diff --git a/builder/web/src/lib/trailview/terrain/bins.test.ts b/builder/web/src/lib/trailview/terrain/bins.test.ts
index a8ecfc5cbe..37f898fe03 100644
--- a/builder/web/src/lib/trailview/terrain/bins.test.ts
+++ b/builder/web/src/lib/trailview/terrain/bins.test.ts
@@ -2,16 +2,19 @@ import { readFileSync } from 'node:fs';
 import { gunzipSync } from 'node:zlib';
 import { describe, expect, it } from 'vitest';
 import KINDS from '../../../../../../data/trailview/kinds.json' with { type: 'json' };
+import FINISHES from '../../../../../../data/trailview/finishes.json' with { type: 'json' };
 import CLASS_RULES from '../../../../../../data/trailview/roads.json' with { type: 'json' };
 import WATERWAYS from '../../../../../../data/trailview/waterways.json' with { type: 'json' };
 import { functionOf, shaderFunctions } from '../gpu/shader-functions';
 import { decodeFeatures, EXTENT, SIDE_BACK, SIDE_ON, unitScale, type Feature } from '../stream/features';
 import { PAGE } from '../stream/heights';
 import { auditSamples, IN_WATER, roadHeight, SAMPLE } from './audit-samples';
-import { BRIDGE, CELL, cellAt, CORNER, crosses, crossSlope, DRIVEWAY, EDGE, features, gateTexel, GRID, halfWidth, INSIDE, insideRings, isPath, JUNCTION, junctions, junctionWays, LAKE, metresPerUnit, NEAR, nodeStamps, PATH, ringsDistance, smoothed, PROFILE_FLOATS, PROFILE_ROWS, PROFILES, profileTable, RAIL_CODE, RECORD, RIVER, ROAD, RULES, SEA, seaShows, SHOULDER_M, shows, SLEEPER_M, STREAM, surfaceOf, SURFACE_CODES, SURFACES, AREA, TUNNEL, WARP_M, waterAt, type Line, type Profile } from './bins';
+import { BRIDGE, CELL, cellAt, CORNER, crosses, crossSlope, DRIVEWAY, EDGE, features, fronts, gateTexel, GRID, halfWidth, INSIDE, insideRings, isPath, JUNCTION, junctions, junctionWays, LAKE, linesNear, metresPerUnit, NEAR, nodeStamps, PATH, ringsDistance, smoothed, PROFILE_FLOATS, PROFILE_ROWS, PROFILES, profileTable, RAIL_CODE, RECORD, RIVER, ROAD, RULES, SEA, seaShows, SHOULDER_M, shows, SLEEPER_M, STREAM, surfaceOf, SURFACE_CODES, SURFACES, AREA, trackSurface, TUNNEL, WARP_M, waterAt, type Line, type Profile, type Shapes } from './bins';
+import { SPILL_M } from '../roads/section';
 import { cornersOf, halfAt, partnersOf } from './corners';
 import { FOOT_HALF_M, GIVE_WAY_M } from './culverts';
 import { LEFT, RIGHT } from './town';
+import { waterMesh } from './water-mesh';
 
 const shader = readFileSync(new URL('./stamp-core.wgsl', import.meta.url), 'utf8');
 const fixture = (z: number, x: number, y: number) =>
@@ -107,8 +110,7 @@ describe('the stamp data of a node', { timeout: 30_000 }, () => {
     });
 
     it('rounds the top of a cut and the foot of a fill far from the road, and keeps the crease beside it', () => {
-        const stamp = readFileSync(new URL('./stamp.wgsl', import.meta.url), 'utf8');
-        const { rounded } = shaderFunctions<{ rounded: (base: number, s: object) => number }>(stamp, ['rounded']);
+        const { rounded } = shaderFunctions<{ rounded: (base: number, s: object) => number }>(shader, ['rounded']);
         const cut = (x: number) => ({ cut: true, hi: 10, cut_x: x, fill: false }), fill = (x: number) => ({ fill: true, lo: 10, fill_x: x, cut: false });
         // Beside the road the slope meets the ground in a crease: the bound and nothing else.
         expect([rounded(12, cut(1)), rounded(9, cut(1)), rounded(8, fill(1)), rounded(11, fill(1))]).toEqual([10, 9, 10, 11]);
@@ -119,7 +121,9 @@ describe('the stamp data of a node', { timeout: 30_000 }, () => {
         // It never falls as the base rises.
         for (let base = 8; base < 12; base += 0.05) expect(rounded(base + 0.05, cut(5))).toBeGreaterThanOrEqual(rounded(base, cut(5)) - 1e-9);
         // The stamp pass takes the ground from it, then clamps.
-        expect(functionOf(stamp, 'stamp')).toMatch(/h = select\(NONE, clamp\(rounded\(base, s\), s\.lo, s\.hi\), known\(base\)\);/);
+        expect(functionOf(shader, 'stamped_ground')).toMatch(/return clamp\(rounded\(base, s\), s\.lo, s\.hi\);/);
+        const stamp = readFileSync(new URL('./stamp.wgsl', import.meta.url), 'utf8');
+        expect(functionOf(stamp, 'stamp')).toMatch(/ground = select\(NONE, stamped_ground\(base, s\), known\(base\)\);/);
     });
 
     it('marks a shoulder in the byte of a sidewalk, and the paint and the snap each read the part that is theirs', () => {
@@ -136,7 +140,7 @@ describe('the stamp data of a node', { timeout: 30_000 }, () => {
         const stamp = readFileSync(new URL('./stamp.wgsl', import.meta.url), 'utf8'), mask = readFileSync(new URL('./features.wgsl', import.meta.url), 'utf8');
         expect(functionOf(stamp, 'stamp')).toContain('walk_byte(s.walk, s.shoulder, s.trodden, s.marked)');
         expect(functionOf(stamp, 'snap')).toMatch(/walk = max\(walk, walk_metres\(wide\)\);\s+shoulder = max\(shoulder, select\(0\.0, shoulder_of\(surface\), holds_shoulder\(wide\)\)\);/);
-        expect(functionOf(mask, 'mask_at')).toMatch(/walk_metres\(past\), is_trodden\(past\), is_marked\(past\)/);
+        expect(functionOf(mask, 'mask_in')).toMatch(/walk_metres\(past\), is_trodden\(past\), is_marked\(past\)/);
         // Only a plain road marks it, and a corner's arc takes it away.
         const body = functionOf(shader, 'stamp_at');
         expect(body).toContain('let plain = kind == ROAD && walk == 0.0 && !gallery && road_shows(own, rule, level);');
@@ -144,6 +148,32 @@ describe('the stamp data of a node', { timeout: 30_000 }, () => {
         expect(body.match(/out\.shoulder = false;/g)).toHaveLength(2);
     });
 
+    it('keeps the material of the painted way in the paint, and paints a way without one as before', () => {
+        const source = ['./records.wgsl', './stamp-core.wgsl', './mask-walk.wgsl', './stamp.wgsl'].map(file => readFileSync(new URL(file, import.meta.url), 'utf8')).join('\n');
+        const scope = globalThis as Record, helpers = {
+            painted_finish: (mp: { finish: number }) => mp.finish, asinh: Math.asinh, fract: (x: number) => x - Math.floor(x),
+            clamp: (x: number, lo: number, hi: number) => Math.min(Math.max(x, lo), hi), vec4f: (...v: number[]) => v,
+        };
+        Object.assign(scope, helpers);
+        try {
+            const { paint_texel: paint } = shaderFunctions<{ paint_texel: (mp: object) => number[] }>(source, ['paint_texel', 'distance_code', 'walk_byte']);
+            const MARKED = 512, NONE = 0xffffffff;
+            for (const code of Object.values(SURFACES).map((_, i) => i + 1)) for (const flags of [0, MARKED]) for (const material of [1, 2, 3, 4]) {
+                const way = (m: number, painted = 0) => ({ block: 1, painted, d_paved: -1.2, across: 2.5, along: 7.3, finish: code | flags | (m << 16) });
+                const [plain, worn] = [paint(way(0)), paint(way(material))];
+                // The finish code alone, as before, in a way without a material; the material above it in a way with one.
+                expect(Math.round(plain[3] * 255)).toBe(code === 2 ? 1 : code);
+                expect(Math.round(worn[3] * 255)).toBe((code === 2 ? 1 : code) | (material << 4));
+                expect(worn.slice(0, 3)).toEqual(plain.slice(0, 3));
+                // No paint, no material.
+                expect(paint(way(material, NONE))).toEqual(paint(way(0, NONE)));
+                expect(paint(way(material, NONE))[3]).toBe(0);
+            }
+        } finally {
+            for (const name of Object.keys(helpers)) delete scope[name];
+        }
+    });
+
     it('shows a line on the levels where the gates of stamp-core.wgsl show it', () => {
         const gates = shaderGates(), seen = new Set();
         for (const [kind, profile] of [[ROAD, 0], [PATH, Object.keys(PROFILES).indexOf('path')], [RIVER, Object.keys(PROFILES).indexOf('river')]]) for (const h of [0.6, 2, 5, 12]) for (let level = 12; level <= 18; level++) {
@@ -191,6 +221,19 @@ describe('the stamp data of a node', { timeout: 30_000 }, () => {
         expect(held.mask).toBe(true);
     });
 
+    it('lists a segment whose box comes within the reach of a node only at its corner, and not one past the reach', () => {
+        const tile = { level: 13, x: 4287, y: 2889 }, node = { level: 18, x: tile.x * 32 + 10, y: tile.y * 32 + 10 }, shift = 22 - node.level, cell = CELL * 2 ** shift;
+        const x0 = node.x * PAGE * 2 ** shift - cell, y0 = node.y * PAGE * 2 ** shift - cell, reach = 40 / metresPerUnit(y0);
+        // North-west of the node, across the diagonal: the box's corner lies `share` of the reach from the node's corner on both axes, the segment far off.
+        const road = (share: number) => {
+            const ax = x0 - share * reach, ay = y0 - share * reach, world = [ax - 3000, ay, ax, ay - 3000];
+            return { kind: 'road', tags: { highway: 'tertiary' }, geometry: 'line' as const, parts: [{ outer: false, xy: Float32Array.from(world, (v, i) => v / 8 - (i % 2 ? tile.y : tile.x) * EXTENT), z: Float32Array.of(1000, 1000) }] };
+        };
+        const { data } = nodeStamps([road(0.9), road(1.5)], tile, node), corner = cellOf(data!, node, 0).entries;
+        expect(data![0]).toBe(1);
+        expect(Array.from(corner)).toEqual([0]);
+    });
+
     it('takes the points inside the buildings and the river areas, from each cell origin and the edges that the cell lists', () => {
         // Engelberg: a level-17 node on the river through the village.
         const tile = { level: 13, x: 4287, y: 2887 }, list = fixture(tile.level, tile.x, tile.y), { areas, buildings } = features(list, tile);
@@ -268,6 +311,31 @@ describe('the stamp data of a node', { timeout: 30_000 }, () => {
             expect(waterAt(data!, NODE, p[0], p[1])).toBe(sea ? 0 : -Infinity);
         }
     });
+
+    it('numbers the lines with records per node in a tile past the 16-bit index, and leaves a node with more of them empty and counted', () => {
+        // A level-17 node spans 1024 tile units; 65,537 paths in the tile's far corner come between the bridge and the river.
+        const tile = { level: 13, x: 4287, y: 2889 }, node = { level: 17, x: tile.x * 16 + 8, y: tile.y * 16 + 8 };
+        const line = (kind: string, tags: Record, ...parts: number[][]) =>
+            ({ kind, tags, geometry: 'line' as const, parts: parts.map(xy => ({ outer: false, xy: Float32Array.from(xy), z: new Float32Array(xy.length / 2).fill(1000) })) });
+        const paths = Array.from({ length: 0x10001 }, (_, i) => [100 + (i % 256) * 8, 100 + Math.floor(i / 256) * 8, 104 + (i % 256) * 8, 100 + Math.floor(i / 256) * 8]);
+        const list = [
+            { kind: 'lake', tags: {}, geometry: 'area' as const, parts: [{ outer: true, xy: Int32Array.from([8600, 8600, 8800, 8600, 8800, 8800, 8600, 8800]), z: Float32Array.of(990) }] },
+            line('road', { highway: 'tertiary', bridge: 'yes' }, [8200, 8500, 9200, 8500]), line('path', { highway: 'path' }, ...paths), line('river', { waterway: 'river' }, [8200, 8900, 9200, 8900]),
+        ];
+        expect(features(list, tile).lines.length).toBe(0x10001 + 2);
+        for (const plan of [false, true]) {
+            const { data, limits } = nodeStamps(list, tile, node, plan), records = 2 + GRID * GRID + 1 + data![1];
+            const word = (r: number, i: number) => data![records + RECORD * r + i], all = Array.from({ length: data![0] }, (_, r) => r);
+            expect(limits).toBeUndefined();
+            // With `plan` a bridge has no record on a near level: the records hold the ground under it.
+            expect([BRIDGE, LAKE, RIVER].map(kind => all.some(r => word(r, 4) === kind))).toEqual([!plan, true, true]);
+            const kinds = plan ? [RIVER] : [BRIDGE, RIVER];
+            expect(kinds.map(kind => word(all.find(r => word(r, 4) === kind)!, 13) & 0xffff)).toEqual(plan ? [0] : [0, 1]);
+        }
+        expect(waterMesh(list, tile, node)!.lakes).toBeGreaterThan(0);
+        // Over the paths, a level-16 node holds 65,537 lines with records: their records alone pass STAMP_WORDS.
+        expect(nodeStamps(list, tile, { level: 16, x: tile.x * 8, y: tile.y * 8 })).toEqual({ data: null, heights: false, mask: false, limits: 1 });
+    });
 });
 
 describe('the audit of the sea', () => {
@@ -491,6 +559,14 @@ describe('the ends of bridges and tunnels', () => {
         ], { level: 14, x: 8574, y: 5778 });
         expect(lines.filter(line => line.kind === BRIDGE || line.kind === TUNNEL).map(line => line.abut)).toEqual([[true, true], [true, false], [false, false]]);
     });
+
+    it('take a passage through a building of kind `tunnel` as a way of its class, and a tunnel as a bore', () => {
+        const way = (tunnel: string) =>
+            ({ kind: 'tunnel', tags: { highway: 'residential', tunnel }, geometry: 'line' as const, parts: [{ outer: false, xy: Int32Array.from([1000, 4000, 2000, 4000]), z: Float32Array.from([500, 500]) }] });
+        const kinds = (tunnel: string) => features([way(tunnel)], { level: 14, x: 8574, y: 5778 }).lines.map(line => line.kind);
+        expect(kinds('building_passage')).toEqual([ROAD]);
+        expect(kinds('yes')).toEqual([TUNNEL]);
+    });
 });
 
 describe('a waterway', () => {
@@ -499,10 +575,10 @@ describe('a waterway', () => {
         expect(Object.keys(WATERWAYS).sort()).toEqual(values.sort());
         // PROFILES keys both files by name: a name in both would replace a class's row.
         expect(Object.keys(WATERWAYS).filter(name => Object.hasOwn(CLASS_RULES, name))).toEqual([]);
-        for (const [value, { width_m, cover_m, cover_lift_max_m, culvert_max_m, ...row }] of Object.entries(WATERWAYS)) {
+        for (const [value, { width_m, cover_m, cover_lift_max_m, culvert_max_m, tol, reach, least, cut, fill }] of Object.entries(WATERWAYS)) {
             expect(width_m, value).toBeGreaterThan(0);
             expect(Math.min(cover_m, cover_lift_max_m, culvert_max_m), value).toBeGreaterThanOrEqual(0);
-            expect(PROFILES[value], value).toEqual({ ...row, tilt: 0, walk: 0, ditch: 0 });
+            expect(PROFILES[value], value).toEqual({ tol, reach, least, cut, fill, tilt: 0, walk: 0, ditch: 0 });
         }
         const line = (kind: string, tags: Record) =>
             features([{ kind, tags, geometry: 'line', parts: [{ outer: false, xy: Int32Array.from([1000, 4000, 5000, 4000]), z: Float32Array.from([1001, 1000]) }] }], TILE).lines[0];
@@ -513,16 +589,10 @@ describe('a waterway', () => {
 });
 
 describe('a path', () => {
-    it('without a `width` tag is on its widest surface as wide as the bake takes it, and a pedestrian bridge is a path', () => {
-        const rust = readFileSync(new URL('../../../../../../host/obc-trailview-features/src/structures.rs', import.meta.url), 'utf8');
-        const block = /^const PATH_HALF_M: [^=]+= \[([^\]]*)\];$/m.exec(rust)![1];
-        const table: Record = Object.fromEntries([...block.matchAll(/\("([a-z_]+)", ([0-9.]+)\)/g)].map(([, highway, half]) => [highway, Number(half)]));
-        expect(Object.keys(table).length).toBeGreaterThan(5);
-        for (const [highway, half] of Object.entries(table)) {
-            const widest = Math.max(...['', 'asphalt', 'gravel', 'dirt', 'grass'].map(surface => halfWidth({ highway, surface }, surfaceOf({ highway, surface }))));
-            expect(widest, highway).toBe(half);
-            expect(isPath({ profile: Object.keys(PROFILES).indexOf(highway) } as Line), highway).toBe(true);
-        }
+    it('is a class of roads.json from `path` on, and a pedestrian bridge is a path', () => {
+        const classes = Object.keys(CLASS_RULES), paths = classes.slice(classes.indexOf('path'));
+        expect(paths.length).toBeGreaterThan(5);
+        for (const highway of paths) expect(isPath({ profile: Object.keys(PROFILES).indexOf(highway) } as Line), highway).toBe(true);
         expect(isPath({ profile: Object.keys(PROFILES).indexOf('track') } as Line)).toBe(false);
     });
 });
@@ -613,7 +683,7 @@ describe('a town', () => {
     });
 
     it('fronts a house with its wall that faces the road, but for a house that a road reaches or none comes near', () => {
-        const frontOf = (gap: number) => features([road, house(gap)], tile).buildings[0].front;
+        const frontOf = (gap: number) => fronts([road, house(gap)], tile)[0];
         expect(frontOf(15)).toEqual([0, -1]);
         expect(frontOf(1)).toBeUndefined();
         expect(frontOf(25)).toBeUndefined();
@@ -634,3 +704,81 @@ describe('a town', () => {
         expect(walks('service')).toEqual([[0, 1.5], [0, 1.5]]);
     });
 });
+
+describe('the cross-section table of the ground plan', () => {
+    const TRACKS = ['rail', 'light_rail', 'narrow_gauge', 'funicular'], PATHS = ['path', 'footway', 'cycleway', 'bridleway', 'steps', 'pedestrian', 'via_ferrata'];
+    const rows = CLASS_RULES as Record;
+    const caps = FINISHES as Record;
+    const capped = (value: number, cap: number | null) => (cap === null ? value : Math.min(value, cap));
+    /** The rules of host/obc-ground-plan/src/sections.rs on the two tables. */
+    const tables = (kind: string, tags: Record, town: boolean) => {
+        const track = TRACKS.includes(tags.railway) && !tags.highway;
+        const name = track ? (tags.rack && tags.rack !== 'no' ? 'rack' : tags.railway) : (tags.highway ?? '');
+        const row = rows[name] ?? rows[kind === 'path' ? 'path' : 'road'], finish = track ? trackSurface(tags) : surfaceOf(tags, town);
+        const width = parseFloat(tags.width ?? '');
+        const half = !track && Number.isFinite(width) ? Math.max(width / 2, 0.4) : capped(row.half_m, caps[finish].half_m);
+        return { half: Math.min(half, 15), shoulder: capped(row.shoulder_m, caps[finish].shoulder_m) };
+    };
+
+    it('gives the half-width and the shoulder of the viewer for every class', () => {
+        const variants: Record[] = [{}, { surface: 'asphalt' }, { surface: 'gravel' }, { surface: 'dirt' }, { surface: 'grass' }, { tracktype: 'grade1' }, { tracktype: 'grade2' }, { tracktype: 'grade3' }];
+        for (const name of Object.keys(CLASS_RULES)) for (const variant of variants) for (const town of [false, true]) {
+            const base: Record = name === 'rack' ? { railway: 'rail', rack: 'yes' } : TRACKS.includes(name) ? { railway: name } : { highway: name };
+            const tags = { ...base, ...variant }, track = !tags.highway, path = PATHS.includes(name);
+            const surface = track ? trackSurface(tags) : surfaceOf(tags, town);
+            const viewer = { half: track ? SURFACES[surface] : halfWidth(tags, surface), shoulder: track ? SPILL_M : path ? 0 : (SHOULDER_M[surface] ?? 0) };
+            expect(tables(track ? 'railway' : path ? 'path' : 'road', tags, town), `${JSON.stringify(tags)} ${town}`).toEqual(viewer);
+        }
+    });
+
+    it('lists the finishes in the order of the surface codes, with the values of the viewer', () => {
+        const BEDS = ['rail', 'narrow', 'rack', 'narrow-rack'];
+        expect(Object.keys(FINISHES)).toEqual(Object.keys(SURFACES));
+        for (const [finish, { half_m, shoulder_m }] of Object.entries(caps)) {
+            if (half_m !== null) expect(half_m, finish).toBe(SURFACES[finish as keyof typeof SURFACES]);
+            if (shoulder_m !== null) expect(shoulder_m, finish).toBe(BEDS.includes(finish) ? SPILL_M : (SHOULDER_M[finish as keyof typeof SURFACES] ?? 0));
+        }
+    });
+});
+
+describe('the lines near a point', () => {
+    /** A steady value in [0, 1) for each call. */
+    const random = (seed => () => (seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31)(7);
+    const tileOf = (lines: Line[]) => ({ lines, lakes: [], seas: [], pads: [], areas: [], buildings: [] }) as unknown as Shapes;
+    const way = (xy: number[]) => ({ kind: ROAD, xy, z: xy.filter((_, i) => i % 2 === 0).map(() => 0), h: 2.5, code: 2, ford: false, profile: 0 }) as Line;
+    /** The world units from a point to the nearest segment of a line. */
+    const distance = ({ xy }: Line, x: number, y: number) => {
+        let best = Infinity;
+        for (let i = 0; i + 3 < xy.length; i += 2) {
+            const dx = xy[i + 2] - xy[i], dy = xy[i + 3] - xy[i + 1], t = Math.min(1, Math.max(0, ((x - xy[i]) * dx + (y - xy[i + 1]) * dy) / (dx * dx + dy * dy || 1)));
+            best = Math.min(best, Math.hypot(xy[i] + t * dx - x, xy[i + 1] + t * dy - y));
+        }
+        return best;
+    };
+
+    it('hold every line that a scan of all lines finds within reach, in the tile\'s order', () => {
+        // The index has cells of 2^13 units: a square of 20 cells, with its corner on a cell line.
+        const cell = 2 ** 13, x0 = 2 ** 29, y0 = 2 ** 29, side = 20 * cell, lines: Line[] = [];
+        for (let k = 0; k < 400; k++) {
+            const xy = [x0 + random() * side, y0 + random() * side];
+            for (let v = 1 + Math.floor(random() * 5); v > 0; v--) xy.push(xy[xy.length - 2] + (random() - 0.5) * 3 * cell, xy[xy.length - 2 + 1] + (random() - 0.5) * 3 * cell);
+            lines.push(way(xy));
+        }
+        // A segment without length, ways on a cell line and across every cell, and a way that ends on a corner of cells.
+        lines.push(way([x0 + 5.5 * cell, y0 + 5.5 * cell, x0 + 5.5 * cell, y0 + 5.5 * cell]), way([x0 + 3 * cell, y0, x0 + 3 * cell, y0 + side]), way([x0, y0 + 7 * cell, x0 + side, y0 + 7 * cell]), way([x0 + 2 * cell, y0 + 2 * cell, x0 + 2.5 * cell, y0 + 2.2 * cell]));
+        const shapes = tileOf(lines);
+        const points = Array.from({ length: 300 }, () => [x0 + (random() * 1.4 - 0.2) * side, y0 + (random() * 1.4 - 0.2) * side]);
+        // On a cell line, on a corner of cells, on the segment without length, and far outside the tile.
+        points.push([x0 + 3 * cell, y0 + 4.5 * cell], [x0 + 2 * cell, y0 + 2 * cell], [x0 + 5.5 * cell, y0 + 5.5 * cell], [x0 - 50 * cell, y0 + 300 * cell], [0, 0]);
+        let found = 0;
+        for (const [x, y] of points) for (const reach of [0, 40, 600, 2.5 * cell]) {
+            const near = linesNear(shapes, x, y, reach);
+            expect(near).toEqual([...near].sort((a, b) => a - b));
+            const scanned = lines.flatMap((line, k) => (distance(line, x, y) <= reach ? [k] : []));
+            expect(scanned.filter(k => !near.includes(k))).toEqual([]);
+            found += scanned.length;
+        }
+        expect(found).toBeGreaterThan(1000);
+        expect(linesNear(tileOf([]), x0, y0, 600)).toEqual([]);
+    });
+});
diff --git a/builder/web/src/lib/trailview/terrain/bins.ts b/builder/web/src/lib/trailview/terrain/bins.ts
index ad03621319..eab49d9c5c 100644
--- a/builder/web/src/lib/trailview/terrain/bins.ts
+++ b/builder/web/src/lib/trailview/terrain/bins.ts
@@ -59,7 +59,7 @@ export const PAVED_CODES = PAVED_ROADS.map(codeOf), ROAD_CODE = codeOf('road');
 const TOWN_PATHS = ['footway', 'pedestrian', 'cycleway', 'steps'];
 const PAVED: Record = { motorway: 6, trunk: 5, primary: 4, secondary: 3.25, tertiary: 3, unclassified: 2.5, residential: 2.5, service: 2, living_street: 2 };
 const MAIN = ['motorway', 'trunk', 'primary', 'secondary', 'motorway_link', 'trunk_link', 'primary_link'];
-/** The path classes and the widest half-width of each without a `width` tag, whatever its surface: a paved footway is not a road. As PATH_HALF_M of host/obc-trailview-features/src/structures.rs. */
+/** The path classes and the widest half-width of each without a `width` tag, whatever its surface: a paved footway is not a road. */
 const PATH_HALF: Record = { path: 1, footway: 1, cycleway: 1.5, bridleway: 1, steps: 1, pedestrian: 3, via_ferrata: 0.6 };
 /** OSM bridge values of a way that lies on the ground, as GROUND of host/obc-trailview-features/src/structures.rs. */
 const GROUND = ['no', 'boardwalk', 'low_water_crossing'];
@@ -96,10 +96,10 @@ export const PROFILES: Record = {
 const CLASSES = Object.keys(PROFILES);
 /** Classes that cross a town road's sidewalk, whose paint and mesh run on over them, and their bit in a segment's code byte, as DRIVEWAY of stamp-core.wgsl. */
 export const DRIVEWAYS = ['service', 'track'], DRIVEWAY = 64;
-/** Whether a way is a track, as `is_track` of host/obc-trailview-features/src/structures.rs: a `railway` of these and no `highway`. */
+/** Whether a way is a track, as `is_track` of host/obc-ground-plan/src/sections.rs: a `railway` of these and no `highway`. */
 const TRACKS = ['rail', 'narrow_gauge', 'light_rail', 'funicular'];
 const isTrack = (tags: Record) => TRACKS.includes(tags.railway) && !tags.highway;
-/** The class of a way, as `class_of` of host/obc-trailview-features/src/structures.rs: `rack` for a rack railway, else the `railway` of a track or its `highway`. */
+/** The class of a way, as `class_of` of host/obc-ground-plan/src/sections.rs: `rack` for a rack railway, else the `railway` of a track or its `highway`. */
 const classOf = (tags: Record) => (isTrack(tags) ? (tags.rack && tags.rack !== 'no' ? 'rack' : tags.railway) : tags.highway ?? '');
 /** The row of a line's class; a class that the table lacks takes the row of its kind. */
 const profileOf = (kind: string, name = '') => CLASSES.indexOf(Object.hasOwn(PROFILES, name) ? name : kind === 'path' ? 'path' : 'road');
@@ -220,8 +220,8 @@ export interface Line {
 export interface Barrier { xy: number[]; wall: boolean; height?: number }
 /** A lake: its level, and its rings in world units; a ring after an outer ring and before the next is its hole. */
 export interface Lake { level: number; rings: number[][]; outer: boolean[] }
-/** A building: the outward unit direction of the wall that faces its road, in world units. */
-export interface Building { rings: number[][]; outer: boolean[]; front?: [number, number] }
+/** A building's rings in world units. */
+export interface Building { rings: number[][]; outer: boolean[] }
 /**
  * The shapes of a tile: lines, lakes and the sea with heights, the river areas, which lie on the drawn
  * surface, the pads under the platforms and the buildings.
@@ -267,6 +267,87 @@ export function features(list: Feature[], tile: Node): Shapes {
     return known;
 }
 
+/**
+ * A tile's lines and outlines in grids of their boxes, made once per tile and released with its shapes: a node asks them
+ * for what comes near it, and a structure for the lines and the water near a point (`linesNear`).
+ * `reach` is the farthest in metres that a line's stamp acts past it, and `waterHalf` the widest half-width of a
+ * waterway. The outlines are the lakes, the seas, the pads, the river areas and the buildings, in that order; `seasFrom` and
+ * the others are the index of the first of each.
+ */
+export interface TileIndex { lines: Grid; reach: number; waterHalf: number; outlines: Grid & { seasFrom: number; padsFrom: number; areasFrom: number; buildingsFrom: number } }
+const indexes = new WeakMap();
+/**
+ * The cells of a tile's index, 2^13 world units (about 200 m in the Alps): a level-18 node asks a few, and a lake's box
+ * takes few. Most structures ask about a point with a reach of some tens of metres: one cell, or two to four at a cell's
+ * edge. `coreAt` asks with a quarter of the tile's longest way segment, which can be hundreds of metres and many cells.
+ */
+const INDEX_SHIFT = 13;
+
+/** The box of rings, west, north, east, south. */
+function ringsBox(rings: number[][]): number[] {
+    // Not a spread: a sea polygon has more vertices than a call takes arguments.
+    const box = [Infinity, Infinity, -Infinity, -Infinity];
+    for (const ring of rings) for (let i = 0; i < ring.length; i += 2) {
+        box[0] = Math.min(box[0], ring[i]);
+        box[1] = Math.min(box[1], ring[i + 1]);
+        box[2] = Math.max(box[2], ring[i]);
+        box[3] = Math.max(box[3], ring[i + 1]);
+    }
+    return box;
+}
+
+export function tileIndex(shapes: Shapes): TileIndex {
+    let index = indexes.get(shapes);
+    if (index) return index;
+    const { lines, lakes, seas, pads, areas, buildings } = shapes, seasAt = lakes.length, padsAt = seasAt + seas.length, areasAt = padsAt + pads.length;
+    index = {
+        lines: gridOf(lines.map(({ xy }) => ringsBox([xy])), INDEX_SHIFT),
+        reach: lines.reduce((most, line) => Math.max(most, reachOf(line, NEAR), reachOf(line, NEAR - 1)), REACH_M),
+        waterHalf: lines.reduce((most, { kind, h }) => (kind === RIVER || kind === STREAM ? Math.max(most, h) : most), 0),
+        outlines: { ...gridOf([...lakes, ...seas, ...pads, ...areas, ...buildings].map(({ rings }) => ringsBox(rings)), INDEX_SHIFT), seasFrom: seasAt, padsFrom: padsAt, areasFrom: areasAt, buildingsFrom: areasAt + areas.length },
+    };
+    indexes.set(shapes, index);
+    return index;
+}
+
+/** The indices of the boxes of a grid within `reach` world units of a box, in their order. */
+export function nearBoxes(grid: Grid, [x0, y0, x1, y1]: number[], reach: number): number[] {
+    const found: number[] = [];
+    near(grid, x0, y0, x1, y1, reach, b => found.push(b));
+    return found.sort((a, b) => a - b);
+}
+
+/**
+ * The numbers of the lines of a tile that can come within `reach` world units of world point x, y, in their order: those
+ * whose box does, with one unit more for the rounding of a distance. A test that takes a line only where the point lies
+ * within `reach` of its vertices' segments gives over these lines what it gives over all the lines of the tile.
+ */
+export function linesNear(shapes: Shapes, x: number, y: number, reach: number): number[] {
+    return nearBoxes(tileIndex(shapes).lines, [x, y, x, y], reach + 1);
+}
+
+/** The fronts of each decoded tile, made once: the house records of its quarters read them. */
+const frontsMade = new WeakMap();
+
+/**
+ * Per building of a tile, in the order of its list, its front (faceRoads), from the tile's roads and paths on the ground alone.
+ * Their lines leave out what only the stamps need, the sidewalks' test against the other beds and the approaches, whose
+ * cuts move a line by at most one world unit.
+ */
+export function fronts(list: Feature[], tile: Node): Front[] {
+    const name = `${tile.level}/${tile.x}/${tile.y}`;
+    let known = frontsMade.get(list);
+    if (known?.tile !== name) {
+        const frame = frameOf(tile), town = townOf(frame.buildings(list)), lines: Line[] = [];
+        list.forEach((feature, f) => {
+            const type = lineType(feature.kind, feature.tags);
+            if (type === ROAD || type === PATH) addLines(lines, f, feature, type, frame, town);
+        });
+        frontsMade.set(list, (known = { tile: name, fronts: faceRoads(lines, town) }));
+    }
+    return known.fronts;
+}
+
 /** The metres along a part's stroke at its vertex `start`, which only a missing height lets differ from the first. */
 function strokeAt({ along, backward }: NonNullable, xy: ArrayLike, start: number, world: (xy: ArrayLike, v: number) => number[]): Line['stroke'] {
     let metres = 0;
@@ -277,7 +358,8 @@ function strokeAt({ along, backward }: NonNullable, xy: Arr
     return backward ? { at: along - metres, sign: -1 } : { at: along + metres, sign: 1 };
 }
 
-function shapesOf(list: Feature[], tile: Node): Shapes {
+/** A tile's frame: its features' points in world units, the line of a part, whose curve is made once, and the rings of an area. */
+function frameOf(tile: Node) {
     const scale = unitScale(tile.level), ox = tile.x * EXTENT, oy = tile.y * EXTENT;
     const world = (xy: ArrayLike, v: number) => [(ox + xy[2 * v]) * scale, (oy + xy[2 * v + 1]) * scale];
     const curves = new Map();
@@ -289,10 +371,82 @@ function shapesOf(list: Feature[], tile: Node): Shapes {
         const sag = Object.hasOwn(PATH_HALF, tags.highway) && ![...PAVED_ROADS, 'paving'].includes(surfaceOf(tags, true)) ? PATH_SAG : ROAD_SAG;
         return curves.get(part) ?? curves.set(part, curveOf(part, edge, sag, scale, y => scale * metresPerUnit((oy + y) * scale))).get(part)!;
     };
-    const lines: Line[] = [], lakes: Lake[] = [], seas: Lake[] = [], areas: Shapes['areas'] = [], pads: Lake[] = [], barriers: Barrier[] = [], crossings: Shapes['crossings'] = [];
     const area = (parts: Feature['parts']) => ({ rings: parts.map(({ xy }) => Array.from({ length: xy.length / 2 }, (_, v) => world(xy, v)).flat()), outer: parts.map(part => part.outer) });
-    const buildings: Building[] = list.filter(({ kind }) => kind === 'building').map(({ parts }) => area(parts));
-    const town = townOf(buildings), beds = bedsOf(list, world, drawn);
+    const buildings = (list: Feature[]): Building[] => list.filter(({ kind }) => kind === 'building').map(({ parts }) => area(parts));
+    return { world, drawn, area, buildings };
+}
+type Frame = ReturnType;
+
+/** The primitive kind of the lines of a feature; none for a feature that makes no line. */
+function lineType(kind: string, tags: Record): number | undefined {
+    const river = kind === 'river' || kind === 'stream';
+    if (!river && !['main-road', 'road', 'path', 'railway', 'tunnel', 'gallery'].includes(kind)) return undefined;
+    // Tiles of an older bake hold a passage through a building as a tunnel: it is a way, the building stands over it.
+    const bore = kind === 'tunnel' && tags.tunnel !== 'building_passage';
+    const bridge = !river && !bore && !GROUND.includes(tags.bridge ?? 'no');
+    return kind === 'river' ? RIVER : kind === 'stream' ? STREAM : bridge ? BRIDGE : bore ? TUNNEL : kind === 'railway' ? RAIL : kind === 'path' || Object.hasOwn(PATH_HALF, tags.highway) ? PATH : ROAD;
+}
+
+/**
+ * Adds the lines of feature `feature` of the list, of primitive kind `type`. In a town, a road's sidewalk keeps out of the
+ * `beds` of the other lines where they are given.
+ */
+function addLines(lines: Line[], feature: number, { kind, tags, parts }: Feature, type: number, { world, drawn }: Frame, town: Town, beds?: () => Beds): void {
+    const river = type === RIVER || type === STREAM, bridge = type === BRIDGE, bore = type === TUNNEL, path = Object.hasOwn(PATH_HALF, tags.highway), track = isTrack(tags);
+    const surface = track ? trackSurface(tags) : surfaceOf(tags), h = halfOf(kind, tags), code = river ? 0 : Object.keys(SURFACES).indexOf(surface) + 1;
+    const profile = profileOf(kind === 'tunnel' || kind === 'gallery' ? (path ? 'path' : 'road') : kind, river ? waterwayOf(kind, tags) : classOf(tags));
+    const deck = bridge ? parseFloat(tags.deck ?? '') || DECK_M : bore ? (track ? BORE_RAIL_M : path ? BORE_PATH_M : BORE_M) : kind === 'gallery' ? (track ? ROOF_RAIL_M : path ? ROOF_PATH_M : ROOF_M) : undefined;
+    const wire = track && !bore && ['contact_line', 'yes'].includes(tags.electrified) && tags.railway !== 'funicular';
+    const style: BridgeStyle | undefined = !bridge ? undefined : tags.bridge === 'covered' ? 'covered' : CABLES.includes(tags['bridge:structure']) ? 'cable' : 'beam';
+    // In a town, where a building is near a piece of it: a road has a sidewalk on that side, and a footway is paved.
+    const sidewalk = type === ROAD && kind !== 'gallery' ? sidewalkOf(tags, surface) : 0;
+    const paving = type === PATH && kind !== 'gallery' && surfaceOf(tags, true) !== surface;
+    for (const part of parts) {
+        const curve = drawn(part, kind, tags), { xy, z } = curve, sideWaysOf = sidesAlong(part, world);
+        if (!z) continue;
+        // A line splits where a vertex has no height: a missing height is unknown, never 0 m. A footway splits
+        // where it enters or leaves a town.
+        let run: number[] = [], heights: number[] = [];
+        const flush = (end: number) => {
+            if (heights.length >= 2) {
+                const start = end - heights.length;
+                const whole: Shape = 'anchors' in curve ? { xy: run, z: heights, anchors: curve.anchors.slice(start, end), plan: planPart(curve.plan, start, end) } : smoothed(run, heights);
+                const [shape, sides] = sidewalk || paving ? townPieces(whole, town, sidewalk && beds ? clearOf(beds, feature, h, sidewalk) : undefined, sidewalk && h + sidewalk) : [whole, []];
+                const n = shape.z.length, paved = (v: number) => paving && sides[v] !== 0, sideWays = sideWaysOf?.(shape.xy);
+                const stroke = part.plan && (type === ROAD || type === BRIDGE || type === TUNNEL) ? strokeAt(part.plan, xy, start, world) : undefined;
+                for (let from = 0, to = 1; to < n; to++) {
+                    if (to < n - 1 && paved(to) === paved(from)) continue;
+                    const line: Line = {
+                        kind: type, xy: shape.xy.slice(2 * from, 2 * to + 2), z: shape.z.slice(from, to + 1), anchors: shape.anchors.slice(from, to + 1), plan: shape.plan && planPart(shape.plan, from, to + 1),
+                        h: paved(from) ? halfWidth(tags, 'paving') : h, code: paved(from) ? PAVING_CODE : code, ford: !!tags.ford && tags.ford !== 'no', profile, deck, style,
+                        gallery: kind === 'gallery' ? (tags.uphill === 'right' ? -1 : 1) : undefined, wire, sidewalks: sidewalk ? sides.slice(from, to) : undefined, sideWays: sideWays?.slice(from, to + 1), surface: tags.surface, roundabout: tags.junction === 'roundabout' || undefined, oneway: onewayOf(tags), stroke,
+                    };
+                    if (type === RAIL) line.sleepers = sleepers(line);
+                    lines.push(line);
+                    from = to;
+                }
+            }
+            run = [];
+            heights = [];
+        };
+        for (let v = 0; v < z.length; v++) {
+            if (Number.isNaN(z[v])) flush(v);
+            else {
+                run.push(...world(xy, v));
+                heights.push(z[v]);
+            }
+        }
+        flush(z.length);
+    }
+}
+
+function shapesOf(list: Feature[], tile: Node): Shapes {
+    const frame = frameOf(tile), { world, drawn, area } = frame;
+    const lines: Line[] = [], lakes: Lake[] = [], seas: Lake[] = [], areas: Shapes['areas'] = [], pads: Lake[] = [], barriers: Barrier[] = [], crossings: Shapes['crossings'] = [];
+    // The beds are made at the first sidewalk that a building is near.
+    const buildings = frame.buildings(list), town = townOf(buildings);
+    let made: Beds | undefined;
+    const beds = () => (made ??= bedsOf(list, world, drawn));
     for (const [feature, { kind, tags, parts }] of list.entries()) {
         if (kind === 'lake' || kind === 'sea') {
             const level = parts[0]?.z?.[0];
@@ -317,64 +471,14 @@ function shapesOf(list: Feature[], tile: Node): Shapes {
             if (zebraTagged(tags)) for (const { xy } of parts) crossings.push({ x: world(xy, 0)[0], y: world(xy, 0)[1] });
             continue;
         }
-        const river = kind === 'river' || kind === 'stream';
-        if (!river && !['main-road', 'road', 'path', 'railway', 'tunnel', 'gallery'].includes(kind)) continue;
-        // A passage through a building is a road: the building stands over it.
-        const bore = kind === 'tunnel' && tags.tunnel !== 'building_passage', path = Object.hasOwn(PATH_HALF, tags.highway);
-        const bridge = !river && !bore && !GROUND.includes(tags.bridge ?? 'no'), track = isTrack(tags);
-        const surface = track ? trackSurface(tags) : surfaceOf(tags), h = halfOf(kind, tags), code = river ? 0 : Object.keys(SURFACES).indexOf(surface) + 1;
-        const profile = profileOf(kind === 'tunnel' || kind === 'gallery' ? (path ? 'path' : 'road') : kind, river ? waterwayOf(kind, tags) : classOf(tags));
-        const type = kind === 'river' ? RIVER : kind === 'stream' ? STREAM : bridge ? BRIDGE : bore ? TUNNEL : kind === 'railway' ? RAIL : kind === 'path' || path ? PATH : ROAD;
-        const deck = bridge ? parseFloat(tags.deck ?? '') || DECK_M : bore ? (track ? BORE_RAIL_M : path ? BORE_PATH_M : BORE_M) : kind === 'gallery' ? (track ? ROOF_RAIL_M : path ? ROOF_PATH_M : ROOF_M) : undefined;
-        const wire = track && !bore && ['contact_line', 'yes'].includes(tags.electrified) && tags.railway !== 'funicular';
-        const style: BridgeStyle | undefined = !bridge ? undefined : tags.bridge === 'covered' ? 'covered' : CABLES.includes(tags['bridge:structure']) ? 'cable' : 'beam';
-        // In a town, where a building is near a piece of it: a road has a sidewalk on that side, and a footway is paved.
-        const sidewalk = type === ROAD && kind !== 'gallery' ? sidewalkOf(tags, surface) : 0;
-        const paving = type === PATH && kind !== 'gallery' && surfaceOf(tags, true) !== surface;
-        for (const part of parts) {
-            const curve = drawn(part, kind, tags), { xy, z } = curve, sideWaysOf = sidesAlong(part, world);
-            if (!z) continue;
-            // A line splits where a vertex has no height: a missing height is unknown, never 0 m. A footway splits
-            // where it enters or leaves a town.
-            let run: number[] = [], heights: number[] = [];
-            const flush = (end: number) => {
-                if (heights.length >= 2) {
-                    const start = end - heights.length;
-                    const whole: Shape = 'anchors' in curve ? { xy: run, z: heights, anchors: curve.anchors.slice(start, end), plan: planPart(curve.plan, start, end) } : smoothed(run, heights);
-                    const [shape, sides] = sidewalk || paving ? townPieces(whole, town, sidewalk ? clearOf(beds, feature, h, sidewalk) : undefined, sidewalk && h + sidewalk) : [whole, []];
-                    const n = shape.z.length, paved = (v: number) => paving && sides[v] !== 0, sideWays = sideWaysOf?.(shape.xy);
-                    const stroke = part.plan && (type === ROAD || type === BRIDGE || type === TUNNEL) ? strokeAt(part.plan, xy, start, world) : undefined;
-                    for (let from = 0, to = 1; to < n; to++) {
-                        if (to < n - 1 && paved(to) === paved(from)) continue;
-                        const line: Line = {
-                            kind: type, xy: shape.xy.slice(2 * from, 2 * to + 2), z: shape.z.slice(from, to + 1), anchors: shape.anchors.slice(from, to + 1), plan: shape.plan && planPart(shape.plan, from, to + 1),
-                            h: paved(from) ? halfWidth(tags, 'paving') : h, code: paved(from) ? PAVING_CODE : code, ford: !!tags.ford && tags.ford !== 'no', profile, deck, style,
-                            gallery: kind === 'gallery' ? (tags.uphill === 'right' ? -1 : 1) : undefined, wire, sidewalks: sidewalk ? sides.slice(from, to) : undefined, sideWays: sideWays?.slice(from, to + 1), surface: tags.surface, roundabout: tags.junction === 'roundabout' || undefined, oneway: onewayOf(tags), stroke,
-                        };
-                        if (type === RAIL) line.sleepers = sleepers(line);
-                        lines.push(line);
-                        from = to;
-                    }
-                }
-                run = [];
-                heights = [];
-            };
-            for (let v = 0; v < z.length; v++) {
-                if (Number.isNaN(z[v])) flush(v);
-                else {
-                    run.push(...world(xy, v));
-                    heights.push(z[v]);
-                }
-            }
-            flush(z.length);
-        }
+        const type = lineType(kind, tags);
+        if (type !== undefined) addLines(lines, feature, list[feature], type, frame, town, beds);
     }
     // Before the culverts: `waysOf` keeps each way's segments by their vertices, and this adds vertices.
     approaches(lines);
     const buried = joinCulverts(list, lines, world);
     junctionPlanes(lines);
     abutments(lines);
-    faceRoads(lines, buildings, town);
     return { lines, lakes, seas, areas, pads, buildings, barriers, crossings, mouths: standMouths(lines, buried) };
 }
 
@@ -547,9 +651,11 @@ const JOIN_M = 12;
  * The sidewalk test of a street of half-width h with sidewalks `walk` metres wide: the sidewalk lies
  * outside the bed of every other line, but near the vertices where those lines meet the street.
  */
-function clearOf(beds: Beds, feature: number, h: number, walk: number): Clear {
-    const joins = (beds.points[feature] ?? []).map(([x, y]) => ({ x, y, lines: beds.vertices.get(`${x},${y}`)!.filter(f => f !== feature) })).filter(({ lines }) => lines.length);
+function clearOf(made: () => Beds, feature: number, h: number, walk: number): Clear {
+    let known: { x: number; y: number; lines: number[] }[] | undefined;
     return (x, y, dx, dy, side) => {
+        const beds = made();
+        const joins = (known ??= (beds.points[feature] ?? []).map(([x, y]) => ({ x, y, lines: beds.vertices.get(`${x},${y}`)!.filter(f => f !== feature) })).filter(({ lines }) => lines.length));
         const unit = metresPerUnit(y), l = Math.hypot(dx, dy) * unit || 1, out = (side === LEFT ? 1 : -1) * (h + walk / 2) / l;
         // Left of the way, whose y runs south.
         const mx = x + dy * out, my = y - dx * out;
@@ -568,14 +674,17 @@ function clearOf(beds: Beds, feature: number, h: number, walk: number): Clear {
 /** The shortest wall that is a front; a road or a path this near a building reaches it; a wall faces a point within 60° of its normal. */
 const WALL_M = 2, REACHED_M = 2, FACING_COS = 0.5;
 
+/** The outward unit direction of a building's wall that faces its road, in world units. */
+type Front = [number, number] | undefined;
+
 /**
- * The fronts of the houses: a building whose nearest road on the ground comes within BUILT_M, and no road or
+ * The fronts of the buildings of a town: a building whose nearest road on the ground comes within BUILT_M, and no road or
  * path within REACHED_M, fronts that road with its nearest wall that faces it. Only the house and the lines
  * near it decide, so each tile that holds them all draws it alike.
  */
-function faceRoads(lines: Line[], buildings: Building[], town: Town): void {
+function faceRoads(lines: Line[], town: Town): Front[] {
     // Per building, the least gap to the edge of a road and that road; -Infinity where a road or a path reaches it.
-    const nearest = buildings.map(() => ({ gap: BUILT_M, road: undefined as Line | undefined }));
+    const nearest = town.rings.map(() => ({ gap: BUILT_M, road: undefined as Line | undefined }));
     for (const line of lines) {
         if (line.kind !== ROAD && line.kind !== PATH) continue;
         const road = line.kind === ROAD && !line.gallery;
@@ -593,14 +702,12 @@ function faceRoads(lines: Line[], buildings: Building[], town: Town): void {
             });
         }
     }
-    buildings.forEach((building, b) => {
-        if (nearest[b].gap >= REACHED_M && nearest[b].road) building.front = frontOf(building, nearest[b].road);
-    });
+    return nearest.map(({ gap, road }, b) => (gap >= REACHED_M && road ? frontOf(town.rings[b], road) : undefined));
 }
 
-/** The outward direction of a building's nearest wall that faces a road; none where no wall faces it. */
-function frontOf(building: Building, road: Line): [number, number] | undefined {
-    const ring = building.rings[0], n = ring.length / 2, unit = metresPerUnit(ring[1]);
+/** The outward direction of the nearest wall of a building's outer ring that faces a road; none where no wall faces it. */
+function frontOf(ring: number[], road: Line): Front {
+    const n = ring.length / 2, unit = metresPerUnit(ring[1]);
     // The ring's outside lies right of each edge (y south) where its area is positive. About its first vertex: products of world units lose float64 bits.
     let twice = 0;
     for (let i = 0, j = n - 1; i < n; j = i++) twice += (ring[2 * j] - ring[0]) * (ring[2 * i + 1] - ring[1]) - (ring[2 * i] - ring[0]) * (ring[2 * j + 1] - ring[1]);
@@ -638,7 +745,8 @@ function ringDistance(ring: number[], ax: number, ay: number, bx: number, by: nu
 }
 
 /** The lines whose shared vertices are junctions of the road cores: roads, tracks, bridges and tunnels. */
-export const cores = (lines: Line[]) => lines.filter(({ kind }) => kind === ROAD || kind === RAIL || kind === BRIDGE || kind === TUNNEL);
+export const isCore = ({ kind }: Line) => kind === ROAD || kind === RAIL || kind === BRIDGE || kind === TUNNEL;
+export const cores = (lines: Line[]) => lines.filter(isCore);
 
 /**
  * As APPROACH_M of host/obc-trailview-features/src/roads/mod.rs: the solver puts the first metres of a side road on the
@@ -807,6 +915,22 @@ export function junctions(lines: Line[]): Map count > 1));
 }
 
+/** `make` of a tile's lines, made once per decoded tile: each node of the tile reads it. */
+function perTile(make: (lines: Line[]) => T): (lines: Line[]) => T {
+    const made = new WeakMap();
+    return lines => {
+        if (!made.has(lines)) made.set(lines, make(lines));
+        return made.get(lines)!;
+    };
+}
+
+/** A paved road that ends where a path runs on has a plain end: its core and its paint stop at its last vertex. A way of soil keeps its round end, which frays. */
+const joinsOf = perTile(lines => junctions(cores(lines)));
+const runsOnOf = perTile(lines => junctions(lines.filter(({ kind }) => kind !== RIVER && kind !== STREAM)));
+/** A path that meets a road with a sidewalk also has a junction's record: the road's shelf reads it. */
+const kerbedOf = perTile(lines => new Set(lines.flatMap(line => line.sidewalks?.some(Boolean) ? line.z.map((_, v) => `${line.xy[2 * v]},${line.xy[2 * v + 1]}`) : [])));
+const NO_PARTNERS = new Map();
+
 /**
  * The unit mitre normal at vertex v of a line: its tangent where it has an alignment, else along the line
  * at an end, the bisector of the two segments inside. At an OSM vertex the segments run to the OSM vertices
@@ -897,6 +1021,9 @@ export function ringsDistance(rings: number[][], x: number, y: number): number {
     return best;
 }
 
+/** How far a line's stamp acts past it on a level, in metres: a path no farther than its bench, and on the near levels than the mask reads it. */
+const reachOf = (line: Line, level: number) => (line.kind === PATH ? line.h + (level >= NEAR ? MASK_RANGE_M : Object.values(PROFILES)[line.profile].reach) : REACH_M);
+
 /** What a node stamps: its packed data for stamp.wgsl, and what it holds. */
 export interface NodeStamps {
     /** The words of stamp-core.wgsl: counts, cell offsets, cell entries, records. Null when nothing is near. */
@@ -905,21 +1032,30 @@ export interface NodeStamps {
     heights: boolean;
     /** A line, an area or a shore lies in the node: on a near level it holds a feature mask. */
     mask: boolean;
+    /** How often the node hit a limit, where it did: an area left out or the node left empty past STAMP_WORDS, a cell whose origin no nudge moves a unit off its shores. */
+    limits?: number;
 }
 
+/** Words of stamp data per frame at most: the nodes of the frame's stamps. A node holds no more. */
+export const STAMP_WORDS = 2 ** 20;
+
 /**
  * The stamp data of a node from the features of its feature tile. Every primitive goes to each cell
  * that it can act on, so the shader sees every primitive that can reach a texel. A cell keeps the
- * order of stamp-core.wgsl: a lake's edges before its marker, a line's segments together.
+ * order of stamp-core.wgsl: a lake's edges before its marker, a line's segments together. With `plan`
+ * the records shape and paint the roads, paths and rail lines (model.wgsl): their records stay out,
+ * and the node stamps and holds a mask where they would. Without `areas` the river areas and the
+ * buildings stay out, as they do where the node would pass STAMP_WORDS with them.
  */
-export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps {
-    const { lines, lakes, seas, pads, areas, buildings } = features(list, tile);
+export function nodeStamps(list: Feature[], tile: Node, node: Node, plan = false, areas = true): NodeStamps {
+    const shapes = features(list, tile), { lines, lakes, seas, pads, buildings } = shapes, index = tileIndex(shapes);
     const shift = 22 - node.level, cell = CELL * 2 ** shift;
-    const x0 = node.x * PAGE * 2 ** shift - cell, y0 = node.y * PAGE * 2 ** shift - cell, span = GRID * cell;
+    const x0 = node.x * PAGE * 2 ** shift - cell, y0 = node.y * PAGE * 2 ** shift - cell, span = GRID * cell, square = [x0, y0, x0 + span, y0 + span];
     // Units per metre grow toward the pole: the node's poleward edge bounds them.
     const units = 1.02 / metresPerUnit(y0 < UNITS / 2 ? y0 - span : y0 + 2 * span);
     const records: number[][] = [];
     const cells: number[][][] = Array.from({ length: 3 }, () => Array.from({ length: GRID * GRID }, () => []));
+    let limits = 0;
     /** The cells within `metres` of a box. */
     const within = (box: number[], metres: number) => {
         const reach = metres * units, out: number[] = [];
@@ -934,18 +1070,15 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps
     /** Two numbers within ±1 as unpack2x16snorm reads them. */
     const pair = (a: number, b: number) => (Math.round(a * 32767) & 0xffff) | (Math.round(b * 32767) << 16);
 
-    // A paved road that ends where a path runs on has a plain end: its core and its paint stop at its last vertex. A way of soil keeps its round end, which frays.
-    const joins = junctions(cores(lines)), runsOn = junctions(lines.filter(({ kind }) => kind !== RIVER && kind !== STREAM));
-    // A path that meets a road with a sidewalk also has a junction's record: the road's shelf reads it.
-    const kerbed = new Set(lines.flatMap(line => line.sidewalks?.some(Boolean) ? line.z.map((_, v) => `${line.xy[2 * v]},${line.xy[2 * v + 1]}`) : []));
-    for (const [point, { x, y, h }] of runsOn) {
-        if (!joins.has(point) && !kerbed.has(point)) continue;
+    // With `plan` the records hold the junctions.
+    for (const [point, { x, y, h }] of plan ? [] : runsOnOf(lines)) {
+        if (!joinsOf(lines).has(point) && !kerbedOf(lines).has(point)) continue;
         const touched = within([x, y, x, y], REACH_M);
         if (!touched.length) continue;
         const at = record([x, y, 0, 0, JUNCTION, 0, f(h)]);
         for (const c of touched) cells[0][c].push(at);
     }
-    for (const corner of cornersOf(lines)) {
+    for (const corner of plan ? [] : cornersOf(lines)) {
         const { o, a, b, z, grad, walk, code, profile, h } = corner, touched = within(boxOf(corner), 1);
         if (!touched.length) continue;
         // The sidewalks' widths in decimetres share a word; the slopes fill the words about the second end.
@@ -953,15 +1086,22 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps
         for (const c of touched) cells[2][c].push(at);
     }
     let heights = false;
-    const partners = partnersOf(lines);
-    // A record holds a line's index in 16 bits.
-    if (lines.length > 0x10000) throw new Error(`nodeStamps: ${lines.length} lines pass the 16-bit index`);
-    lines.forEach((line, id) => {
-        const stamps = shows(line, gateTexel(node.level));
-        if (line.kind === STREAM || (!stamps && node.level < NEAR)) return;
-        // A path acts no farther than its bench, and on the near levels than the mask reads it.
-        const reach = line.kind === PATH ? line.h + (node.level >= NEAR ? MASK_RANGE_M : Object.values(PROFILES)[line.profile].reach) : REACH_M;
-        const n = line.z.length, end = (v: number) => v === 0 || v === n - 1;
+    // Only a road has partners, and with `plan` no road reaches a record.
+    const partners = plan ? NO_PARTNERS : partnersOf(lines);
+    // The inner cells that the records' ways reach, with `plan`.
+    const ways = new Set();
+    // A record holds a number of its line in 16 bits, which groups the line's segments in a cell (stamp-core.wgsl): its
+    // index in the tile, or, in a tile with more lines, its place among the node's lines with records. A node with more
+    // than 2^16 of those passes STAMP_WORDS with their records alone, so it stamps nothing.
+    const numbers = lines.length > 0x10000 ? new Map() : undefined;
+    // Only the lines whose box comes within their reach of the node can touch its cells.
+    for (const id of nearBoxes(index.lines, square, index.reach * units + 1)) {
+        const line = lines[id], stamps = shows(line, gateTexel(node.level));
+        // With `plan` the records shape the ways on the near levels only (model.wgsl), and the ground under a bridge
+        // there (the decks' ceilings): its deck terms stay off those levels.
+        const way = plan && (line.kind === ROAD || line.kind === PATH || line.kind === RAIL || (line.kind === BRIDGE && node.level >= NEAR));
+        if (line.kind === STREAM || ((!stamps || way) && node.level < NEAR)) continue;
+        const reach = reachOf(line, node.level), n = line.z.length, end = (v: number) => v === 0 || v === n - 1;
         // A bridge's or a tunnel's metres from its start at each vertex: it rests on its abutments, or runs on the ground into its portal, a few mesh cells from an end that meets the ground.
         const along = [0];
         for (let v = 1; v < n; v++) along.push(along[v - 1] + Math.hypot(line.xy[2 * v] - line.xy[2 * v - 2], line.xy[2 * v + 1] - line.xy[2 * v - 1]) * metresPerUnit(line.xy[2 * v + 1]));
@@ -969,8 +1109,14 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps
             const [ax, ay, bx, by] = line.xy.slice(2 * v, 2 * v + 4);
             const touched = within([Math.min(ax, bx), Math.min(ay, by), Math.max(ax, bx), Math.max(ay, by)], reach);
             if (!touched.length) continue;
+            const number = way || !numbers ? id : (numbers.get(id) ?? numbers.set(id, numbers.size).get(id)!);
+            heights ||= stamps;
+            if (way) {
+                for (const c of touched) ways.add(c);
+                continue;
+            }
             const [mx, my] = mitre(line, v), [nx, ny] = mitre(line, v + 1);
-            const dead = (w: number) => end(w) && !(PAVED_CODES.includes(line.code) ? runsOn : joins).has(`${line.xy[2 * w]},${line.xy[2 * w + 1]}`);
+            const dead = (w: number) => end(w) && !(PAVED_CODES.includes(line.code) ? runsOnOf : joinsOf)(lines).has(`${line.xy[2 * w]},${line.xy[2 * w + 1]}`);
             const join = (w: number) => !!line.join?.[w === 0 ? 0 : 1] && end(w);
             const flags = (line.kind === BRIDGE || line.kind === TUNNEL ? 0 : (line.ford ? FORD : 0) | (dead(v) ? CORE_A : 0) | (dead(v + 1) ? CORE_B : 0) | (end(v) ? CONE_A : 0) | (end(v + 1) ? CONE_B : 0)
                 | (join(v) ? JOIN_A : 0) | (join(v + 1) ? JOIN_B : 0)) | (marked(line) ? MARKED : 0);
@@ -986,28 +1132,21 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps
             // The mitres of the two ends, then the rise of the bank to the right at each. One word stays free.
             const rise = (w: number) => -(line.plan?.bank[w] ?? 0);
             const at = record([ax, ay, bx, by, line.kind, line.code | ((line.sidewalks?.[v] ?? 0) << 4) | (DRIVEWAYS.includes(CLASSES[line.profile]) && !line.sidewalks?.some(Boolean) ? DRIVEWAY : 0) | (flags << 8) | (line.profile << 16) | (deck << 24), f(line.z[v]), f(line.z[v + 1]), f(line.h),
-                pair(mx, my), pair(nx, ny), pair(rise(v), rise(v + 1)), 0, id | (taper(v) << 16) | (taper(v + 1) << 24), ...ends]);
+                pair(mx, my), pair(nx, ny), pair(rise(v), rise(v + 1)), 0, number | (taper(v) << 16) | (taper(v + 1) << 24), ...ends]);
             for (const c of touched) cells[2][c].push(at);
-            heights ||= stamps;
         }
-    });
+    }
     // The stamps of a node read only the cells inside its apron.
     const inner = (c: number) => c % GRID > 0 && c % GRID < GRID - 1 && c >= GRID && c < GRID * (GRID - 1);
-    let mask = [cells[0], cells[2]].some(lists => lists.some((list, c) => inner(c) && list.length > 0));
+    let mask = [cells[0], cells[2]].some(lists => lists.some((list, c) => inner(c) && list.length > 0)) || [...ways].some(inner);
     // Per lake, sea polygon, pad and area near the node, its edges in each cell that they reach.
-    const outlines = [...lakes.map(lake => ({ lake, kind: LAKE })), ...(seaShows(node.level) ? seas.map(lake => ({ lake, kind: SEA })) : []),
-        ...(node.level >= PAD_LEVEL ? pads.map(lake => ({ lake, kind: PAD })) : []),
-        ...(node.level >= NEAR ? [...areas, ...buildings].map(area => ({ lake: { level: 0, ...area }, kind: AREA })) : [])];
-    const all = Array.from({ length: GRID * GRID }, (_, c) => c);
-    const near = outlines.flatMap(({ lake, kind }) => {
-        // Not a spread: a sea polygon has more vertices than a call takes arguments.
-        const box = [Infinity, Infinity, -Infinity, -Infinity];
-        for (const ring of lake.rings) for (let i = 0; i < ring.length; i += 2) {
-            box[0] = Math.min(box[0], ring[i]);
-            box[1] = Math.min(box[1], ring[i + 1]);
-            box[2] = Math.max(box[2], ring[i]);
-            box[3] = Math.max(box[3], ring[i + 1]);
-        }
+    const { outlines } = index, all = Array.from({ length: GRID * GRID }, (_, c) => c);
+    // No outline acts farther than REACH_M past its box.
+    const near = nearBoxes(outlines, square, REACH_M * units + 1).flatMap(k => {
+        const kind = k < outlines.seasFrom ? LAKE : k < outlines.padsFrom ? SEA : k < outlines.areasFrom ? PAD : AREA, box = outlines.boxes[k];
+        if ((kind === SEA && !seaShows(node.level)) || (kind === PAD && node.level < PAD_LEVEL) || (kind === AREA && (node.level < NEAR || !areas))) return [];
+        const lake = kind === LAKE ? lakes[k] : kind === SEA ? seas[k - outlines.seasFrom] : kind === PAD ? pads[k - outlines.padsFrom]
+            : { level: 0, ...(k < outlines.buildingsFrom ? shapes.areas[k - outlines.areasFrom] : buildings[k - outlines.buildingsFrom]) };
         // An area acts only inside it: its edges go to the cells that they cross, so a village's cells stay
         // short. The sea acts no farther than the end of its bed's slope from its coast, so its long coasts
         // stay short too: BED_M past sea_band of stamp-core.wgsl, in units at most a shore band and the
@@ -1034,14 +1173,12 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps
         const held = (v: number, base: number) => Math.min(Math.max(v, base + cell), base + cell + PAGE * 2 ** shift - 1);
         const centre = [held(x0 + (c % GRID + 0.5) * cell, x0), held(y0 + (Math.floor(c / GRID) + 0.5) * cell, y0)];
         const edges = near.flatMap(({ edges }) => edges.get(c) ?? []).map(r => records[r]);
-        for (const [dx, dy] of NUDGES) {
-            const [x, y] = [centre[0] + dx, centre[1] + dy];
-            if (edges.every(([ax, ay, bx, by]) => segmentDistance(x, y, ax, ay, bx, by) >= 1)) {
-                nudges[c] = (dx + 8) | ((dy + 8) << 4);
-                return [x, y];
-            }
-        }
-        throw new Error(`No origin off the shores in cell ${c} of node ${node.level}/${node.x}/${node.y}`);
+        const least = ([dx, dy]: number[]) => edges.reduce((most, [ax, ay, bx, by]) => Math.min(most, segmentDistance(centre[0] + dx, centre[1] + dy, ax, ay, bx, by)), Infinity);
+        // Where no nudge moves it a unit off the shores, it takes the nudge farthest from them.
+        const [dx, dy] = NUDGES.find(([dx, dy]) => edges.every(([ax, ay, bx, by]) => segmentDistance(centre[0] + dx, centre[1] + dy, ax, ay, bx, by) >= 1))
+            ?? (limits++, NUDGES.reduce((best, nudge) => (least(nudge) > least(best) ? nudge : best)));
+        nudges[c] = (dx + 8) | ((dy + 8) << 4);
+        return [centre[0] + dx, centre[1] + dy];
     };
     const origins = Array.from({ length: GRID * GRID }, (_, c): [number, number] => (near.length ? origin(c) : [0, 0]));
     for (const { lake, kind, edges, cells: reached } of near) {
@@ -1061,9 +1198,15 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps
         // The box of a sea polygon covers much land, where it stamps nothing.
         heights ||= used && kind !== AREA;
     }
-    if (!records.length || (!heights && (!mask || node.level < NEAR))) return { data: null, heights: false, mask: false };
+    const counted = limits ? { limits } : {};
+    if ((!records.length && !ways.size) || (!heights && (!mask || node.level < NEAR))) return { data: null, heights: false, mask: false, ...counted };
     const entries = cells[0].map((_, c) => [...cells[0][c], ...cells[1][c], ...cells[2][c]]);
     const count = entries.reduce((sum, list) => sum + list.length, 0);
+    if (HEAD + OFFSETS + count + RECORD * records.length > STAMP_WORDS) {
+        // The areas only take their insides out of the mask. Without them a node that still passes the limit stamps nothing.
+        const dropped = areas ? near.filter(({ kind }) => kind === AREA).length : 0, lean = dropped ? nodeStamps(list, tile, node, plan, false) : { data: null, heights: false, mask: false, limits };
+        return { ...lean, limits: (lean.limits ?? 0) + (dropped || 1) };
+    }
     const data = new Uint32Array(HEAD + OFFSETS + count + RECORD * records.length);
     data[0] = records.length;
     data[1] = count;
@@ -1075,11 +1218,13 @@ export function nodeStamps(list: Feature[], tile: Node, node: Node): NodeStamps
     });
     data[HEAD + GRID * GRID] = count;
     records.forEach((words, r) => data.set(words.map(w => w >>> 0), HEAD + OFFSETS + count + RECORD * r));
-    return { data, heights, mask };
+    return { data, heights, mask, ...counted };
 }
 
-/** The moves of a cell's origin that the worker tries, in world units, as a signed nibble each. */
-const NUDGES = [[0, 0], [1, 0], [0, 1], [1, 1], [2, 1], [1, 2], [-1, 2], [3, 1], [-2, 3], [3, -2], [4, 3], [-3, 4]];
+/** The moves of a cell's origin that the worker tries, in world units, as a signed nibble each: these, then every other by its length. */
+const FIRST = [[0, 0], [1, 0], [0, 1], [1, 1], [2, 1], [1, 2], [-1, 2], [3, 1], [-2, 3], [3, -2], [4, 3], [-3, 4]];
+const NUDGES = [...FIRST, ...Array.from({ length: 256 }, (_, k) => [(k & 15) - 8, (k >> 4) - 8])
+    .filter(([dx, dy]) => !FIRST.some(([x, y]) => x === dx && y === dy)).sort((p, q) => Math.hypot(p[0], p[1]) - Math.hypot(q[0], q[1]))];
 
 function segmentDistance(x: number, y: number, ax: number, ay: number, bx: number, by: number): number {
     const dx = bx - ax, dy = by - ay, t = Math.min(1, Math.max(0, ((x - ax) * dx + (y - ay) * dy) / (dx * dx + dy * dy || 1)));
diff --git a/builder/web/src/lib/trailview/terrain/cliff.test.ts b/builder/web/src/lib/trailview/terrain/cliff.test.ts
new file mode 100644
index 0000000000..6e36bf1249
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/cliff.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { PAGE } from '../stream/heights';
+import { cliffJobs } from './cliff';
+import { key, type Node } from './lod';
+import type { Page } from './pages';
+
+const page = (x: number, y: number, mask?: number): Page => ({ node: { level: 17, x, y }, kind: 'synth', slot: x + 10 * y, used: 0, range: [0, 0], complete: true, ready: true, drawn: x + 10 * y, mask });
+const pool = (...list: Page[]) => new Map(list.map(p => [key(p.node), p]));
+const rects = (jobs: ReturnType) => jobs.map(({ page: { node }, lo, hi }) => `${node.x},${node.y}: ${lo} ${hi}`).sort();
+
+describe('cliffJobs', () => {
+    it('makes a page whole when its mask or heights change, and the texels of each neighbour with a mask that face it', () => {
+        const last = new Map();
+        const west = page(4, 5, 0), middle = page(5, 5, 1), north = page(5, 4, 2), corner = page(6, 6, 3), plain = page(6, 5);
+        expect(cliffJobs(pool(west, north, corner, plain), last, [])).toHaveLength(3);
+        // The middle page gets its mask: its neighbours make the 4 texels that read it.
+        expect(rects(cliffJobs(pool(west, middle, north, corner, plain), last, []))).toEqual([
+            `4,5: ${PAGE - 4},0 ${PAGE},${PAGE}`, `5,4: 0,${PAGE - 4} ${PAGE},${PAGE}`, `5,5: 0,0 ${PAGE},${PAGE}`, '6,6: 0,0 4,4',
+        ]);
+        expect(cliffJobs(pool(west, middle, north, corner, plain), last, [])).toEqual([]);
+        // New heights of the page without a mask, and the north page loses its mask.
+        north.mask = undefined;
+        expect(rects(cliffJobs(pool(west, middle, north, corner, plain), last, [plain.node]))).toEqual([
+            `4,5: ${PAGE - 4},0 ${PAGE},4`, `5,5: 0,0 ${PAGE},4`, `5,5: ${PAGE - 4},0 ${PAGE},${PAGE}`, `6,6: 0,0 ${PAGE},4`,
+        ]);
+    });
+});
diff --git a/builder/web/src/lib/trailview/terrain/cliff.ts b/builder/web/src/lib/trailview/terrain/cliff.ts
new file mode 100644
index 0000000000..aef9d5bae0
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/cliff.ts
@@ -0,0 +1,59 @@
+import { PAGE } from '../stream/heights';
+import { NEAR } from './bins';
+import { key, type Node } from './lod';
+import type { Page } from './pages';
+
+/** Texels of a page whose cliff share reads a neighbour's heights or moves (cliff.wgsl): two, as whole packed texels of four. */
+const REACH = 4;
+/** Bytes of `CliffJob` in cliff.wgsl. */
+export const CLIFF_JOB_BYTES = 32;
+
+/** The texels from `lo` to `hi` (not included) of a page with a mask that the cliff pass makes. */
+export interface CliffJob {
+    page: Page;
+    lo: [number, number];
+    hi: [number, number];
+}
+
+/**
+ * The cliff pass's jobs of a frame: the whole page of each page with a mask whose mask or heights changed, and the texels
+ * of each other page with a mask that face a neighbour of its level whose heights or mask changed; at most one job per
+ * page and neighbour. `changed` holds the nodes whose heights in the LOD map changed; `last` holds the mask layer and
+ * the node of each page with a mask by name, and takes this frame's.
+ */
+export function cliffJobs(pages: Map, last: Map, changed: Node[]): CliffJob[] {
+    const masked = new Map([...pages].filter(([, page]) => page.mask !== undefined && page.drawn !== undefined));
+    const whole = new Set(changed.map(key)), moved = [...changed];
+    for (const [name, [mask, node]] of last) {
+        if (masked.get(name)?.mask === mask) continue;
+        whole.add(name);
+        moved.push(node);
+    }
+    for (const [name, page] of masked) {
+        if (last.has(name)) continue;
+        whole.add(name);
+        moved.push(page.node);
+    }
+    last.clear();
+    for (const [name, page] of masked) last.set(name, [page.mask!, page.node]);
+    const jobs: CliffJob[] = [...masked].filter(([name]) => whole.has(name)).map(([, page]) => ({ page, lo: [0, 0], hi: [PAGE, PAGE] }));
+    const seen = new Set();
+    for (const { level, x, y } of moved) {
+        if (level < NEAR) continue;
+        // The neighbour lies at -dx, -dy from the page.
+        for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
+            const name = key({ level, x: x + dx, y: y + dy }), page = masked.get(name), side = `${name}/${dx}/${dy}`;
+            if (!page || whole.has(name) || seen.has(side)) continue;
+            seen.add(side);
+            jobs.push({ page, lo: [dx < 0 ? PAGE - REACH : 0, dy < 0 ? PAGE - REACH : 0], hi: [dx > 0 ? REACH : PAGE, dy > 0 ? REACH : PAGE] });
+        }
+    }
+    return jobs;
+}
+
+/** Jobs as `CliffJob` in cliff.wgsl. */
+export function packCliffJobs(jobs: CliffJob[]): ArrayBuffer {
+    const data = new ArrayBuffer(Math.max(1, jobs.length) * CLIFF_JOB_BYTES), ints = new Int32Array(data);
+    jobs.forEach(({ page: { node, mask }, lo, hi }, k) => ints.set([node.x * PAGE, node.y * PAGE, node.level, mask!, ...lo, ...hi], (CLIFF_JOB_BYTES / 4) * k));
+    return data;
+}
diff --git a/builder/web/src/lib/trailview/terrain/cliff.wgsl b/builder/web/src/lib/trailview/terrain/cliff.wgsl
new file mode 100644
index 0000000000..fe226ca34d
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/cliff.wgsl
@@ -0,0 +1,115 @@
+// The cliff share of the pages with masks on the plan path (cliff_at of features.wgsl): per texel, how far
+// ground_colour turns the ground's normal toward the coarse one. The plan's heights hold creases and a wall's step
+// sharper than a texel, and the texel normals beside them change with the crease's phase from texel to texel: the
+// turn's key (cliff_of, or a normal that turns past what the texels resolve) then flips per texel along the crease.
+// Each texel takes the key of the 3 × 3 texels about it, filtered, where the plan moved the ground within two texels;
+// elsewhere UNSHAPED, and the look keeps its own key. The pass makes a page once when its heights or its mask
+// change, and the texels facing a neighbour of the same level when that neighbour's do (cliff.ts).
+// #include ../ground/look.wgsl
+
+struct CliffJob {
+    // The node's first texel at its level.
+    first: vec2i,
+    level: u32,
+    mask: u32,
+    // The texels of the page to make, from lo to hi (not included); x in whole packed texels of four.
+    lo: vec2u,
+    hi: vec2u,
+}
+
+@group(0) @binding(0) var cliff_jobs: array;
+// As cliff_texels of features.wgsl: four texels of a row in one texel.
+@group(0) @binding(1) var cliff_out: texture_storage_2d_array;
+
+// A workgroup's tile of 8 × 8 texels: the heights and the moves two texels about it, the keys one texel about it.
+var tile_heights: array;
+var tile_moved: array;
+var tile_keys: array;
+var tile_shares: array;
+
+// The workgroups of a job's dispatch row: each makes every 32nd tile of the job's texels.
+const ROW: u32 = 32u;
+// A normal that turns more than this from one texel to the next is all cliff: the texels do not resolve it.
+const UNRESOLVED: vec2f = vec2f(0.15, 0.4);
+
+@compute @workgroup_size(8, 8)
+fn cliff(@builtin(workgroup_id) group: vec3u, @builtin(local_invocation_index) lane: u32) {
+    let job = cliff_jobs[group.z];
+    let low = job.lo / 8u;
+    let tiles = (job.hi + 7u) / 8u - low;
+    for (var k = group.x; k < tiles.x * tiles.y; k += ROW) {
+        cliff_tile(job, (low + vec2u(k % tiles.x, k / tiles.x)) * 8u, lane);
+    }
+}
+
+fn cliff_tile(job: CliffJob, corner: vec2u, lane: u32) {
+    let origin = job.first + vec2i(corner) - 2;
+    for (var k = lane; k < 144u; k += 64u) {
+        let t = origin + vec2i(i32(k % 12u), i32(k / 12u));
+        tile_heights[k] = texel_height(job.level, t, false);
+        let slot = mask_of(job.level, t);
+        var moved = 0.0;
+        if (slot != 0u) {
+            moved = moved_texel(slot - 1u, t);
+        }
+        tile_moved[k] = moved;
+    }
+    workgroupBarrier();
+    for (var k = lane; k < 100u; k += 64u) {
+        // The row's own metres, not the eye's: a page's share must not depend on where the eye was when it was made.
+        tile_keys[k] = texel_key((k / 10u + 1u) * 12u + k % 10u + 1u, texel_metres(job.level, origin.y + i32(k / 10u) + 1));
+    }
+    workgroupBarrier();
+    let own = vec2u(lane % 8u, lane / 8u);
+    var sum = 0.0;
+    var weight = 0.0;
+    for (var j = 0u; j < 3u; j++) {
+        for (var i = 0u; i < 3u; i++) {
+            let key = tile_keys[(own.y + j) * 10u + own.x + i];
+            // The weights 1 2 1 across and up.
+            let w = select(0.0, f32((1u + i % 2u) * (1u + j % 2u)), key >= 0.0);
+            sum += w * key;
+            weight += w;
+        }
+    }
+    var shaped = false;
+    for (var j = 0u; j < 5u; j++) {
+        for (var i = 0u; i < 5u; i++) {
+            shaped = shaped || tile_moved[(own.y + j) * 12u + own.x + i] >= 0.5 * MOVED_M;
+        }
+    }
+    tile_shares[lane] = select(UNSHAPED, round(SHARE_STEPS * sum / max(weight, 1.0)) / 255.0, shaped && weight > 0.0);
+    workgroupBarrier();
+    let t = corner + own;
+    if (own.x % 4u == 0u && all(t >= job.lo) && all(t < job.hi)) {
+        let at = in_layer(job.mask, job.first + vec2i(t));
+        textureStore(cliff_out, vec2i(at.x >> 2u, at.y), job.mask >> 6u, vec4f(tile_shares[lane], tile_shares[lane + 1u], tile_shares[lane + 2u], tile_shares[lane + 3u]));
+    }
+    workgroupBarrier();
+}
+
+// The turn's key of a texel of the tile, at `at` in tile_heights: how far it is cliff (cliff_of, without the spread
+// that the filter takes over), or all of it where its normal turns more than the texels resolve; -1 where its height is
+// unknown. Its normal and turn are those of level_normal at the texel: an unknown neighbour continues the slope through
+// it.
+fn texel_key(at: u32, metres: f32) -> f32 {
+    let h = tile_heights[at];
+    if (!known(h)) {
+        return -1.0;
+    }
+    let we = continued(h, tile_heights[at - 1u], tile_heights[at + 1u]);
+    let ns = continued(h, tile_heights[at - 12u], tile_heights[at + 12u]);
+    let rise = vec2f(we.y - we.x, ns.x - ns.y);
+    let bend = vec2f(we.x + we.y, ns.x + ns.y) - 2.0 * h;
+    let across = dot(rise, rise) + 4.0 * metres * metres;
+    let z = 2.0 * metres * inverseSqrt(across);
+    let turn = length(bend) * 4.0 * metres / across;
+    return max(cliff_of(z, 0.0), smoothstep(UNRESOLVED.x, UNRESOLVED.y, turn));
+}
+
+// The heights before and after a texel of height h: an unknown one continues the slope through the texel, level
+// where both are unknown.
+fn continued(h: f32, before: f32, after: f32) -> vec2f {
+    let b = select(select(h, 2.0 * h - after, known(after)), before, known(before));
+    return vec2f(b, select(2.0 * h - b, after, known(after)));
+}
diff --git a/builder/web/src/lib/trailview/terrain/corners.ts b/builder/web/src/lib/trailview/terrain/corners.ts
index 84b8fd72d7..6a902e7f1a 100644
--- a/builder/web/src/lib/trailview/terrain/corners.ts
+++ b/builder/web/src/lib/trailview/terrain/corners.ts
@@ -2,7 +2,7 @@
 // apart, their kerb turns from the edge of the one to the edge of the other round an arc: the stamps paint
 // its asphalt and the sidewalk round it and hold their ground. A corner that
 // another line's band reaches into stays sharp, so its paint covers no other way or water.
-import { crossSlope, junctionWays, metresPerUnit, PAVED_CODES, ROAD, ROAD_CODE, splitThrough, walkOf, type Line } from './bins';
+import { crossSlope, junctionWays, metresPerUnit, PAVED_CODES, ROAD, ROAD_CODE, splitThrough, STREAM, walkOf, type Line } from './bins';
 import { gridOf, LEFT, near, RIGHT, type Grid } from './town';
 
 /**
@@ -28,6 +28,16 @@ interface Way { line: Line; v: number; step: number; ux: number; uy: number; ang
 
 const found = new WeakMap();
 const paired = new WeakMap>();
+/** The lines whose bands keep the corners of a tile's lines sharp, where keepBands holds them. */
+const bands = new WeakMap();
+
+/**
+ * Holds the bands of a tile's lines as they are now for its corners, which are made at their first read: a later
+ * change of a stream's line leaves them as they are. Only the streams change after this, so only they are copied.
+ */
+export function keepBands(lines: Line[]): void {
+    bands.set(lines, lines.map(line => (line.kind === STREAM ? { ...line, xy: line.xy.slice(), z: line.z.slice() } : line)));
+}
 
 /** Per road, the roads that its start and its end run on into: the other way of a through road that OSM splits at the junction, a bridge's or a tunnel's too. */
 export function partnersOf(lines: Line[]): Map {
@@ -73,7 +83,8 @@ function cornersIn(lines: Line[]): { corners: Corner[]; grid: Grid } {
             (at.get(key) ?? at.set(key, []).get(key)!).push({ line, v });
         }
     }
-    const all = segmentsOf(lines), partners = partnersOf(lines), corners: Corner[] = [];
+    const all = segmentsOf(bands.get(lines) ?? lines), partners = partnersOf(lines), corners: Corner[] = [];
+    bands.delete(lines);
     for (const here of at.values()) {
         if (here.every(({ line }) => line === here[0].line)) continue;
         const out = here.flatMap(({ line, v }) => [-1, 1].filter(step => v + step >= 0 && v + step < line.z.length).map(step => wayOut(line, v, step))).sort((p, q) => p.angle - q.angle);
diff --git a/builder/web/src/lib/trailview/terrain/culverts.ts b/builder/web/src/lib/trailview/terrain/culverts.ts
index c0a72cf12b..e92db5a64f 100644
--- a/builder/web/src/lib/trailview/terrain/culverts.ts
+++ b/builder/web/src/lib/trailview/terrain/culverts.ts
@@ -5,7 +5,7 @@
 import WATERWAY_RULES from '../../../../../../data/trailview/waterways.json' with { type: 'json' };
 import type { Feature } from '../stream/features';
 import { BRIDGE, metresPerUnit, PATH, RAIL, RIVER, ROAD, STREAM, walkOf, type Line } from './bins';
-import { cornersOf } from './corners';
+import { keepBands } from './corners';
 import { along, gridOf, LEFT, near, RIGHT } from './town';
 
 /** A ribbon stops this far past a way's edge or its sidewalk, as GIVE_WAY_M of water.wgsl: past a guard rail's posts, 0.67 m (roads/details.ts). */
@@ -338,7 +338,7 @@ function piecesOf(line: Line, { metres, total, at }: Ruler, cuts: Cut[]): Line[]
 /** Runs each stream on to the ways ahead of it, ends its ribbon at a mouth on each side of a road or a railway that it crosses and at each buried culvert, and returns the mouths. */
 export function standMouths(lines: Line[], buried: Set): CulvertMouth[] {
     // A corner's shape holds for the lines as they were joined: it stays sharp where a stream's ribbon would reach it, so a wall on that stream stands on no corner's paint.
-    cornersOf(lines);
+    keepBands(lines);
     const ways = waysOf(lines), mouths: CulvertMouth[] = [];
     joinSplits(lines, buried);
     runOnToWays(lines, buried, ways.gap);
diff --git a/builder/web/src/lib/trailview/terrain/device-cache.ts b/builder/web/src/lib/trailview/terrain/device-cache.ts
new file mode 100644
index 0000000000..e3b6c86c22
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/device-cache.ts
@@ -0,0 +1,131 @@
+// The device cache: what a worker makes of the release's tiles, kept in Cache Storage under the release and a
+// build version, the hash of the code that makes it (model.ts: the plan's cells with `ground=plan`, stamps.ts:
+// the stamp worker's nodes, houses.ts: the house records of a tile, tree-models.ts: the tree models, which no
+// tile changes). That code is a pure function of its input, so an entry is byte-equal to what the worker makes.
+// The least recently used entries leave past the cap.
+
+/**
+ * The device storage of each kind: past its cap, the least recently used entries of the kind go. Together
+ * 296 MiB; a view writes more cell bytes than stamp bytes. The cap of the trees holds the models of every species.
+ */
+export const CAPS = { cells: 192 * 2 ** 20, stamps: 64 * 2 ** 20, houses: 16 * 2 ** 20, trees: 24 * 2 ** 20 };
+/** The entry's first word, then the count of parts, their lengths in words and the SHA-256 of the parts. */
+const MAGIC = 0x4f424343;
+const DIGEST_WORDS = 8;
+/** The key of the index: each entry's bytes, least recently used first. */
+const INDEX = 'https://cache.invalid/index';
+/** The index is saved at most this often. */
+const SAVE_MS = 2000;
+
+const urlOf = (key: string) => `https://cache.invalid/${key}`;
+
+/** The SHA-256 of bytes or a string, as hex. */
+export async function sha256(data: BufferSource | string): Promise {
+    const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
+    return [...new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))].map(b => b.toString(16).padStart(2, '0')).join('');
+}
+
+/** An entry: the header, the SHA-256 of the parts and the parts. */
+export async function encode(parts: Uint32Array[]): Promise {
+    const payload = new Uint32Array(parts.reduce((sum, p) => sum + p.length, 0));
+    parts.reduce((at, p) => (payload.set(p, at), at + p.length), 0);
+    const head = new Uint32Array([MAGIC, parts.length, ...parts.map(p => p.length)]);
+    return new Blob([head, await crypto.subtle.digest('SHA-256', payload), payload]);
+}
+
+/** The parts of an entry, or undefined when it is partial or corrupt. */
+export async function decode(buffer: ArrayBuffer): Promise[] | undefined> {
+    if (buffer.byteLength % 4) return undefined;
+    const words = new Uint32Array(buffer);
+    if (words.length < 2 || words[0] !== MAGIC) return undefined;
+    const n = words[1], first = 2 + n + DIGEST_WORDS;
+    if (words.length < first) return undefined;
+    const lengths = [...words.subarray(2, 2 + n)];
+    if (first + lengths.reduce((a, b) => a + b, 0) !== words.length) return undefined;
+    const digest = new Uint32Array(await crypto.subtle.digest('SHA-256', words.subarray(first))), stored = words.subarray(2 + n, first);
+    if (!digest.every((w, i) => w === stored[i])) return undefined;
+    let at = first;
+    // Each part its own buffer: a kept rim does not hold the whole entry.
+    return lengths.map(length => words.slice(at, (at += length)));
+}
+
+export class DeviceCache {
+    private saving?: ReturnType;
+    /** Each entry's bytes, least recently used first. */
+    private readonly index = new Map();
+    /** Settles once the saved index is merged in: a read does not wait for it, a write and a save do. */
+    private readonly loaded: Promise;
+
+    private constructor(private readonly cache: Cache, private readonly cap: number) {
+        this.loaded = this.load().catch(() => {});
+    }
+
+    /**
+     * The cache of a kind, a release (any string that names its data) and a build version; undefined where
+     * the context has no Cache Storage. A cache of the kind for another release or build goes, in the background.
+     */
+    static async open(kind: string, release: string, build: string, cap: number): Promise {
+        if (!globalThis.caches) return undefined;
+        const prefix = `trailview-${kind}/`, name = `${prefix}${await sha256(release)}/${build}`;
+        void caches.keys().then(names => Promise.all(names.filter(other => other.startsWith(prefix) && other !== name).map(other => caches.delete(other)))).catch(() => {});
+        return new DeviceCache(await caches.open(name), cap);
+    }
+
+    /**
+     * Merges the saved index in before the entries that this session used. Entries that it does not know
+     * count as least recently used, with their bytes unknown until a read: the first to go past the cap.
+     */
+    private async load(): Promise {
+        const [saved, requests] = await Promise.all([this.cache.match(INDEX).then(r => r?.json()).catch(() => undefined) as Promise | undefined>, this.cache.keys()]);
+        const urls = new Set(requests.map(request => request.url).filter(url => url !== INDEX)), used = [...this.index];
+        this.index.clear();
+        for (const url of urls) if (!saved || !Object.hasOwn(saved, url)) this.index.set(url, 0);
+        for (const [url, bytes] of Object.entries(saved ?? {})) if (urls.has(url)) this.index.set(url, bytes);
+        for (const [url, bytes] of used) {
+            this.index.delete(url);
+            this.index.set(url, bytes);
+        }
+    }
+
+    /** The parts of an entry; a partial or corrupt entry goes and reads as missing. */
+    async read(key: string): Promise[] | undefined> {
+        const url = urlOf(key), response = await this.cache.match(url);
+        if (!response) return undefined;
+        const parts = await decode(await response.arrayBuffer());
+        this.index.delete(url);
+        if (parts) this.index.set(url, Number(response.headers.get('x-bytes')) || 0);
+        else await this.cache.delete(url);
+        this.save();
+        return parts;
+    }
+
+    /** Keeps an entry; the least recently used entries go until all fit the cap. A full storage drops the entry. */
+    async write(key: string, parts: Uint32Array[]): Promise {
+        const url = urlOf(key), blob = await encode(parts);
+        if (blob.size > this.cap) return;
+        await this.cache.put(url, new Response(blob, { headers: { 'x-bytes': String(blob.size) } }));
+        await this.loaded;
+        this.index.delete(url);
+        this.index.set(url, blob.size);
+        for (const old of this.index.keys()) {
+            if (this.bytes <= this.cap) break;
+            this.index.delete(old);
+            await this.cache.delete(old);
+        }
+        this.save();
+    }
+
+    /** The bytes of all entries that it knows the size of. */
+    get bytes(): number {
+        let sum = 0;
+        for (const bytes of this.index.values()) sum += bytes;
+        return sum;
+    }
+
+    private save(): void {
+        this.saving ??= setTimeout(() => {
+            this.saving = undefined;
+            void this.loaded.then(() => this.cache.put(INDEX, Response.json(Object.fromEntries(this.index)))).catch(() => {});
+        }, SAVE_MS);
+    }
+}
diff --git a/builder/web/src/lib/trailview/terrain/drawn-height.wgsl b/builder/web/src/lib/trailview/terrain/drawn-height.wgsl
index 920db44c5a..5fc4ad7cf4 100644
--- a/builder/web/src/lib/trailview/terrain/drawn-height.wgsl
+++ b/builder/web/src/lib/trailview/terrain/drawn-height.wgsl
@@ -114,6 +114,36 @@ fn entry(level: u32, t: vec2i) -> u32 {
     return lod_map[(i32(level) * MAP + slot.y) * MAP + slot.x];
 }
 
+// Catmull-Rom weights of the four texels about a part t.
+fn spline(t: f32) -> vec4f {
+    return 0.5 * vec4f(-t + 2.0 * t * t - t * t * t, 2.0 - 5.0 * t * t + 3.0 * t * t * t, t + 4.0 * t * t - 3.0 * t * t * t, -t * t + t * t * t);
+}
+
+// The bicubic height of the finest stored level up to `top` that knows all 16 texels about a point.
+fn stored_base(u: vec2i, top: u32) -> f32 {
+    for (var level = top; level >= COARSEST; level--) {
+        let t = texel_of_units(u, level);
+        let wx = spline(t.part.x);
+        let wy = spline(t.part.y);
+        var sum = 0.0;
+        var complete = true;
+        for (var j = 0; j < 4 && complete; j++) {
+            for (var i = 0; i < 4; i++) {
+                let h = texel_height(level, t.whole + vec2i(i - 1, j - 1), true);
+                if (!known(h)) {
+                    complete = false;
+                    break;
+                }
+                sum += h * wx[i] * wy[j];
+            }
+        }
+        if (complete) {
+            return sum;
+        }
+    }
+    return NONE;
+}
+
 // The height of a texel: the drawn page's, or with `stored` the raw stored page's. NONE where no page holds it or it is unknown.
 fn texel_height(level: u32, t: vec2i, stored: bool) -> f32 {
     let e = entry(level, t);
@@ -258,8 +288,10 @@ fn or_guess(h: vec2f, guess: vec2f) -> vec2f {
 
 // The bilinear normal of the finest level up to `top` that knows the 4 heights of the quad of a point,
 // as bilinear_rise: each texel's normal from its four neighbours. An unknown neighbour outside the quad
-// continues the quad's slope, so the difference across that texel is one-sided.
-fn level_normal(s: vec2f, top: u32) -> vec2f {
+// continues the quad's slope, so the difference across that texel is one-sided. In z, bilinear alike, how far
+// the normal turns from one texel to the next, in radians: per texel its slope's change from the texel before to
+// the one after (the heights' second differences along x and y) × z².
+fn level_normal(s: vec2f, top: u32) -> vec3f {
     for (var level = top; level >= COARSEST; level--) {
         let t = texel_of(s, level);
         let e = entry(level, t.whole) & 0xffffu;
@@ -285,13 +317,21 @@ fn level_normal(s: vec2f, top: u32) -> vec2f {
         let b = slope_normal(dx.y, dy.y, metres);
         let c = slope_normal(dx.z, dy.z, metres);
         let d = slope_normal(dx.w, dy.w, metres);
-        return mix(mix(a, b, t.part.x), mix(c, d, t.part.x), t.part.y);
+        let kx = vec4f(west.x, q.x, west.y, q.z) + vec4f(q.y, east.x, q.w, east.y) - 2.0 * q;
+        let ky = vec4f(north, q.xy) + vec4f(q.zw, south) - 2.0 * q;
+        let turn = sqrt(kx * kx + ky * ky) * 4.0 * metres / (dx * dx + dy * dy + 4.0 * metres * metres);
+        return mix(mix(vec3f(a, turn.x), vec3f(b, turn.y), t.part.x), mix(vec3f(c, turn.z), vec3f(d, turn.w), t.part.x), t.part.y);
     }
-    return vec2f(0.0);
+    return vec3f(0.0);
 }
 
 // The normal of the drawn surface in LOD space axes, with the same level and morph as its height.
 fn drawn_normal(s: vec2f) -> vec3f {
+    return drawn_relief(s).xyz;
+}
+
+// drawn_normal, and in w how far it turns from one texel to the next (level_normal).
+fn drawn_relief(s: vec2f) -> vec4f {
     let lambda = lod(s);
     let level = u32(ceil(lambda));
     var n = level_normal(s, level);
@@ -299,7 +339,7 @@ fn drawn_normal(s: vec2f) -> vec3f {
     if (morph > 0.0) {
         n = mix(n, level_normal(s, level - 1u), morph);
     }
-    return normalize(vec3f(n, sqrt(max(1.0 - dot(n, n), 1e-4))));
+    return vec4f(normalize(vec3f(n.xy, sqrt(max(1.0 - dot(n.xy, n.xy), 1e-4)))), n.z);
 }
 
 // A normal of LOD space axes in render space, with the linear part of the cubic.
diff --git a/builder/web/src/lib/trailview/terrain/drawn-mesh.wgsl b/builder/web/src/lib/trailview/terrain/drawn-mesh.wgsl
index c7f197bf99..6697c8d47b 100644
--- a/builder/web/src/lib/trailview/terrain/drawn-mesh.wgsl
+++ b/builder/web/src/lib/trailview/terrain/drawn-mesh.wgsl
@@ -63,14 +63,19 @@ struct Place {
 }
 
 fn vertex_place(u: vec2i, level: u32, snapping: bool) -> Place {
+    return vertex_place_by(u, level, snapping, snapping);
+}
+
+// vertex_place with the snap of the vertex's own level (`own`) and of the coarser level that it morphs toward apart.
+fn vertex_place_by(u: vec2i, level: u32, own: bool, coarser: bool) -> Place {
     let morph = clamp(f32(level) - lod(lod_space(vec2f(u))), 0.0, 1.0);
-    let moved = u + snap(u, level, snapping);
+    let moved = u + snap(u, level, own);
     let at = lod_space(vec2f(moved));
     if (morph <= 0.0) {
         return Place(at, moved, moved, morph);
     }
     let even = u - ((surface.anchor + u) & vec2i(1 << (24u - level)));
-    let settled = even + snap(even, level - 1u, snapping);
+    let settled = even + snap(even, level - 1u, coarser);
     return Place(mix(at, lod_space(vec2f(settled)), morph), moved, settled, morph);
 }
 
@@ -90,7 +95,11 @@ fn place_height(p: Place, level: u32) -> f32 {
 
 // The mesh vertex of a level at a grid point.
 fn grid_vertex(u: vec2i, level: u32, snapping: bool) -> Vertex {
-    let p = vertex_place(u, level, snapping);
+    return grid_vertex_by(u, level, snapping, snapping);
+}
+
+fn grid_vertex_by(u: vec2i, level: u32, own: bool, coarser: bool) -> Vertex {
+    let p = vertex_place_by(u, level, own, coarser);
     return Vertex(p.at, place_height(p, level));
 }
 
diff --git a/builder/web/src/lib/trailview/terrain/features.wgsl b/builder/web/src/lib/trailview/terrain/features.wgsl
index 3137c60901..d3cda594b1 100644
--- a/builder/web/src/lib/trailview/terrain/features.wgsl
+++ b/builder/web/src/lib/trailview/terrain/features.wgsl
@@ -21,6 +21,17 @@ struct Masks {
 // vertex's move onto the nearest road edge in units, x and y as 16-bit signed halves. The stamp pass
 // writes it.
 @group(3) @binding(2) var snaps: texture_2d_array;
+// With `ground=plan`, per mask texel: the paint of the records' paved labels in the mask's format (the distance
+// to the paved outline, the walk byte, the metres across the host, the finish code with the material of the top in
+// place of the flags), and how far their heights moved the ground from the plain terrain, 0 to MOVED_RANGE_M as
+// 0..1, four texels of a row in one texel. The stamp pass writes them.
+@group(3) @binding(3) var paint_texels: texture_2d_array;
+@group(3) @binding(4) var moved_texels: texture_2d_array;
+// With `ground=plan`, per mask texel: the cliff share of cliff.wgsl in SHARE_STEPS steps, or UNSHAPED where the
+// plan did not move the ground about it, four texels of a row in one texel.
+@group(3) @binding(5) var cliff_texels: texture_2d_array;
+const SHARE_STEPS: f32 = 254.0;
+const UNSHAPED: f32 = 1.0;
 
 const WALL: u32 = 1u;
 const CONFLICT: u32 = 2u;
@@ -32,6 +43,7 @@ const MASK_LEVEL: u32 = 16u;
 // As MASK_RANGE and MASK_KNEE of stamp.wgsl.
 const MASK_M: f32 = 12.75;
 const MASK_KNEE: f32 = 0.5;
+const MOVED_RANGE_M: f32 = 0.5;
 // Paint hands over to the corridors this far inside what they hold.
 const CORRIDOR_FADE_M: f32 = 40.0;
 // Plants and stones keep this far off a trodden way's middle, and a little less off its tread (trail_look of
@@ -83,7 +95,8 @@ struct Mask {
     edge: f32,
     // The share of the texels on a road's cut or fill face.
     face: f32,
-    // The surface code and the flags.
+    // The surface code and the flags. A paint mask holds the material of the way's top in place of the flags, so
+    // its `kind.y` and `face` are no flags: no reader takes flags from a paint mask.
     kind: vec2u,
     // The level of the page that holds it; 0 where no page within reach has a mask.
     level: u32,
@@ -107,6 +120,8 @@ struct Mask {
     trodden: bool,
     // Whether the nearest texel's road wears lines.
     marked: bool,
+    // The mask layer of the page that holds the nearest texel.
+    page: u32,
 }
 
 // Metres across a texel of a level in texel row `row`, as unit_metres of stamp-core.wgsl.
@@ -115,18 +130,19 @@ fn texel_metres(level: u32, row: i32) -> f32 {
     return 2.0 * 3.14159265 * 6371000.0 / 1073741824.0 / cosh(3.14159265 * (1.0 - f32(row << shift) / 536870912.0)) * f32(1 << shift);
 }
 
-// The metres from the middle of a texel's road.
-fn across_metres(texel: vec4f) -> f32 {
+// The metres from the middle of a texel's road. The paint texture holds a road's on the asinh scale of the
+// distance, so a centre line keeps the steps of an edge.
+fn across_metres(texel: vec4f, paint: bool) -> f32 {
     let track = (u32(round(texel.w * 255.0)) & 15u) >= RAIL_CODE;
-    return (texel.z - 0.5) * 2.0 * select(MASK_M, TRACK_M, track);
+    return select((texel.z - 0.5) * 2.0 * select(MASK_M, TRACK_M, track), mask_metres(texel.z), paint && !track);
 }
 
 // The half-width of the road that a texel's distances belong to; a track's from its code, as `across`
 // stops at ±TRACK_M.
-fn half_width(texel: vec4f) -> f32 {
+fn half_width(texel: vec4f, paint: bool) -> f32 {
     let code = u32(round(texel.w * 255.0)) & 15u;
     let track = select(RAIL_HALF_M, NARROW_HALF_M, ((code - RAIL_CODE) & 1u) == 1u);
-    return select(abs(across_metres(texel)) - mask_metres(texel.x), track, code >= RAIL_CODE);
+    return select(abs(across_metres(texel, paint)) - mask_metres(texel.x), track, code >= RAIL_CODE);
 }
 
 // The mask at a point, from the finest page at or above `top` that has a mask: the shapes and the
@@ -139,45 +155,132 @@ fn mask_at(s: vec2f, top: u32, roads: bool) -> Mask {
         let whole = t.whole + vec2i(round(t.part));
         let slot = mask_of(level, whole);
         if (slot != 0u) {
-            let page = slot - 1u;
-            let byte = mask_byte(page, whole);
+            let byte = mask_byte(slot - 1u, whole);
             if (roads && (byte & 15u) == 0u && ((byte >> 4u) & TAKEN) == 0u) {
                 break;
             }
+            return mask_in(mask_texels, s, level, slot - 1u, false);
+        }
+    }
+    return Mask(0.0, 0.0, vec2u(0u), 0u, vec2f(0.0), 0.0, 0.0, 0.0, vec2f(0.0), 0.0, false, false, 0u);
+}
+
+// The mask at a point of the page in layer `page` of `texels` (a texture in the mask's format, or with `paint`
+// the paint texture's) at `level`.
+fn mask_in(texels: texture_2d_array, s: vec2f, level: u32, page: u32, paint: bool) -> Mask {
+    let t = texel_of(s, level);
+    let whole = t.whole + vec2i(round(t.part));
+    let first = (whole >> vec2u(8u)) << vec2u(8u);
+    let a = clamp(t.whole, first, first + vec2i(255));
+    let b = clamp(t.whole + vec2i(1), first, first + vec2i(255));
+    let ab = array(texel_in(texels, page, a), texel_in(texels, page, vec2i(b.x, a.y)), texel_in(texels, page, vec2i(a.x, b.y)), texel_in(texels, page, b));
+    let nearest = texel_in(texels, page, whole);
+    let byte = u32(round(nearest.w * 255.0));
+    // The paving of a footway takes the texels past a sidewalk. The distances of the two
+    // are to different edges, and a mix of them reads as a road: a texel of the other kind counts as the nearest.
+    let paving = (byte & 15u) == PAVING_CODE;
+    var e = array(mask_metres(ab[0].x), mask_metres(ab[1].x), mask_metres(ab[2].x), mask_metres(ab[3].x));
+    for (var i = 0; i < 4; i++) {
+        if (((u32(round(ab[i].w * 255.0)) & 15u) == PAVING_CODE) != paving) {
+            e[i] = mask_metres(nearest.x);
+        }
+    }
+    let edge = mix(mix(e[0], e[1], t.part.x), mix(e[2], e[3], t.part.x), t.part.y);
+    let face = mix(mix(faced(ab[0]), faced(ab[1]), t.part.x), mix(faced(ab[2]), faced(ab[3]), t.part.x), t.part.y);
+    // Texel rows run along -y of LOD space.
+    let rise = vec2f(mix(e[1] - e[0], e[3] - e[2], t.part.y), -mix(e[2] - e[0], e[3] - e[1], t.part.x));
+    let away = select(vec2f(0.0), normalize(rise), dot(rise, rise) > 0.0);
+    let half = mix(mix(half_width(ab[0], paint), half_width(ab[1], paint), t.part.x), mix(half_width(ab[2], paint), half_width(ab[3], paint), t.part.x), t.part.y);
+    // The sleepers of the nearest texel, carried on along the track: across the rise of the metres
+    // from its middle, which grow to the track's left. A fraction cannot be filtered across its wrap.
+    let m = array(across_metres(ab[0], paint), across_metres(ab[1], paint), across_metres(ab[2], paint), across_metres(ab[3], paint));
+    let across = mix(mix(m[0], m[1], t.part.x), mix(m[2], m[3], t.part.x), t.part.y);
+    let middle = vec2f(mix(m[1] - m[0], m[3] - m[2], t.part.y), mix(m[2] - m[0], m[3] - m[1], t.part.x));
+    let ahead = select(vec2f(0.0), normalize(vec2f(middle.y, -middle.x)), dot(middle, middle) > 0.0);
+    let axis = select(away, normalize(vec2f(middle.x, -middle.y)), dot(middle, middle) > 0.0);
+    let y = nearest.y;
+    let sleepers = y + dot(t.part - round(t.part), ahead) * texel_metres(level, whole.y) / SLEEPER_SPACING_M;
+    let past = select(u32(round(y * 255.0)), 0u, (byte & 15u) >= RAIL_CODE);
+    return Mask(edge, face, vec2u(byte & 15u, byte >> 4u), level, away, half, sleepers, across, axis, walk_metres(past), is_trodden(past), is_marked(past), page);
+}
+
+fn texel_in(texels: texture_2d_array, page: u32, t: vec2i) -> vec4f {
+    return textureLoad(texels, in_layer(page, t), page >> 6u, 0);
+}
+
+fn moved_texel(page: u32, t: vec2i) -> f32 {
+    let at = in_layer(page, t);
+    return textureLoad(moved_texels, vec2i(at.x >> 2u, at.y), page >> 6u, 0)[at.x & 3] * MOVED_RANGE_M;
+}
+
+// The metres that the records' heights moved the ground at a point, from the finest page at or above `top`
+// that has a mask, filtered between the four texels about it in that page; 0 where no page has one.
+fn moved_at(s: vec2f, top: u32) -> f32 {
+    for (var level = top; level >= MASK_LEVEL; level--) {
+        let t = texel_of(s, level);
+        let whole = t.whole + vec2i(round(t.part));
+        let slot = mask_of(level, whole);
+        if (slot != 0u) {
             let first = (whole >> vec2u(8u)) << vec2u(8u);
             let a = clamp(t.whole, first, first + vec2i(255));
             let b = clamp(t.whole + vec2i(1), first, first + vec2i(255));
-            let ab = array(shape_at(page, a), shape_at(page, vec2i(b.x, a.y)), shape_at(page, vec2i(a.x, b.y)), shape_at(page, b));
-            let nearest = shape_at(page, whole);
-            // The paving of a footway takes the texels past a sidewalk. The distances of the two
-            // are to different edges, and a mix of them reads as a road: a texel of the other kind counts as the nearest.
-            let paving = (byte & 15u) == PAVING_CODE;
-            var e = array(mask_metres(ab[0].x), mask_metres(ab[1].x), mask_metres(ab[2].x), mask_metres(ab[3].x));
-            for (var i = 0; i < 4; i++) {
-                if (((u32(round(ab[i].w * 255.0)) & 15u) == PAVING_CODE) != paving) {
-                    e[i] = mask_metres(nearest.x);
-                }
-            }
-            let edge = mix(mix(e[0], e[1], t.part.x), mix(e[2], e[3], t.part.x), t.part.y);
-            let face = mix(mix(faced(ab[0]), faced(ab[1]), t.part.x), mix(faced(ab[2]), faced(ab[3]), t.part.x), t.part.y);
-            // Texel rows run along -y of LOD space.
-            let rise = vec2f(mix(e[1] - e[0], e[3] - e[2], t.part.y), -mix(e[2] - e[0], e[3] - e[1], t.part.x));
-            let away = select(vec2f(0.0), normalize(rise), dot(rise, rise) > 0.0);
-            let half = mix(mix(half_width(ab[0]), half_width(ab[1]), t.part.x), mix(half_width(ab[2]), half_width(ab[3]), t.part.x), t.part.y);
-            // The sleepers of the nearest texel, carried on along the track: across the rise of the metres
-            // from its middle, which grow to the track's left. A fraction cannot be filtered across its wrap.
-            let m = array(across_metres(ab[0]), across_metres(ab[1]), across_metres(ab[2]), across_metres(ab[3]));
-            let across = mix(mix(m[0], m[1], t.part.x), mix(m[2], m[3], t.part.x), t.part.y);
-            let middle = vec2f(mix(m[1] - m[0], m[3] - m[2], t.part.y), mix(m[2] - m[0], m[3] - m[1], t.part.x));
-            let ahead = select(vec2f(0.0), normalize(vec2f(middle.y, -middle.x)), dot(middle, middle) > 0.0);
-            let axis = select(away, normalize(vec2f(middle.x, -middle.y)), dot(middle, middle) > 0.0);
-            let y = nearest.y;
-            let sleepers = y + dot(t.part - round(t.part), ahead) * texel_metres(level, whole.y) / SLEEPER_SPACING_M;
-            let past = select(u32(round(y * 255.0)), 0u, (byte & 15u) >= RAIL_CODE);
-            return Mask(edge, face, vec2u(byte & 15u, byte >> 4u), level, away, half, sleepers, across, axis, walk_metres(past), is_trodden(past), is_marked(past));
+            let top_row = mix(moved_texel(slot - 1u, a), moved_texel(slot - 1u, vec2i(b.x, a.y)), t.part.x);
+            return mix(top_row, mix(moved_texel(slot - 1u, vec2i(a.x, b.y)), moved_texel(slot - 1u, b), t.part.x), t.part.y);
+        }
+    }
+    return 0.0;
+}
+
+// How far ground_colour turns the normal at a point toward the coarse one, with the level and morph of drawn_relief:
+// between the cliff shares of the texels about it (cliff.wgsl), each `key` (the look's own, at the point) where its
+// page has no mask or the plan did not move the ground about it.
+fn cliff_at(s: vec2f, key: f32) -> f32 {
+    let lambda = lod(s);
+    let level = u32(ceil(lambda));
+    var share = cliff_in(s, level, key);
+    let morph = f32(level) - lambda;
+    if (morph > 0.0) {
+        share = mix(share, cliff_in(s, level - 1u, key), morph);
+    }
+    return share;
+}
+
+fn cliff_in(s: vec2f, level: u32, key: f32) -> f32 {
+    if (level < MASK_LEVEL) {
+        return key;
+    }
+    let t = texel_of(s, level);
+    var slots = vec4u(mask_of(level, t.whole));
+    if (!in_one_page(t.whole)) {
+        slots = vec4u(slots.x, mask_of(level, t.whole + vec2i(1, 0)), mask_of(level, t.whole + vec2i(0, 1)), mask_of(level, t.whole + 1));
+    } else if (slots.x == 0u) {
+        return key;
+    }
+    let top = mix(cliff_texel(slots.x, t.whole, key), cliff_texel(slots.y, t.whole + vec2i(1, 0), key), t.part.x);
+    return mix(top, mix(cliff_texel(slots.z, t.whole + vec2i(0, 1), key), cliff_texel(slots.w, t.whole + 1, key), t.part.x), t.part.y);
+}
+
+// The cliff share of a texel in the mask layer + 1 `slot`, or `key`.
+fn cliff_texel(slot: u32, t: vec2i, key: f32) -> f32 {
+    if (slot == 0u) {
+        return key;
+    }
+    let at = in_layer(slot - 1u, t);
+    let v = textureLoad(cliff_texels, vec2i(at.x >> 2u, at.y), (slot - 1u) >> 6u, 0)[at.x & 3];
+    return select(v * 255.0 / SHARE_STEPS, key, v > (SHARE_STEPS + 0.5) / 255.0);
+}
+
+// The metres from a point to the records' paved outline (negative inside), from the paint of the finest page at
+// or above `top` that has a mask; MASK_M where none has one.
+fn paved_edge(s: vec2f, top: u32) -> f32 {
+    for (var level = top; level >= MASK_LEVEL; level--) {
+        let t = texel_of(s, level);
+        let slot = mask_of(level, t.whole + vec2i(round(t.part)));
+        if (slot != 0u) {
+            return mask_in(paint_texels, s, level, slot - 1u, true).edge;
         }
     }
-    return Mask(0.0, 0.0, vec2u(0u), 0u, vec2f(0.0), 0.0, 0.0, 0.0, vec2f(0.0), 0.0, false, false);
+    return MASK_M;
 }
 
 // Whether the mask keeps a thing off a point: in water or in a building, on a road, its sidewalk, a path or
diff --git a/builder/web/src/lib/trailview/terrain/heights.wgsl b/builder/web/src/lib/trailview/terrain/heights.wgsl
new file mode 100644
index 0000000000..21a5533ab0
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/heights.wgsl
@@ -0,0 +1,1282 @@
+// The heights of the one road model: the crate's `faces::heights::height_at`, line for line, in f32.
+// Per point, each line near it gives its own surface, its distance past its core and a presence; the
+// paved field is a normalized painter of these surfaces in which each pair of records blends as far as
+// they agree and the greater one rules inside its core. Slopes start from the face plan's paved outline
+// (the records' outline edges): per host line a fill and a cut over its edges, released at the reach,
+// and the ground is a smooth min(cut, max(T, fill)), where a line's cut rises to the bank of the other
+// lines' fills, a wall class's up to its highest wall and then at its steepest cut. The ground (the terrain and
+// the slopes) stays under every deck's ceiling.
+// #include records.wgsl
+
+const H_SLOTS: u32 = 10u;
+// The pairs of H_SLOTS records.
+const H_PAIRS: u32 = 45u;
+const H_QUADS: u32 = 4u;
+// The most regions beyond a region's edges that weigh at a point, as heights::REGIONS.
+const H_REGIONS: u32 = 2u;
+// The heights' rule words follow the block's head (heights::RULES of the crate).
+const H_RULES_AT: u32 = 15u;
+// The words of an outline edge, its grade's steps per metre and its turn's steps per π (records::EDGE,
+// GRADE_STEPS, TURN_STEPS).
+const H_EDGE: u32 = 10u;
+const H_TURN_STEPS: f32 = 32767.0;
+const H_GRADE_STEPS: f32 = 4096.0;
+// An outline edge's cone reaches this many frame units past its line into its paved face before it falls
+// on at face_max (heights::SIDE_UNITS).
+const H_SIDE_UNITS: f32 = 32.0;
+// HRec.rank and HLine.rank: the class rank below H_FLAGS, the line's flags from it on (a wall class, a
+// rail, line water).
+const H_FLAGS: u32 = 1u << 24u;
+const H_WALL: u32 = 1u << 31u;
+const H_RAIL: u32 = 1u << 30u;
+const H_WATER: u32 = 1u << 29u;
+
+// The rule values of heights, as heights::HeightRules: read from the block by height_at.
+struct HRules {
+    feather_min: f32,
+    blend_steep: f32,
+    leg_reach: f32,
+    health_margin: f32,
+    health_width: f32,
+    frame_tilt: f32,
+    round: f32,
+    fade_share: f32,
+    fade_gap: f32,
+    toe_per_m: f32,
+    toe_max: f32,
+    toe_span: f32,
+    toe_gap_min: f32,
+    via_fade: f32,
+    band_fade: f32,
+    mitre_band: f32,
+    budget_round: f32,
+    wall_max: f32,
+    face_max: f32,
+    region_fade: f32,
+    ceiling_release: f32,
+    legs_wall: bool,
+}
+var H: HRules;
+// The whole metres that height_at takes off every absolute height and adds back at the end: f32 sums of
+// heights near the plain terrain keep their sub-millimetre steps on high ground.
+var H_BASE: f32;
+
+fn h_rules(block: u32) -> HRules {
+    let r = block + H_RULES_AT;
+    return HRules(mf(r), mf(r + 1u), mf(r + 2u), mf(r + 3u), mf(r + 4u), mf(r + 5u), mf(r + 6u), mf(r + 7u), mf(r + 8u), mf(r + 9u), mf(r + 10u), mf(r + 11u), mf(r + 12u), mf(r + 13u), mf(r + 14u), mf(r + 15u), mf(r + 16u), mf(r + 17u), mf(r + 18u), mf(r + 20u), mf(r + 22u), mw(r + 23u) == 1u);
+}
+
+// An unknown terrain where an outline edge's cones let go, or an unknown grade.
+const H_UNKNOWN: f32 = -1e9;
+const H_BIG: f32 = 1e9;
+
+// The kind of rule that gave a height, as heights::Kind.
+const H_TERRAIN: f32 = 0.0;
+const H_SLOPE: f32 = 1.0;
+const H_PAVED: f32 = 2.0;
+
+fn h_smooth(x: f32) -> f32 {
+    let c = clamp(x, 0.0, 1.0);
+    return c * c * (3.0 - 2.0 * c);
+}
+
+fn h_phi(x: f32) -> f32 {
+    return 1.0 - h_smooth(x);
+}
+
+// The width of the toe's smooth min/max at d metres past the outline, levelling at `level` or
+// H.toe_max, as heights::toe_width.
+fn h_toe_width(d: f32, level: f32) -> f32 {
+    let most = min(level, H.toe_max);
+    let x = min(H.toe_per_m * d / (2.0 * most), 1.0);
+    return most * (1.0 - (1.0 - x) * (1.0 - x));
+}
+
+// The lesser of two widths with no kink where they cross, as heights::soft_min.
+fn h_soft_min(a: f32, b: f32) -> f32 {
+    let lo = min(a, b);
+    let r = lo / max(a, b);
+    return select(lo / sqrt(sqrt(1.0 + r * r * r * r)), lo, lo <= 0.0);
+}
+
+fn h_smin(a: f32, b: f32, k: f32) -> f32 {
+    if (k <= 0.0) {
+        return min(a, b);
+    }
+    let h = max(k - abs(a - b), 0.0) / k;
+    return min(a, b) - h * h * k * 0.25;
+}
+
+fn h_smax(a: f32, b: f32, k: f32) -> f32 {
+    return -h_smin(-a, -b, k);
+}
+
+fn h_unit(a: vec2f) -> vec2f {
+    let n = length(a);
+    return select(vec2f(1.0, 0.0), a / n, n > 0.0);
+}
+
+struct HLine {
+    first: u32,
+    count: u32,
+    cut: f32,
+    fill: f32,
+    reach: f32,
+    rank: u32,
+    side: f32,
+    ret: f32,
+    // The class's steepest fill and cut of the no-room rule.
+    fill_max: f32,
+    cut_max: f32,
+    // The fill cone starts this far over its edge and this far past it (water's dyke).
+    rise: f32,
+    crest: f32,
+}
+
+fn h_line(block: u32, l: u32) -> HLine {
+    let at = block + mw(block + 6u) + M_LINE * l;
+    let f = mw(at + 1u);
+    let rank = mw(at + 7u) | select(0u, H_WALL, (f & M_WALL) != 0u) | select(0u, H_RAIL, (f & M_RAIL) != 0u) | select(0u, H_WATER, (f & M_WATER) != 0u);
+    return HLine(mw(at + 2u), mw(at + 3u), mf(at + 4u), mf(at + 5u), mf(at + 6u), rank, mf(at + 8u) + mf(at + 9u), mf(at + 10u), mf(at + 14u), mf(at + 15u), mf(at + 16u), mf(at + 17u));
+}
+
+// Whether line l of the block is water; false for none.
+fn h_line_water(block: u32, l: u32) -> bool {
+    return (m_line_finish(block, l) & M_WATER) != 0u;
+}
+
+struct HSample {
+    p: vec2f,
+    h: f32,
+    z: f32,
+    bank: f32,
+    grade: f32,
+}
+
+// A height word less H_BASE, H_UNKNOWN where it is unknown.
+fn h_known_word(i: u32) -> f32 {
+    let w = mw(i);
+    return select(bitcast(w) - H_BASE, H_UNKNOWN, (w & 0x7f800000u) == 0x7f800000u);
+}
+
+fn h_sample(block: u32, ln: HLine, i: u32, mpu: f32) -> HSample {
+    let at = block + mw(block + 7u) + M_SAMPLE * (ln.first + i);
+    return HSample(vec2f(mi(at), mi(at + 1u)), mf(at + 2u) * mpu, mf(at + 5u) - H_BASE, mf(at + 6u), mf(at + 7u));
+}
+
+// The mitre direction at sample i and the health radius on a side (+1 left, −1 right).
+fn h_mitre(block: u32, ln: HLine, i: u32) -> vec2f {
+    let at = block + mw(block + 7u) + M_SAMPLE * (ln.first + i);
+    return vec2f(mf(at + 8u), mf(at + 9u));
+}
+
+fn h_rho(block: u32, ln: HLine, i: u32, side: f32) -> f32 {
+    let at = block + mw(block + 7u) + M_SAMPLE * (ln.first + i);
+    return mf(at + select(11u, 10u, side > 0.0));
+}
+
+fn h_hermite(z0: f32, z1: f32, m0: f32, m1: f32, t: f32) -> f32 {
+    let t2 = t * t;
+    let t3 = t2 * t;
+    return (2.0 * t3 - 3.0 * t2 + 1.0) * z0 + (t3 - 2.0 * t2 + t) * m0 + (-2.0 * t3 + 3.0 * t2) * z1 + (t3 - t2) * m1;
+}
+
+// The frame's health at seg metres from the line toward a health radius r, as heights::health.
+fn h_health(r: f32, seg: f32) -> f32 {
+    return h_smooth((r - seg - H.health_margin) / H.health_width);
+}
+
+// The frame's units across at q in the quad of segment a, a + ab with the mitres ta and tb, at its
+// share t (signed, + left), as heights::across.
+fn h_across(q: vec2f, a: vec2f, ab: vec2f, ta: vec2f, tb: vec2f, t: f32) -> f32 {
+    let m = h_unit(ta + t * (tb - ta));
+    let v = q - a;
+    let along = dot(ab, m);
+    let f = select(0.0, dot(v, m) / along, along != 0.0);
+    return -m_cross(m, v - f * ab);
+}
+
+struct HFrame {
+    ok: bool,
+    z: f32,
+    delta: f32,
+    nu: f32,
+}
+
+// Segment i of a line at q: in its mitre quad, or past the line's first or last sample, as
+// heights::segment_of.
+fn h_segment(block: u32, ln: HLine, i: u32, sa: HSample, sb: HSample, q: vec2f, mpu: f32) -> HFrame {
+    var f = HFrame(false, 0.0, 0.0, 0.0);
+    let ta = h_mitre(block, ln, i);
+    let tb = h_mitre(block, ln, i + 1u);
+    let da = dot(q - sa.p, ta);
+    let db = dot(sb.p - q, tb);
+    let first = i == 0u;
+    let last = i + 2u == ln.count;
+    let ab = sb.p - sa.p;
+    let len = length(ab);
+    if (len <= 0.0) {
+        return f;
+    }
+    let u = ab / len;
+    let lateral = -m_cross(u, q - sa.p) * mpu;
+    let len_m = len * mpu;
+    var t = 0.0;
+    if (da >= 0.0 && db >= 0.0) {
+        t = select(0.5, da / (da + db), da + db > 0.0);
+        f.z = h_hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, t);
+        f.delta = h_across(q, sa.p, ab, ta, tb, t) * mpu;
+        let rl = mpu / ((1.0 - t) / h_rho(block, ln, i, 1.0) + t / h_rho(block, ln, i + 1u, 1.0));
+        let rr = mpu / ((1.0 - t) / h_rho(block, ln, i, -1.0) + t / h_rho(block, ln, i + 1u, -1.0));
+        f.nu = h_health(rl, f.delta) * h_health(rr, -f.delta);
+    } else if (first && da < 0.0 && db >= 0.0) {
+        let past = -dot(q - sa.p, u) * mpu;
+        t = 0.0;
+        f.z = sa.z - sa.grade * past;
+        f.delta = lateral;
+        f.nu = h_health(h_rho(block, ln, i, 1.0) * mpu, lateral) * h_health(h_rho(block, ln, i, -1.0) * mpu, -lateral);
+    } else if (last && db < 0.0 && da >= 0.0) {
+        let past = dot(q - sb.p, u) * mpu;
+        t = 1.0;
+        f.z = sb.z + sb.grade * past;
+        f.delta = lateral;
+        f.nu = h_health(h_rho(block, ln, i + 1u, 1.0) * mpu, lateral) * h_health(h_rho(block, ln, i + 1u, -1.0) * mpu, -lateral);
+    } else {
+        return f;
+    }
+    // The bank tilts about the frame's metres across, and neighbour quads blend over a band about their
+    // mitre line.
+    f.z += (sa.bank + t * (sb.bank - sa.bank)) * f.delta;
+    if (da >= 0.0 && db >= 0.0) {
+        let own = (da + db) * mpu;
+        if (i > 0u && da * mpu < min(H.mitre_band, own / 2.0)) {
+            f.z = h_mitre_band(f.z, h_surface(block, ln, i - 1u, q, mpu), da * mpu, own);
+        }
+        if (i + 2u < ln.count && db * mpu < min(H.mitre_band, own / 2.0)) {
+            f.z = h_mitre_band(f.z, h_surface(block, ln, i + 1u, q, mpu), db * mpu, own);
+        }
+    }
+    f.ok = true;
+    return f;
+}
+
+// A quad's surface z at x metres from its mitre line blended with the neighbour's carried on past it
+// (n: its surface and its length through q, metres), as heights::mitre_band.
+fn h_mitre_band(z: f32, n: vec2f, x: f32, own: f32) -> f32 {
+    if (n.y <= 0.0) {
+        return z;
+    }
+    let w = 1.0 / (1.0 / H.mitre_band + 2.0 / own + 2.0 / n.y);
+    let s = h_smooth((x / w + 1.0) / 2.0);
+    return s * z + (1.0 - s) * n.x;
+}
+
+// Segment j's surface at q past its mitre quad and its length through q (0 when not positive), as
+// heights::surface.
+fn h_surface(block: u32, ln: HLine, j: u32, q: vec2f, mpu: f32) -> vec2f {
+    let sa = h_sample(block, ln, j, mpu);
+    let sb = h_sample(block, ln, j + 1u, mpu);
+    let da = dot(q - sa.p, h_mitre(block, ln, j));
+    let db = dot(sb.p - q, h_mitre(block, ln, j + 1u));
+    let ab = sb.p - sa.p;
+    let len = length(ab);
+    if (da + db <= 0.0 || len <= 0.0) {
+        return vec2f(0.0, 0.0);
+    }
+    let t = da / (da + db);
+    let len_m = len * mpu;
+    let n = h_across(q, sa.p, ab, h_mitre(block, ln, j), h_mitre(block, ln, j + 1u), t) * mpu;
+    let z = h_hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, t) + (sa.bank + t * (sb.bank - sa.bank)) * n;
+    return vec2f(z, (da + db) * mpu);
+}
+
+struct HRec {
+    line: u32,
+    rank: u32,
+    // The glob order of its first sample: the painter's order among equal classes.
+    glob: u32,
+    z: f32,
+    d: f32,
+    feather: f32,
+    ret: f32,
+}
+
+struct HPoint {
+    recs: array,
+    n: u32,
+    // rel[h_pair(i, j)]: how much a fan relates records i and j at the point; 0 where no fan does.
+    rel: array,
+}
+
+// The index of the pair of records i and j (i != j) in a triangle of H_PAIRS.
+fn h_pair(i: u32, j: u32) -> u32 {
+    let a = min(i, j);
+    let b = max(i, j);
+    return b * (b - 1u) / 2u + a;
+}
+
+// Whether record a goes before record b in the painter's order: class rank, then the global key.
+fn h_before(a: HRec, b: HRec) -> bool {
+    let ra = a.rank % H_FLAGS;
+    let rb = b.rank % H_FLAGS;
+    return ra < rb || (ra == rb && (a.glob < b.glob || (a.glob == b.glob && a.line < b.line)));
+}
+
+// Insert a record in the painter's order, as heights::present: past H_SLOTS records the last by it go,
+// but never the labels' material lines.
+fn h_insert(hp: ptr, r: HRec, keep: vec2u) {
+    if ((*hp).n == H_SLOTS) {
+        var last = H_SLOTS;
+        for (var k = 0u; k < H_SLOTS; k++) {
+            let l = (*hp).recs[k].line;
+            if (l != keep.x && l != keep.y) {
+                last = k;
+            }
+        }
+        let kept = r.line == keep.x || r.line == keep.y;
+        if (last == H_SLOTS || (!kept && !h_before(r, (*hp).recs[last]))) {
+            return;
+        }
+        for (var k = last; k + 1u < H_SLOTS; k++) {
+            (*hp).recs[k] = (*hp).recs[k + 1u];
+        }
+        (*hp).n--;
+    }
+    var j = (*hp).n;
+    loop {
+        if (j == 0u || !h_before(r, (*hp).recs[j - 1u])) {
+            break;
+        }
+        (*hp).recs[j] = (*hp).recs[j - 1u];
+        j--;
+    }
+    (*hp).recs[j] = r;
+    (*hp).n++;
+}
+
+fn h_glob(block: u32, ln: HLine) -> u32 {
+    return mw(block + mw(block + 7u) + M_SAMPLE * ln.first + 4u);
+}
+
+// The distance from q to the segment a, b: q − a first, as heights::to_segment.
+fn h_point_segment(a: vec2f, b: vec2f, q: vec2f) -> f32 {
+    let u = b - a;
+    let l2 = dot(u, u);
+    let f = select(0.0, clamp(dot(q - a, u) / l2, 0.0, 1.0), l2 > 0.0);
+    return length(q - a - f * u);
+}
+
+// Metres from q to the outer edge of the slope band, from the edges of q's bin, as
+// heights::slope_edge.
+fn h_slope_edge(block: u32, q: vec2f, mpu: f32) -> f32 {
+    let head = m_bin_head(block, q);
+    if (head == 0u) {
+        return H_BIG;
+    }
+    var at = block + mw(head);
+    var best = H_BIG;
+    for (var c = 0u; c < (mw(head + 1u) >> 16u); c++) {
+        let next = m_skip_item(at);
+        let k = m_cand(block, mw(at) & 0xffffu);
+        let label = mw(k + 3u);
+        if (mw(k) == M_BAND && label != M_NONE && (mw(m_label(block, label)) & 0xffu) == M_SURFACE_SLOPE) {
+            var run = at + 2u;
+            for (var r = 0u; r < mw(at + 1u); r++) {
+                let n = mw(run);
+                for (var e = 0u; e + 1u < n; e++) {
+                    let a = vec2f(mi(run + 1u + 2u * e), mi(run + 2u + 2u * e));
+                    let b = vec2f(mi(run + 3u + 2u * e), mi(run + 4u + 2u * e));
+                    best = min(best, h_point_segment(a, b, q));
+                }
+                run += 1u + 2u * n;
+            }
+        }
+        at = next;
+    }
+    return best * mpu;
+}
+
+// The first word of q's bin's height segment items, as heights::bin_items.
+fn h_heights_start(block: u32, q: vec2f) -> u32 {
+    let segs = m_bin_segments(block, q);
+    return select(segs.x + segs.y, 0u, segs.x == 0u);
+}
+
+// The storey of a line's finish word: 0 but for a storey's line (M_STOREY).
+fn h_storey(finish: u32) -> u32 {
+    return select(0u, finish >> 24u, (finish & M_STOREY) != 0u);
+}
+
+// The lines present at q, as heights::present, into hp, a point as WGSL declares it (all zero). keep: the
+// material lines of the labels asked for, never skipped as absent. The lines are those of keep.x's storey.
+fn h_present(hp: ptr, block: u32, q: vec2f, mpu: f32, keep: vec2u, start: u32) {
+    (*hp).n = 0u;
+    let head = m_bin_head(block, q);
+    if (head == 0u) {
+        return;
+    }
+    let hcounts = mw(head + 2u);
+    let at = select(h_heights_start(block, q), start, start != 0u);
+    let nh = hcounts >> 16u;
+    let nd = hcounts & 0xffffu;
+    let ds = at + nh;
+    let lines = block + mw(block + 6u);
+    var storey = 0u;
+    if (keep.x != M_NONE) {
+        storey = h_storey(mw(lines + M_LINE * keep.x + 1u));
+    }
+    var k = 0u;
+    loop {
+        if (k >= nh) {
+            break;
+        }
+        let l = mw(at + k) & 0xffffu;
+        let finish = mw(lines + M_LINE * l + 1u);
+        // The ceiling lines and the storeys' lines come last: no line of storey 0 follows.
+        if (storey == 0u && (finish & (M_CEILING | M_STOREY)) != 0u) {
+            break;
+        }
+        if (h_storey(finish) != storey) {
+            k++;
+            continue;
+        }
+        let ln = h_line(block, l);
+        // A line whose core lies a feather or more from q is not present: skip it before its frames
+        // (the labels' material lines stay).
+        let feather = max(ln.reach, H.feather_min);
+        let kept = l == keep.x || l == keep.y;
+        var end = k;
+        var near = H_BIG;
+        var least = H_BIG;
+        loop {
+            if (end >= nh || (mw(at + end) & 0xffffu) != l) {
+                break;
+            }
+            end++;
+            let wa = block + mw(block + 7u) + M_SAMPLE * (ln.first + (mw(at + end - 1u) >> 16u));
+            let pa = vec2f(mi(wa), mi(wa + 1u));
+            let ab = vec2f(mi(wa + M_SAMPLE), mi(wa + M_SAMPLE + 1u)) - pa;
+            let l2 = dot(ab, ab);
+            let f = select(0.0, clamp(dot(q - pa, ab) / l2, 0.0, 1.0), l2 > 0.0);
+            let half = (mf(wa + 2u) + f * (mf(wa + M_SAMPLE + 2u) - mf(wa + 2u))) * mpu;
+            let dist = length(q - pa - f * ab) * mpu;
+            near = min(near, dist - half - ln.side);
+            least = min(least, dist);
+        }
+        if (near >= feather && !kept) {
+            k = end;
+            continue;
+        }
+        // The healthy quads: (own height, health).
+        var quads: array;
+        var deltas: array;
+        var nq = 0u;
+        // The least frame metres across of the line's quads that hold q so far, healthy or not.
+        var across = H_BIG;
+        // The fallback surface: a soft nearest of the segments' surfaces at their nearest points.
+        var fb_w = 0.0;
+        var fb_z = 0.0;
+        loop {
+            if (k >= end) {
+                break;
+            }
+            let i = mw(at + k) >> 16u;
+            k++;
+            let sa = h_sample(block, ln, i, mpu);
+            let sb = h_sample(block, ln, i + 1u, mpu);
+            let f = h_segment(block, ln, i, sa, sb, q, mpu);
+            // The quads that can weigh, in the order of the line's samples, as heights::present: when
+            // the slots are full, those that a nearer quad put past the leg's reach go.
+            if (f.ok) {
+                across = min(across, abs(f.delta));
+            }
+            if (f.ok && f.nu > 0.0 && abs(f.delta) - across < H.leg_reach) {
+                if (nq == H_QUADS) {
+                    var kept = 0u;
+                    for (var j = 0u; j < nq; j++) {
+                        if (deltas[j] - across < H.leg_reach) {
+                            quads[kept] = quads[j];
+                            deltas[kept] = deltas[j];
+                            kept++;
+                        }
+                    }
+                    nq = kept;
+                }
+                if (nq < H_QUADS) {
+                    quads[nq] = vec2f(f.z, f.nu);
+                    deltas[nq] = abs(f.delta);
+                    nq++;
+                }
+            }
+            let ab = sb.p - sa.p;
+            let l2 = dot(ab, ab);
+            let g = select(0.0, clamp(dot(q - sa.p, ab) / l2, 0.0, 1.0), l2 > 0.0);
+            let dist = length(q - sa.p - g * ab) * mpu;
+            let support = (sa.h + g * (sb.h - sa.h)) + ln.side + ln.reach;
+            let psi = h_phi((dist - least) / H.leg_reach) * h_phi(dist / support);
+            if (psi <= 0.0) {
+                continue;
+            }
+            let len_m = sqrt(l2) * mpu;
+            let side = select(-1.0, 1.0, m_cross(ab, q - sa.p) <= 0.0);
+            let z = h_hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, g) + (sa.bank + g * (sb.bank - sa.bank)) * side * dist;
+            fb_w += psi;
+            fb_z += psi * z;
+        }
+        let core_d = max(near, 0.0);
+        if ((core_d >= max(feather, ln.reach) && !kept) || (nq == 0u && fb_w <= 0.0)) {
+            continue;
+        }
+        // The line's surface: each healthy quad weighs its health times φ of its metres across past the
+        // least over leg_reach, or the nearest quad alone; the fallback takes the rest of 1.
+        var jn = 0u;
+        for (var j = 1u; j < nq; j++) {
+            if (deltas[j] < deltas[jn]) {
+                jn = j;
+            }
+        }
+        var sw = 0.0;
+        var z = 0.0;
+        for (var j = 0u; j < nq; j++) {
+            var a = quads[j].y * h_phi((deltas[j] - across) / H.leg_reach);
+            if (H.legs_wall) {
+                a = select(0.0, quads[j].y, j == jn);
+            }
+            sw += a;
+            z += a * quads[j].x;
+        }
+        let fb = max(1.0 - sw, 0.0);
+        let zf = select(0.0, fb_z / fb_w, fb_w > 0.0);
+        h_insert(hp, HRec(l, ln.rank, h_glob(block, ln), (z + fb * zf) / (sw + fb), core_d, feather, ln.ret), keep);
+    }
+    // The fans: q's metres past a fan's circle per pair of its arms. A fan relates its two arms out to their
+    // feather past its circle; two lines that each meet a third near q are related through it as far as that
+    // line's own feather reaches past both corners. With no fan every relation is 0, as rel holds.
+    if (nd == 0u) {
+        return;
+    }
+    var past: array;
+    for (var k = 0u; k < H_PAIRS; k++) {
+        past[k] = H_BIG;
+    }
+    var fans = false;
+    let extras = m_extras(block);
+    for (var e = 0u; e < nd; e++) {
+        let item = mw(ds + e);
+        let cand = m_cand(block, item & 0xffffu);
+        let dk = extras + mw(cand + 5u) + M_DISC * (item >> 16u);
+        let v = q - vec2f(mi(dk), mi(dk + 1u));
+        let radius = mf(dk + 2u) * mpu;
+        let l0 = mw(dk + 3u);
+        let l1 = mw(dk + 4u);
+        // A point's fan relates its arms' ways; a round of the paved outline does not, and two legs of
+        // one way relate by their heights only, as heights::present.
+        if (mw(cand) != M_FILL && l0 != M_NONE && l1 != M_NONE && mw(lines + M_LINE * l0) != mw(lines + M_LINE * l1)) {
+            var i0 = H_SLOTS;
+            var i1 = H_SLOTS;
+            for (var r = 0u; r < (*hp).n; r++) {
+                if ((*hp).recs[r].line == l0) {
+                    i0 = r;
+                }
+                if ((*hp).recs[r].line == l1) {
+                    i1 = r;
+                }
+            }
+            if (i0 < H_SLOTS && i1 < H_SLOTS) {
+                let p = h_pair(i0, i1);
+                past[p] = min(past[p], length(v) * mpu - radius);
+                fans = true;
+            }
+        }
+    }
+    if (!fans) {
+        return;
+    }
+    for (var i = 0u; i < (*hp).n; i++) {
+        for (var j = i + 1u; j < (*hp).n; j++) {
+            var w = h_via(past[h_pair(i, j)], max((*hp).recs[i].feather, (*hp).recs[j].feather));
+            for (var k = 0u; k < (*hp).n; k++) {
+                if (k != i && k != j) {
+                    w = max(w, h_via(max(past[h_pair(i, k)], past[h_pair(k, j)]), (*hp).recs[k].feather) * h_via((*hp).recs[k].d, (*hp).recs[k].feather));
+                }
+            }
+            (*hp).rel[h_pair(i, j)] = w;
+        }
+    }
+}
+
+// A relation at `past` metres that fades over via_fade before the feather, as heights::present.
+fn h_via(past: f32, feather: f32) -> f32 {
+    return h_phi((past - feather + H.via_fade) / H.via_fade);
+}
+
+// The pair's agreement, as heights::paved_as: a fan relates them, the face relates them as arms, or
+// the rise between them is one that the lesser one's return grade climbs over the greater one's
+// feather. A return grade of 0 (water's) climbs no rise.
+fn h_agree(hp: ptr, i: u32, j: u32, arms: u32) -> f32 {
+    let upper = min(i, j);
+    let lower = max(i, j);
+    let wall = (*hp).recs[lower].ret * (*hp).recs[upper].feather / H.blend_steep;
+    let ok = wall * 0.5;
+    let dz = abs((*hp).recs[i].z - (*hp).recs[j].z);
+    let face = f32(((arms >> i) & (arms >> j) & 1u) != 0u);
+    var rel = 0.0;
+    if (i != j) {
+        rel = (*hp).rel[h_pair(i, j)];
+    }
+    let rise = select(0.0, h_phi((dz - ok) / (wall - ok)), wall > 0.0);
+    return max(max(rise, rel), face);
+}
+
+// Whether record k is of the painter's kind: water, or a way.
+fn h_kind(hp: ptr, k: u32, water: bool) -> bool {
+    return (((*hp).recs[k].rank & H_WATER) != 0u) == water;
+}
+
+// The paved field for host o (H_SLOTS for none: a blend face), as heights::paved_as: of the records of the
+// painter's kind (`water`) only.
+fn h_paved_as(hp: ptr, o: u32, arms: u32, water: bool) -> f32 {
+    let n = (*hp).n;
+    var beta: array;
+    for (var k = 0u; k < n; k++) {
+        beta[k] = h_phi((*hp).recs[k].d / (*hp).recs[k].feather);
+    }
+    var sw = 0.0;
+    var swz = 0.0;
+    var near = H_SLOTS;
+    for (var j = 0u; j < n; j++) {
+        if (!h_kind(hp, j, water)) {
+            continue;
+        }
+        if (near == H_SLOTS || (*hp).recs[j].d < (*hp).recs[near].d) {
+            near = j;
+        }
+        var w = beta[j];
+        if (j != o && o < n) {
+            w *= h_agree(hp, o, j, arms);
+        }
+        for (var i = 0u; i < n; i++) {
+            if (!h_kind(hp, i, water)) {
+                continue;
+            }
+            if (i < j) {
+                w *= select(1.0 - beta[i], 1.0 - beta[i] * h_agree(hp, i, j, arms), j == o);
+            } else if (i > j && j != o) {
+                w *= 1.0 - beta[i] * (1.0 - h_agree(hp, i, j, arms));
+            }
+        }
+        sw += w;
+        swz += w * (*hp).recs[j].z;
+    }
+    if (sw > 0.0) {
+        return swz / sw;
+    }
+    if (o < n) {
+        return (*hp).recs[o].z;
+    }
+    return select(0.0, (*hp).recs[min(near, H_SLOTS - 1u)].z, near < H_SLOTS);
+}
+
+fn h_cone(s: f32, d: f32) -> f32 {
+    if (d < H.round) {
+        return s * d * d / (2.0 * H.round);
+    }
+    return s * (d - H.round * 0.5);
+}
+
+// The no-room rule of a cone of slope s from a point of the outline that stands `need` above (a fill) or
+// below (a cut) the plain terrain where the cone should meet it (`known`: whether it is known), with a wall up
+// to `wall` before the face steepens on as steep as the need asks, and `crest` metres less run, as
+// heights::fit: (the slope, the wall).
+fn h_fit(s: f32, most: f32, need: f32, known: bool, wall: f32, reach: f32, crest: f32) -> vec2f {
+    let run = max(max(reach * (1.0 - H.fade_share) - H.round * 0.5, 1e-3) - crest, 1e-3);
+    let s0 = min(s, H.face_max);
+    if (!known) {
+        return vec2f(s0, 0.0);
+    }
+    var sc = select(min(need / run, max(min(most, H.face_max), s0)), s0, need <= s0 * run);
+    if (need - sc * run > wall) {
+        sc = (need - wall) / run;
+    }
+    return vec2f(sc, clamp(need - sc * run, 0.0, wall));
+}
+
+// A value of an outline edge's ends at share f of it (`known`: which ends know it), linear between them; an
+// unknown end takes the other end's, as heights::at_share.
+fn h_at_share(v: vec2f, known: vec2, f: f32) -> f32 {
+    return mix(select(v.y, v.x, known.x), select(v.x, v.y, known.y), f);
+}
+
+// Where q lies past an end of an outline edge within the cone of that end, as heights::fan: (1 or 0 for the
+// end b or a, the metres to it), or x < 0. `turn`: the outline's turn at a and b (`known`: whether an edge
+// goes on there).
+fn h_fan(along: f32, out: f32, len: f32, turn: vec2f, known: vec2) -> vec2f {
+    var x = along;
+    var end = 0u;
+    if (along > len) {
+        x = along - len;
+        end = 1u;
+    } else if (along >= 0.0) {
+        return vec2f(-1.0);
+    }
+    let t = turn[end];
+    if (!known[end]) {
+        return vec2f(f32(end), length(vec2f(x, out)));
+    }
+    if (t <= 0.0) {
+        return vec2f(-1.0);
+    }
+    let before = select(x * cos(t) + out * sin(t) >= 0.0, x * cos(t) - out * sin(t) <= 0.0, end == 1u);
+    if (before) {
+        return vec2f(f32(end), length(vec2f(x, out)));
+    }
+    return vec2f(-1.0);
+}
+
+// The cone of an outline edge at q (sign 1 a fill, −1 a cut) whose top runs linearly, as heights::edge_cone:
+// the line across its strip, falling on by `steep` more than it climbs past the ends' normals, and within an
+// end's fan the end's own cone; with a crest b, falling from b metres out.
+fn h_edge_cone(along: f32, out: f32, len: f32, top: vec2f, s: f32, sign: f32, fan: vec2f, steep: f32, crest: f32) -> f32 {
+    let g = select(0.0, (top.y - top.x) / len, len > 0.0);
+    let past = max(max(-along, along - len), 0.0);
+    let line = top.x + g * along - sign * (s * max(abs(out) - crest, 0.0) + (steep + abs(g)) * past);
+    if (fan.x < 0.0) {
+        return line;
+    }
+    let cone = select(top.x, top.y, fan.x > 0.5) - sign * s * max(fan.y - crest, 0.0);
+    return select(min(line, cone), max(line, cone), sign > 0.0);
+}
+
+// How much the round of a cone of slope s at its foot holds it back at d metres, as heights::round_back.
+fn h_round_back(s: f32, d: f32) -> f32 {
+    return s * d - h_cone(s, d);
+}
+
+// The toe and crest round's width in height, as heights::span_k.
+fn h_span_k(sf: f32, sc: f32, grade: f32) -> f32 {
+    if (grade <= H_UNKNOWN * 0.5) {
+        return H_BIG;
+    }
+    return 0.5 * H.toe_span * max(min(abs(grade + sf), abs(sc - grade)), H.toe_gap_min);
+}
+
+// How far a cone has let go at d metres from its edge, and by how much it has moved, as heights::release.
+fn h_release(d: f32, reach: f32) -> vec2f {
+    let w = reach * H.fade_share;
+    let fade = h_smooth((d - (reach - w)) / w);
+    return vec2f(fade, H.fade_gap * fade / max(1.0 - fade, 1e-6));
+}
+
+// The soft greatest of the first n fills whose bit is set in `counted`, as heights::soft_top: the mean of
+// the two greatest, the second weighted by (1 − gap / width)², the width growing from 0 at the greatest
+// one's outline.
+fn h_soft_top(fills: ptr>, dists: ptr>, n: u32, counted: u32) -> f32 {
+    var top = H_SLOTS;
+    for (var j = 0u; j < n; j++) {
+        if (((counted >> j) & 1u) != 0u && (top == H_SLOTS || (*fills)[j] > (*fills)[top])) {
+            top = j;
+        }
+    }
+    if (top == H_SLOTS) {
+        return -H_BIG;
+    }
+    var second = -H_BIG;
+    for (var j = 0u; j < n; j++) {
+        if (((counted >> j) & 1u) != 0u && j != top) {
+            second = max(second, (*fills)[j]);
+        }
+    }
+    let v = (*fills)[top];
+    let width = h_toe_width((*dists)[top], H.budget_round);
+    if (width <= 0.0 || second <= -H_BIG * 0.5 || v <= -H_BIG * 0.5) {
+        return v;
+    }
+    let x = max(1.0 - (v - second) / width, 0.0);
+    return (v + x * x * second) / (1.0 + x * x);
+}
+
+// One host line's outline near q, as heights::Group: its released fill and cut, the cut it may rise to
+// toward its budget, the metres to its nearest edge, its least toe width and how far it has let go.
+struct HGroup {
+    line: u32,
+    rank: u32,
+    glob: u32,
+    fill: f32,
+    // Its fill without a rise and a crest, which bounds its own cut.
+    plain: f32,
+    cut: f32,
+    steep: f32,
+    d: f32,
+    toe: f32,
+    fade: f32,
+}
+
+struct HGroups {
+    g: array,
+    n: u32,
+}
+
+// Whether group a goes before group b in the painter's order: class rank, then the global key, then the
+// line.
+fn h_group_before(a: HGroup, b: HGroup) -> bool {
+    let ra = a.rank % H_FLAGS;
+    let rb = b.rank % H_FLAGS;
+    return ra < rb || (ra == rb && (a.glob < b.glob || (a.glob == b.glob && a.line < b.line)));
+}
+
+// A line's group ends, as heights::groups: its round at the foot taken once at its distance, then in
+// the painter's order among the first H_SLOTS.
+fn h_close(gs: ptr, g0: HGroup, ln: HLine) {
+    if (g0.d >= H_BIG * 0.5) {
+        return;
+    }
+    var g = g0;
+    g.fade = h_release(g.d, ln.reach).x;
+    g.plain += h_round_back(ln.fill, g.d);
+    g.fill += h_round_back(ln.fill, max(g.d - ln.crest, 0.0));
+    g.cut -= h_round_back(ln.cut, g.d);
+    g.steep -= h_round_back(min(max(ln.cut_max, ln.cut), H.face_max), g.d);
+    if ((*gs).n == H_SLOTS) {
+        if (!h_group_before(g, (*gs).g[H_SLOTS - 1u])) {
+            return;
+        }
+        (*gs).n--;
+    }
+    var j = (*gs).n;
+    loop {
+        if (j == 0u || !h_group_before(g, (*gs).g[j - 1u])) {
+            break;
+        }
+        (*gs).g[j] = (*gs).g[j - 1u];
+        j--;
+    }
+    (*gs).g[j] = g;
+    (*gs).n++;
+}
+
+// The host lines of the outline edges that q's bin lists, as heights::groups. A bin lists its edges by
+// host line, in half words after their count; a block with no outline edges lists none.
+fn h_groups(block: u32, q: vec2f, mpu: f32) -> HGroups {
+    var gs: HGroups;
+    gs.n = 0u;
+    let head = m_bin_head(block, q);
+    if (head == 0u || mw(block + 14u) >= mw(block + 9u)) {
+        return gs;
+    }
+    let hc = mw(head + 2u);
+    let at = h_heights_start(block, q) + (hc >> 16u) + (hc & 0xffffu) + (mw(head + 3u) & 0xffffu);
+    let n = mw(at) & 0xffffu;
+    let edges = block + mw(block + 14u);
+    var g = HGroup(M_NONE, 0u, 0u, -H_BIG, -H_BIG, H_BIG, H_BIG, H_BIG, H_BIG, 1.0);
+    var ln: HLine;
+    for (var k = 1u; k <= n; k++) {
+        let e = edges + H_EDGE * ((mw(at + k / 2u) >> (16u * (k % 2u))) & 0xffffu);
+        let line = mw(e + 3u) & 0xffffu;
+        if (line != g.line) {
+            if (g.line != M_NONE) {
+                h_close(&gs, g, ln);
+            }
+            ln = h_line(block, line);
+            g = HGroup(line, ln.rank, h_glob(block, ln), -H_BIG, -H_BIG, H_BIG, H_BIG, H_BIG, H_BIG, 1.0);
+        }
+        // Metres along and off the edge from q − a; b is two i16 offsets from a.
+        let a = vec2f(mi(e), mi(e + 1u));
+        let ob = mw(e + 2u);
+        let ab = vec2f(f32(bitcast(ob << 16u) >> 16u), f32(bitcast(ob) >> 16u));
+        let v = q - a;
+        let lu = length(ab);
+        let u = select(vec2f(1.0, 0.0), ab / lu, lu > 0.0);
+        let along = dot(v, u) * mpu;
+        let side = -m_cross(u, v);
+        let off = abs(side) * mpu;
+        let len = lu * mpu;
+        let foot = clamp(along, 0.0, len) - along;
+        let d = sqrt(foot * foot + off * off);
+        if (d >= ln.reach) {
+            continue;
+        }
+        let h = vec2f(mf(e + 4u), mf(e + 5u)) - H_BASE;
+        let t = vec2f(h_known_word(e + 6u), h_known_word(e + 7u));
+        let known = t > vec2f(H_UNKNOWN * 0.5);
+        let last = mw(e + 8u);
+        let gq = vec2i(bitcast(mw(e + 3u)) >> 16u, bitcast(last << 16u) >> 16u);
+        let graded = gq != vec2i(-32768);
+        let tq = vec2i(bitcast(mw(e + 9u) << 16u) >> 16u, bitcast(last) >> 16u);
+        let fan = h_fan(along, side * mpu, len, vec2f(tq) / H_TURN_STEPS * 3.14159265, tq != vec2i(-32768));
+        let fr = h_release(d, ln.reach);
+        let wall = select(0.0, H.wall_max, (ln.rank & H_WALL) != 0u);
+        // The slope and the wall at q's foot on the edge, from the need there. The fill starts ln.rise over
+        // the edge and ln.crest past it.
+        let share = select(0.0, clamp(along / len, 0.0, 1.0), len > 0.0);
+        let need = h_at_share(h - t, known, share);
+        let grade = select(H_UNKNOWN, h_at_share(vec2f(gq) / H_GRADE_STEPS, graded, share), any(graded));
+        let f = h_fit(ln.fill, ln.fill_max, need + ln.rise, any(known), wall, ln.reach, ln.crest);
+        let c = h_fit(ln.cut, ln.cut_max, -need, any(known), wall, ln.reach, 0.0);
+        g.d = min(g.d, d);
+        let past = select(max(max(-along, along - len), 0.0), 0.0, fan.x >= 0.0);
+        let w = h_toe_width(d, h_span_k(f.x, c.x, grade)) + H.face_max * past;
+        g.toe = min(g.toe, w + fr.x * (H.toe_max - w));
+        // Past its line into its paved face (from H_SIDE_UNITS on) an edge's cone falls on at face_max,
+        // as heights::groups.
+        let inside = select(0.0, max(-side - H_SIDE_UNITS, 0.0) * mpu * H.face_max, lu > 0.0);
+        let out = side * mpu;
+        let fill = h_edge_cone(along, out, len, h + ln.rise - f.y, f.x, 1.0, fan, H.face_max, ln.crest);
+        var plain = fill;
+        if (ln.rise > 0.0 || ln.crest > 0.0) {
+            let pf = h_fit(ln.fill, ln.fill_max, need, any(known), wall, ln.reach, 0.0);
+            plain = h_edge_cone(along, out, len, h - pf.y, pf.x, 1.0, fan, H.face_max, 0.0);
+        }
+        g.fill = max(g.fill, fill - fr.y - inside);
+        g.plain = max(g.plain, plain - fr.y - inside);
+        g.cut = min(g.cut, h_edge_cone(along, out, len, h + c.y, c.x, -1.0, fan, H.face_max, 0.0) + fr.y + inside);
+        // The highest cut toward the budget: a wall class's wall up to wall_max at its edge, then a face
+        // at the steepest cut from the wall's top.
+        let steep = min(max(ln.cut_max, ln.cut), H.face_max);
+        let s = h_fit(steep, steep, -need - wall, any(known), 0.0, ln.reach, 0.0);
+        g.steep = min(g.steep, h_edge_cone(along, out, len, h + wall, s.x, -1.0, fan, H.face_max, 0.0) + fr.y + inside);
+    }
+    if (g.line != M_NONE) {
+        h_close(&gs, g, ln);
+    }
+    return gs;
+}
+
+// The slope field at q, as heights::slope: per host line of the outline near q its fill and cut, then a
+// smooth min(cut, max(T, fill)). A line's cut rises toward its bank budget (the soft greatest fill of
+// the other lines that are no rail and no water) up to its highest cut, in a round that grows from 0 at
+// its own outline and at the outline of every line in the budget; where its own plain fill passes its
+// cut, that fill bounds the cut.
+fn h_slope(block: u32, q: vec2f, mpu: f32, t: f32) -> f32 {
+    let gs = h_groups(block, q, mpu);
+    let n = gs.n;
+    if (n == 0u) {
+        return t;
+    }
+    var fills: array;
+    var dists: array;
+    var toe = H.toe_max;
+    var roads = 0u;
+    for (var k = 0u; k < n; k++) {
+        let g = gs.g[k];
+        let kq = h_soft_min(g.toe, g.cut - g.fill);
+        toe = min(toe, kq + g.fade * (H.toe_max - kq));
+        fills[k] = g.fill;
+        dists[k] = g.d;
+        roads |= select(1u << k, 0u, (g.rank & (H_RAIL | H_WATER)) != 0u);
+    }
+    let lo = h_soft_top(&fills, &dists, n, 0xffffffffu);
+    var hi = H_BIG;
+    for (var k = 0u; k < n; k++) {
+        let g = gs.g[k];
+        let counted = roads & ~(1u << k);
+        // Another line's rail bed counts with its fill less its wall cap, as heights::slope.
+        var budget = h_soft_top(&fills, &dists, n, counted);
+        for (var j = 0u; j < n; j++) {
+            if (j != k && (gs.g[j].rank & H_RAIL) != 0u) {
+                budget = max(budget, fills[j] - select(0.0, H.wall_max, (gs.g[j].rank & H_WALL) != 0u));
+            }
+        }
+        var near = g.d;
+        for (var j = 0u; j < n; j++) {
+            if (((counted >> j) & 1u) != 0u) {
+                near = min(near, dists[j]);
+            }
+        }
+        let w = h_toe_width(near, H.budget_round);
+        let lift = h_smin(budget, g.steep, w);
+        hi = min(hi, max(h_smax(g.cut, lift, w), min(g.plain, g.steep)));
+    }
+    let edge = h_slope_edge(block, q, mpu);
+    let k = toe * h_smooth(edge / M_MARGIN);
+    return t + h_smooth(edge / H.band_fade) * (h_smin(hi, h_smax(t, lo, k), k) - t);
+}
+
+// The records that region `id` relates as its junction's arms, a bit each, as heights::arms_of.
+fn h_arms_of(block: u32, hp: ptr, id: u32) -> u32 {
+    let lw = m_label(block, id);
+    let jr = m_junction(block, id);
+    var arms = 0u;
+    for (var k = 0u; k < (*hp).n; k++) {
+        let line = (*hp).recs[k].line;
+        var named = line == mw(lw + 2u);
+        if (jr == M_NONE) {
+            for (var w = 4u; w < 12u; w++) {
+                named = named || mw(lw + w) == line;
+            }
+        } else {
+            for (var a = 0u; a < (mw(jr + 2u) & 0xffu); a++) {
+                named = named || (mw(m_arm(jr, a)) & 0xffffu) == line;
+            }
+        }
+        arms |= select(0u, 1u << k, named);
+    }
+    return arms;
+}
+
+// A junction's region at q: its own painter, faded near each of its edges to the face beyond, as
+// heights::region. The groups: a host beyond at its record's index, then the regions beyond (the
+// nearest H_REGIONS). Toward a slope or the terrain the region keeps its own painter. `water`: the region's
+// kind, its material line's.
+fn h_region(block: u32, q: vec2f, mpu: f32, hp: ptr, label: u32, arms: u32, water: bool) -> f32 {
+    let n = (*hp).n;
+    let own = h_paved_as(hp, H_SLOTS, arms, water);
+    var dist: array;
+    for (var k = 0u; k < H_SLOTS; k++) {
+        dist[k] = H_BIG;
+    }
+    var beyond: array;
+    var beyond_id: array;
+    for (var k = 0u; k < H_REGIONS; k++) {
+        beyond[k] = vec2f(H_BIG, 0.0);
+        beyond_id[k] = M_NONE;
+    }
+    let head = m_bin_head(block, q);
+    if (head != 0u) {
+        var at = h_heights_start(block, q);
+        let hc = mw(head + 2u);
+        at += (hc >> 16u) + (hc & 0xffffu);
+        for (var e = 0u; e < (mw(head + 3u) & 0xffffu); e++) {
+            let ew = block + mw(block + 11u) + M_BLEND * mw(at + e);
+            if (mw(ew + 4u) != label) {
+                continue;
+            }
+            let d = h_point_segment(vec2f(mi(ew), mi(ew + 1u)), vec2f(mi(ew + 2u), mi(ew + 3u)), q) * mpu;
+            if (d >= H.region_fade) {
+                continue;
+            }
+            let other = mw(ew + 5u);
+            let rule = select(0u, mw(m_label(block, other)) >> 24u, other != M_NONE);
+            if (rule == 3u) {
+                var k = H_REGIONS - 1u;
+                for (var j = 0u; j < H_REGIONS; j++) {
+                    if (beyond_id[j] == other) {
+                        k = j;
+                    }
+                }
+                if (d < beyond[k].x) {
+                    beyond[k].x = d;
+                    beyond_id[k] = other;
+                    for (var j = H_REGIONS - 1u; j > 0u; j--) {
+                        if (beyond[j].x < beyond[j - 1u].x) {
+                            let t = beyond[j];
+                            beyond[j] = beyond[j - 1u];
+                            beyond[j - 1u] = t;
+                            let i = beyond_id[j];
+                            beyond_id[j] = beyond_id[j - 1u];
+                            beyond_id[j - 1u] = i;
+                        }
+                    }
+                }
+                continue;
+            }
+            // A paved face beyond: its host line, if it has one.
+            if (rule != 2u && rule != 4u) {
+                continue;
+            }
+            let host = mw(m_label(block, other) + 2u);
+            for (var k = 0u; k < n; k++) {
+                if ((*hp).recs[k].line == host) {
+                    dist[k] = min(dist[k], d);
+                }
+            }
+        }
+    }
+    var sw = 1.0;
+    var sv = 0.0;
+    // The hosts beyond: σ is the host's presence times the region's agreement with it.
+    for (var g = 0u; g < n; g++) {
+        if (dist[g] >= H.region_fade) {
+            continue;
+        }
+        var agreed = 0.0;
+        for (var k = 0u; k < n; k++) {
+            if (((arms >> k) & 1u) != 0u) {
+                agreed = max(agreed, h_phi((*hp).recs[k].d / (*hp).recs[k].feather) * h_agree(hp, k, g, arms));
+            }
+        }
+        let sigma = h_phi((*hp).recs[g].d / (*hp).recs[g].feather) * agreed;
+        if (sigma <= 0.0) {
+            continue;
+        }
+        let v = h_paved_as(hp, g, 0u, ((*hp).recs[g].rank & H_WATER) != 0u);
+        let s = h_smooth(dist[g] / H.region_fade);
+        if (s <= 0.0) {
+            return v;
+        }
+        let w = sigma * (1.0 - s) / s;
+        sw += w;
+        sv += w * (v - own);
+    }
+    // The regions beyond, nearest first (equal distances by their target): both regions' arms related.
+    var vr: array;
+    for (var k = 0u; k < H_REGIONS; k++) {
+        if (beyond_id[k] != M_NONE) {
+            vr[k] = h_paved_as(hp, H_SLOTS, arms | h_arms_of(block, hp, beyond_id[k]), water);
+        }
+    }
+    for (var j = 1u; j < H_REGIONS; j++) {
+        if (beyond_id[j] != M_NONE && beyond[j].x == beyond[j - 1u].x && vr[j] < vr[j - 1u]) {
+            let t = vr[j];
+            vr[j] = vr[j - 1u];
+            vr[j - 1u] = t;
+        }
+    }
+    for (var k = 0u; k < H_REGIONS; k++) {
+        if (beyond_id[k] == M_NONE) {
+            continue;
+        }
+        let s = h_smooth(beyond[k].x / H.region_fade);
+        if (s <= 0.0) {
+            return vr[k];
+        }
+        let w = (1.0 - s) / s;
+        sw += w;
+        sv += w * (vr[k] - own);
+    }
+    return own + sv / sw;
+}
+
+// The height at q (frame units from the cell's origin) of the block, with the label there (M_NONE for
+// terrain), the plain terrain t, and the first word of the bin's height lists (`ModelPoint.heights`,
+// or 0 to find it): (height, kind).
+fn height_at(block: u32, q: vec2f, label: u32, t: f32, start: u32) -> vec2f {
+    H_BASE = round(t);
+    let h = height_relative(block, q, label, t - H_BASE, start);
+    return vec2f(h.x + H_BASE, h.y);
+}
+
+// height_at with every height less H_BASE.
+fn height_relative(block: u32, q: vec2f, label: u32, t: f32, start: u32) -> vec2f {
+    let rule = select(mw(m_label(block, label)) >> 24u, 0u, label == M_NONE);
+    // The terrain under a deck's ceiling: a point with no ceiling line in its bin reads no rules.
+    if (rule == 0u) {
+        let at = h_ceilings(block, q, start);
+        if (at.y == 0u) {
+            return vec2f(t, H_TERRAIN);
+        }
+        H = h_rules(block);
+        return vec2f(min(t, h_ceiling(block, q, h_scale(block, q), at)), H_TERRAIN);
+    }
+    H = h_rules(block);
+    let mpu = h_scale(block, q);
+    // A slope reads only the outline edges, and the ceilings.
+    if (rule == 1u) {
+        return vec2f(min(h_slope(block, q, mpu, t), h_ceiling(block, q, mpu, h_ceilings(block, q, start))), H_SLOPE);
+    }
+    return h_paved_at(block, q, mpu, label, rule, mw(m_label(block, label) + 2u), t, start);
+}
+
+// The word after q's bin's height segment items and the count of the ceiling lines' items among them, last
+// (records::CEILING): 0 where none.
+fn h_ceilings(block: u32, q: vec2f, start: u32) -> vec2u {
+    let head = m_bin_head(block, q);
+    if (head == 0u) {
+        return vec2u(0u);
+    }
+    let end = select(h_heights_start(block, q), start, start != 0u) + (mw(head + 2u) >> 16u);
+    let lines = block + mw(block + 6u);
+    var n = 0u;
+    loop {
+        if (n == (mw(head + 2u) >> 16u) || (mw(lines + M_LINE * (mw(end - n - 1u) & 0xffffu) + 1u) & M_CEILING) == 0u) {
+            break;
+        }
+        n++;
+    }
+    return vec2u(end, n);
+}
+
+// The ceiling at q from the last `at.y` height segment items before word `at.x`, as heights::ceiling: per
+// segment of a deck's ceiling line, the metres outside its stroke (flat at the line's ends along their `flat`
+// normals, words 4 and 5) and its banked surface at q's foot less its drop (word 10); past the stroke the bound
+// rises at face_max and lets go over ceiling_release.
+fn h_ceiling(block: u32, q: vec2f, mpu: f32, at: vec2u) -> f32 {
+    var best = H_BIG;
+    let lines = block + mw(block + 6u);
+    let samples = block + mw(block + 7u);
+    for (var k = 1u; k <= at.y; k++) {
+        let item = mw(at.x - k);
+        let lw = lines + M_LINE * (item & 0xffffu);
+        let ln = h_line(block, item & 0xffffu);
+        let i = item >> 16u;
+        let sa = h_sample(block, ln, i, mpu);
+        let sb = h_sample(block, ln, i + 1u, mpu);
+        let ab = sb.p - sa.p;
+        let len = length(ab);
+        if (len <= 0.0) {
+            continue;
+        }
+        let u = ab / len;
+        let v = q - sa.p;
+        let t = dot(v, u);
+        let lateral = -m_cross(u, v) * mpu;
+        var f = clamp(t / len, 0.0, 1.0);
+        var across = length(v - f * ab) * mpu;
+        if ((i == 0u && t < 0.0) || (i + 2u == ln.count && t > len)) {
+            f = select(1.0, 0.0, t < 0.0);
+            across = abs(lateral);
+        }
+        let half = sa.h + f * (sb.h - sa.h);
+        let last = ln.count - 1u;
+        let along = samples + M_SAMPLE * ln.first + 3u;
+        var past = 0.0;
+        if (mf(along + M_SAMPLE * i) - mf(along) <= sa.h + H.ceiling_release) {
+            let a = samples + M_SAMPLE * ln.first;
+            past = max(past, -dot(q - vec2f(mi(a), mi(a + 1u)), h_unit(unpack2x16snorm(mw(lw + 4u)))) * mpu);
+        }
+        if (mf(along + M_SAMPLE * last) - mf(along + M_SAMPLE * (i + 1u)) <= sb.h + H.ceiling_release) {
+            let a = samples + M_SAMPLE * (ln.first + last);
+            past = max(past, -dot(q - vec2f(mi(a), mi(a + 1u)), h_unit(unpack2x16snorm(mw(lw + 5u)))) * mpu);
+        }
+        let out = length(vec2f(max(across - half, 0.0), past));
+        if (out >= H.ceiling_release) {
+            continue;
+        }
+        let len_m = len * mpu;
+        let z = h_hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, f) + (sa.bank + f * (sb.bank - sa.bank)) * clamp(lateral, -half, half);
+        best = min(best, z - ln.ret + H.face_max * out + h_release(out, H.ceiling_release).y);
+    }
+    return best;
+}
+
+// height_relative of a paved label. Tint zeroes a function's vars at its entry: hp lives here, so only a paved
+// texel pays for zeroing it.
+fn h_paved_at(block: u32, q: vec2f, mpu: f32, label: u32, rule: u32, material: u32, t: f32, start: u32) -> vec2f {
+    var hp: HPoint;
+    h_present(&hp, block, q, mpu, vec2u(material, M_NONE), start);
+    // A blend face (a junction's region) has no host, and it relates the junction's arms (its
+    // material, host and guest lines), as heights::by_label; with no record of its kind, the plain terrain.
+    let water = h_line_water(block, material);
+    var kind = false;
+    for (var k = 0u; k < hp.n; k++) {
+        kind = kind || h_kind(&hp, k, water);
+    }
+    if (rule == 3u && kind) {
+        return vec2f(h_region(block, q, mpu, &hp, label, h_arms_of(block, &hp, label), water), H_PAVED);
+    }
+    // The host: the label's material line; with none (a way's band face), the first way record whose core
+    // holds q, else the nearest way record, as heights::host.
+    var o = H_SLOTS;
+    for (var k = 0u; k < hp.n; k++) {
+        if (hp.recs[k].line == material) {
+            o = k;
+        }
+    }
+    for (var k = 0u; k < hp.n && o == H_SLOTS && material == M_NONE; k++) {
+        if (hp.recs[k].d <= 0.0 && h_kind(&hp, k, false)) {
+            o = k;
+        }
+    }
+    if (o == H_SLOTS && material == M_NONE) {
+        var best = H_BIG;
+        for (var k = 0u; k < hp.n; k++) {
+            if (hp.recs[k].d < best && h_kind(&hp, k, false)) {
+                best = hp.recs[k].d;
+                o = k;
+            }
+        }
+    }
+    if (o == H_SLOTS) {
+        return vec2f(t, H_PAVED);
+    }
+    return vec2f(h_paved_as(&hp, o, 0u, (hp.recs[o].rank & H_WATER) != 0u), H_PAVED);
+}
diff --git a/builder/web/src/lib/trailview/terrain/lod.ts b/builder/web/src/lib/trailview/terrain/lod.ts
index 107e95349b..e0ba059e62 100644
--- a/builder/web/src/lib/trailview/terrain/lod.ts
+++ b/builder/web/src/lib/trailview/terrain/lod.ts
@@ -7,7 +7,9 @@ export const FINEST = 18;
 /** The coarsest level with pages: the quadrants of tile 0/0/0. */
 export const COARSEST = 1;
 /** The morph band of a CDLOD level, in levels of log2 distance, as MORPH in drawn-height.wgsl. */
-const MORPH = 0.3;
+export const MORPH = 0.3;
+/** Calm frames in a row before the quality rises again (terrain.ts), and before the meshes draw again after a frame below level 17 (pieces.ts). */
+export const CALM = 120;
 /** Nodes along an edge of the LOD map window of each level. */
 export const MAP = 32;
 /** A node splits this far, in levels, before its finest point reaches the next level, so float32 shaders see exact plateaus. */
@@ -39,6 +41,8 @@ export const size = (level: number) => 2 ** (30 - level);
 export const OWNER = 15, CHILD = 16;
 /** The level of the squares of a corridor's details, which draw only near the eye. */
 export const DETAIL = 18;
+/** The level of the ground plan's cells: each has its records and its mesh (plan/pieces.ts). */
+export const CELL_LEVEL = 16;
 export const key = ({ level, x, y }: Node) => `${level}/${x}/${y}`;
 
 /**
diff --git a/builder/web/src/lib/trailview/terrain/model-words.wgsl b/builder/web/src/lib/trailview/terrain/model-words.wgsl
new file mode 100644
index 0000000000..8df2949ac5
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/model-words.wgsl
@@ -0,0 +1,3 @@
+// The words of the records of the cells (the crate's `faces::records` blocks), MODEL_ROW words per row.
+// A pass that reads them binds this texture, or swaps this file for its own binding.
+@group(0) @binding(8) var model_words: texture_2d;
diff --git a/builder/web/src/lib/trailview/terrain/model.test.ts b/builder/web/src/lib/trailview/terrain/model.test.ts
new file mode 100644
index 0000000000..f93d2ebb22
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/model.test.ts
@@ -0,0 +1,437 @@
+import { readFileSync } from 'node:fs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { CELL_LEVEL, MODEL_ROW, Records } from './model';
+import { DeviceCache } from './device-cache';
+import { FakeCaches } from '../../../../test-support/fake-caches';
+import { HEAP_LIMIT } from '../plan/plan';
+import type { PlanRequest } from '../plan/plan-worker';
+
+/** A plan worker that answers `start` and keeps the cell builds for the test to answer. */
+class FakeWorker {
+    static all: FakeWorker[] = [];
+    onmessage?: (event: { data: unknown }) => void;
+    onerror?: unknown;
+    builds: Extract[] = [];
+    meshes: Extract[] = [];
+    dead = false;
+
+    constructor() {
+        FakeWorker.all.push(this);
+    }
+
+    postMessage(message: PlanRequest): void {
+        if (message.type === 'start') queueMicrotask(() => this.onmessage?.({ data: { type: 'ready' } }));
+        else if (message.type === 'cell') this.builds.push(message);
+        else if (message.type === 'mesh') this.meshes.push(message);
+    }
+
+    /** Answers a build with a block of `rows` rows, a rim, the worker's heap and a far block or the crate's refusal of it. */
+    answer(build: { id: number }, rows: number, rim = new Uint32Array(0), heap = 2 ** 20, far: Uint32Array | { error: string } = new Uint32Array(0)): void {
+        this.onmessage?.({ data: { id: build.id, ok: true, words: new Uint32Array(rows * MODEL_ROW), rim, far, ms: 1, heap } });
+    }
+
+    terminate(): void {
+        this.dead = true;
+    }
+}
+
+const settle = () => new Promise(resolve => setTimeout(resolve, 0));
+// Two cells of the fixture's zoom-13 tile 4286/2888.
+const A = { level: CELL_LEVEL, x: 4286 * 8, y: 2888 * 8 }, B = { level: CELL_LEVEL, x: 4286 * 8 + 1, y: 2888 * 8 };
+
+describe('the records store', () => {
+    afterEach(() => vi.unstubAllGlobals());
+
+    /** A records store with its two workers ready; `features` gives a feature tile's body. */
+    async function store(features: () => Promise = async () => new ArrayBuffer(4)) {
+        FakeWorker.all = [];
+        vi.stubGlobal('Worker', FakeWorker);
+        vi.stubGlobal('fetch', async () => new Response(readFileSync(new URL('../plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url))));
+        const records = new Records(features, async () => undefined, () => {}, new AbortController().signal);
+        for (let i = 0; i < 20 && FakeWorker.all.length < 2; i++) await settle();
+        await settle();
+        /** The builds that the workers hold, taken from them. */
+        const posted = () => FakeWorker.all.flatMap(worker => worker.builds.splice(0).map(build => ({ worker, build })));
+        return { records, posted };
+    }
+    const at = (dx: number, dy = 0) => ({ level: CELL_LEVEL, x: B.x + dx, y: B.y + dy });
+
+    it('gives the rows to the nearest cells, asks again for a block without rows once it is nearer, counts a refused far block, and nothing waits once the records failed', async () => {
+        const { records, posted } = await store();
+        const frame = async (cells: { node: typeof A; distance: number }[]) => {
+            records.update(cells);
+            await settle();
+            return posted();
+        };
+        // Both have the reserve; their blocks of 1200 rows, over the reserve, do not both fit the 2047 rows.
+        const [a, b] = await frame([{ node: A, distance: 100 }, { node: B, distance: 200 }]);
+        expect(records.waits(B)).toBe(true);
+        a.worker.answer(a.build, 1200);
+        b.worker.answer(b.build, 1200, undefined, undefined, { error: 'a run of too many samples' });
+        expect([records.stats.cells, records.stats.failed, records.stats.refused, records.stats.large]).toEqual([1, 1, 1, 2]);
+        // B's known size keeps it out of the target: its pages draw without records, and it is not built again.
+        expect(await frame([{ node: A, distance: 100 }, { node: B, distance: 200 }])).toEqual([]);
+        expect(records.waits(B)).toBe(false);
+        // The eye moves on: B comes first, and builds again; A leaves for it.
+        const [again] = await frame([{ node: B, distance: 50 }, { node: A, distance: 150 }]);
+        expect(again.build.cell).toMatchObject({ x: B.x, y: B.y });
+        expect(records.waits(B)).toBe(true);
+        records.takeChanged();
+        again.worker.answer(again.build, 1200);
+        expect(records.takeChanged()).toEqual([A, B]);
+        expect([records.stats.cells, records.stats.failed, records.loading]).toEqual([1, 0, false]);
+        // Without feature tiles, no page waits and the store does not count as loading.
+        const none = new Records(undefined, async () => undefined, () => {}, new AbortController().signal);
+        none.update([{ node: A, distance: 100 }]);
+        expect([none.waits(A), none.loading, none.stats.error]).toEqual([false, false, 'the release has no feature tiles']);
+    });
+
+    it('starts a build only with the reserve free after the nearer blocks, and holds a block that arrives before them', async () => {
+        const { records, posted } = await store();
+        // Seven cells in a row, 100 m apart: the reserve of 384 rows fits five times into the 2047 rows.
+        const cells = [1, 2, 3, 4, 5, 6, 7].map(i => ({ node: at(4 * i), distance: 100 * i }));
+        const open = new Map[number]>();
+        /** A frame; returns the cells whose builds went to a worker in it, as their place in the row. */
+        const frame = async () => {
+            records.update(cells);
+            await settle();
+            const sent = posted().map(job => [(job.build.cell.x - B.x) / 4, job] as const);
+            sent.forEach(([i, job]) => open.set(i, job));
+            return sent.map(([i]) => i).sort();
+        };
+        const answer = (i: number, rows: number) => open.get(i)!.worker.answer(open.get(i)!.build, rows);
+        expect(await frame()).toEqual([1, 2]);
+        // With 700 rows of the first, the reserves of the next three leave none for the fifth: it is not asked for.
+        answer(1, 700);
+        expect(await frame()).toEqual([3]);
+        answer(3, 300);
+        expect(await frame()).toEqual([4]);
+        // The fourth block arrives before the second. It fits only if the second is small: it waits, without rows, and its pages wait.
+        answer(4, 900);
+        expect([records.stats.cells, records.waits(at(16)), records.waits(at(20)), records.loading]).toEqual([2, true, false, true]);
+        answer(2, 100);
+        // 2000 rows are known: the fourth has its rows without a second build, and 47 rows are no reserve for the fifth.
+        expect(await frame()).toEqual([]);
+        expect([records.stats.cells, records.stats.builds, records.stats.refused, records.loading]).toEqual([4, 4, 0, false]);
+        expect(cells.map(({ node }) => records.block(node) !== undefined)).toEqual([true, true, true, true, false, false, false]);
+    });
+
+    it('fills the rows past the reserve one cell at a time while the mean block fits, and counts the block that ends the rank', async () => {
+        const cells = [1, 2, 3, 4, 5, 6, 7, 8, 9].map(i => ({ node: at(4 * i), distance: 100 * i }));
+        /** A load in which each block has 280 rows, and the seventh has `seventh`: the cells built, and the store. */
+        const load = async (seventh: number) => {
+            const { records, posted } = await store();
+            const built: number[] = [];
+            for (let frame = 0; frame < 12; frame++) {
+                records.update(cells);
+                await settle();
+                const sent = posted();
+                // Past the reserve, a build starts only when no other is on its way.
+                if (sent.some(({ build }) => (build.cell.x - B.x) / 4 > 6)) expect([sent.length, records.stats.building]).toEqual([1, 1]);
+                for (const { worker, build } of sent) {
+                    const i = (build.cell.x - B.x) / 4;
+                    built.push(i);
+                    worker.answer(build, i === 7 ? seventh : 280);
+                }
+            }
+            return { built, records };
+        };
+        // Six blocks of 280 rows leave 367: no reserve, but the mean fits, so the seventh is tried. Its 250 rows leave 117:
+        // the mean of 276 does not fit, so the eighth is not tried.
+        const fits = await load(250);
+        expect(fits.built).toEqual([1, 2, 3, 4, 5, 6, 7]);
+        expect([fits.records.stats.cells, fits.records.stats.refused, fits.records.loading]).toEqual([7, 0, false]);
+        // A seventh block of 380 rows finds none: it is counted, and it ends the rank.
+        const ends = await load(380);
+        expect(ends.built).toEqual([1, 2, 3, 4, 5, 6, 7]);
+        expect([ends.records.stats.cells, ends.records.stats.refused, ends.records.stats.large, ends.records.waits(at(32)), ends.records.loading]).toEqual([6, 1, 0, false, false]);
+    });
+
+    it('builds the eye\'s cell first, then its neighbours, the nearer first, then the other cells, also when the inputs of the eye\'s cell come last', async () => {
+        // The first tile read, of the eye's cell, takes longer than the others.
+        let first = true;
+        const { records, posted } = await store(async () => {
+            const slow = first;
+            first = false;
+            if (slow) await new Promise(resolve => setTimeout(resolve, 20));
+            return new ArrayBuffer(4);
+        });
+        const eye = at(3, 3), mesh = [{ node: eye, distance: 0 }];
+        // The eye stands in the north-east of its cell.
+        const near = ({ x, y }: typeof A) => Math.hypot(Math.max(0, eye.x - x) * 300 + Math.max(0, x - eye.x) * 100, Math.max(0, y - eye.y) * 200 + Math.max(0, eye.y - y) * 50);
+        const order: number[][] = [], running: ReturnType = [];
+        for (let round = 0; round < 12; round++) {
+            records.update([{ node: eye, distance: 0 }, { node: at(6, 3), distance: 250 }], mesh, false, near);
+            await new Promise(resolve => setTimeout(resolve, 30));
+            const sent = posted();
+            order.push(...sent.map(({ build: { cell } }) => [cell.x - eye.x, cell.y - eye.y]));
+            running.push(...sent);
+            // The build that started first ends first.
+            const done = running.shift();
+            done?.worker.answer(done.build, 1);
+        }
+        // A worker stays free for the eye's cell while the nearest neighbour, whose inputs came first, starts.
+        expect(order).toEqual([[0, -1], [0, 0], [1, 0], [1, -1], [0, 1], [1, 1], [-1, 0], [-1, -1], [-1, 1], [3, 0]]);
+        expect(FakeWorker.all.flatMap(w => w.meshes)).toHaveLength(1);
+    });
+
+    it('does not build a cell that left before its build started, gives no rows to one that left while it ran, and builds the cells of a jump in their order', async () => {
+        const { records, posted } = await store();
+        const far = at(40, 40);
+        records.update([{ node: B, distance: 0 }], [{ node: B, distance: 0 }]);
+        await settle();
+        const old = posted();
+        expect([old.length, records.stats.building]).toEqual([2, 4]);
+        // The eye jumps: the two builds that wait for a worker leave, and two cells about the new eye wait in their place.
+        records.update([{ node: far, distance: 0 }], [{ node: far, distance: 0 }]);
+        await settle();
+        expect([posted(), records.stats.building, records.waits(B), records.waits(far)]).toEqual([[], 4, false, true]);
+        // The old builds arrive: no block takes rows, none counts as refused, and the eye's new cell is the next build.
+        const next: number[][] = [];
+        for (const { worker, build } of old) {
+            worker.answer(build, 1);
+            await settle();
+            next.push(...posted().map(({ build: { cell } }) => [cell.x - far.x, cell.y - far.y]));
+        }
+        expect([records.stats.cells, records.stats.builds, records.stats.refused, records.block(B)]).toEqual([0, 2, 0, undefined]);
+        expect(next).toHaveLength(2);
+        expect(next[0]).toEqual([0, 0]);
+        expect(Math.max(...next[1].map(Math.abs))).toBe(1);
+    });
+
+    it('asks for a mesh once each of the eight neighbours of the cell has a rim, with all their rims, and once only, as the workers answer', async () => {
+        FakeWorker.all = [];
+        vi.stubGlobal('Worker', FakeWorker);
+        vi.stubGlobal('fetch', async () => new Response(readFileSync(new URL('../plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url))));
+        const records = new Records(async () => new ArrayBuffer(4), async () => undefined, () => {}, new AbortController().signal);
+        for (let i = 0; i < 20 && FakeWorker.all.length < 2; i++) await settle();
+        await settle();
+        const mesh = [{ node: B, distance: 0 }], rims = new Map();
+        let rim = 1;
+        // One frame: each answer asks for the next cells, and the last rim for the mesh.
+        records.update([{ node: B, distance: 0 }], mesh);
+        for (let round = 0; round < 12; round++) {
+            await settle();
+            // Until the eight neighbours have rims, no mesh is asked for.
+            if (rims.size < 9) expect(FakeWorker.all.flatMap(w => w.meshes)).toEqual([]);
+            for (const worker of FakeWorker.all) for (const build of worker.builds.splice(0)) {
+                rims.set(`${build.cell.x}/${build.cell.y}`, rim);
+                worker.answer(build, 1, new Uint32Array([rim++]));
+            }
+        }
+        const asked = FakeWorker.all.flatMap(w => w.meshes);
+        expect(rims.size).toBe(9);
+        expect(asked.map(m => [m.cell.x, m.cell.y])).toEqual([[B.x, B.y]]);
+        expect([...asked[0].rims].sort((a, b) => a - b)).toEqual([...rims.values()].sort((a, b) => a - b));
+    });
+
+    it('keeps a full worker while it holds the input of a mesh not asked yet, and draws the pages of a cell whose kept input was lost', async () => {
+        FakeWorker.all = [];
+        vi.stubGlobal('Worker', FakeWorker);
+        vi.stubGlobal('fetch', async () => new Response(readFileSync(new URL('../plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url))));
+        const records = new Records(async () => new ArrayBuffer(4), async () => undefined, () => {}, new AbortController().signal);
+        for (let i = 0; i < 20 && FakeWorker.all.length < 2; i++) await settle();
+        await settle();
+        const mesh = [{ node: B, distance: 0 }];
+        let rim = 1, builtB = 0;
+        // Each build leaves the heap over HEAP_LIMIT, as a town cell can; each live worker answers one build a frame.
+        const frames = async (count: number) => {
+            for (let frame = 0; frame < count && !FakeWorker.all.some(w => !w.dead && w.meshes.length); frame++) {
+                records.update([{ node: B, distance: 0 }], mesh);
+                await settle();
+                await settle();
+                for (const worker of FakeWorker.all.filter(w => !w.dead)) {
+                    const build = worker.builds.shift();
+                    if (build && build.cell.x === B.x && build.cell.y === B.y) builtB++;
+                    if (build) worker.answer(build, 1, new Uint32Array([rim++]), HEAP_LIMIT + 1);
+                }
+            }
+            return FakeWorker.all.find(w => !w.dead && w.meshes.length);
+        };
+        const holder = (await frames(30))!;
+        expect([builtB, holder.meshes.length, records.meshComing(B)]).toEqual([1, 1, true]);
+        // The worker lost the input: the pages draw, and the cell builds again for its mesh.
+        holder.onmessage?.({ data: { id: holder.meshes.shift()!.id, ok: true, gone: true } });
+        expect([records.meshComing(B), records.loading]).toEqual([false, true]);
+        const again = (await frames(30))!;
+        expect(builtB).toBe(2);
+        const restarts = records.stats.restarts;
+        again.onmessage?.({ data: { id: again.meshes[0].id, ok: true, mesh: new ArrayBuffer(4), ms: 1 } });
+        expect(records.settled(B)).toBe(true);
+        // Idle, full, and with no input to keep: the worker ends with its answer.
+        expect(records.stats.restarts).toBeGreaterThan(restarts);
+    });
+
+    it('names a tile to a worker only once a build of it answered, sends every body after a miss, and every body to a new worker', async () => {
+        FakeWorker.all = [];
+        vi.stubGlobal('Worker', FakeWorker);
+        vi.stubGlobal('fetch', async () => new Response(readFileSync(new URL('../plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url))));
+        const records = new Records(async () => new ArrayBuffer(4), async () => undefined, () => {}, new AbortController().signal);
+        for (let i = 0; i < 20 && FakeWorker.all.length < 2; i++) await settle();
+        await settle();
+        // Cells in the middle of tile 4286/2888 read it alone; cells at its east edge read 4287/2888 too.
+        const [C, D, E] = [3, 4, 5].map(dx => ({ level: CELL_LEVEL, x: A.x + dx, y: A.y + 3 }));
+        const [F, G] = [3, 4].map(dy => ({ level: CELL_LEVEL, x: A.x + 7, y: A.y + dy }));
+        const bodies = (build: { tiles: { body?: ArrayBuffer }[] }) => build.tiles.map(({ body }) => !!body);
+        const ask = async (...nodes: (typeof A)[]) => {
+            records.update(nodes.map(node => ({ node, distance: 0 })));
+            await settle();
+            return FakeWorker.all.filter(w => !w.dead).flatMap(worker => worker.builds.splice(0).map(build => ({ worker, build })));
+        };
+        // No worker parsed the tile: each of the two builds carries the body to its worker.
+        const [c, d] = await ask(C, D);
+        expect([bodies(c.build), bodies(d.build), c.worker === d.worker]).toEqual([[true], [true], false]);
+        c.worker.answer(c.build, 1);
+        d.worker.answer(d.build, 1);
+        const [f] = await ask(C, D, F);
+        expect(bodies(f.build)).toEqual([false, true]);
+        f.worker.answer(f.build, 1);
+        // Only F's worker parsed 4287/2888: it gets G with both tiles by name.
+        const [g] = await ask(C, D, F, G);
+        expect([g.worker === f.worker, bodies(g.build)]).toEqual([true, [false, false]]);
+        // The worker let tile 4287/2888 go: the job comes again with every body, also the held one, so it cannot miss again.
+        const worker = g.worker;
+        worker.onmessage?.({ data: { id: g.build.id, ok: true, missing: new Uint32Array([4287, 2888]) } });
+        await settle();
+        const [again] = worker.builds.splice(0);
+        expect([again.id, bodies(again)]).toEqual([g.build.id, [true, true]]);
+        // A trap ends the worker and fails its cell: the worker after it gets the body with its first job.
+        worker.onmessage?.({ data: { id: again.id, ok: false, error: 'unreachable', trapped: true } });
+        for (let i = 0; i < 5; i++) await settle();
+        records.update([C, D, F, G, E].map(node => ({ node, distance: 0 })));
+        await settle();
+        const [fresh] = FakeWorker.all[2].builds;
+        expect([worker.dead, bodies(fresh)]).toEqual([true, [true]]);
+    });
+
+    it('frees the job of a miss whose cell left', async () => {
+        FakeWorker.all = [];
+        vi.stubGlobal('Worker', FakeWorker);
+        vi.stubGlobal('fetch', async () => new Response(readFileSync(new URL('../plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url))));
+        const records = new Records(async () => new ArrayBuffer(4), async () => undefined, () => {}, new AbortController().signal);
+        for (let i = 0; i < 20 && FakeWorker.all.length < 2; i++) await settle();
+        await settle();
+        const C = { level: CELL_LEVEL, x: A.x + 3, y: A.y + 3 }, worker = FakeWorker.all[0];
+        records.update([{ node: C, distance: 0 }]);
+        await settle();
+        worker.answer(worker.builds.shift()!, 1);
+        // The built cell builds again for its mesh, and leaves with a lost device before the worker misses its tile.
+        records.update([{ node: C, distance: 0 }], [{ node: C, distance: 0 }]);
+        await settle();
+        const rebuild = worker.builds.find(({ cell }) => cell.x === C.x && cell.y === C.y)!;
+        records.lost();
+        records.update([]);
+        worker.onmessage?.({ data: { id: rebuild.id, ok: true, missing: new Uint32Array([4286, 2888]) } });
+        for (const w of FakeWorker.all) for (const build of w.builds.splice(0)) if (build !== rebuild) w.answer(build, 1);
+        for (let i = 0; i < 5; i++) await settle();
+        expect(records.stats.building).toBe(0);
+    });
+});
+
+describe('the device cache of built cells', () => {
+    afterEach(() => vi.unstubAllGlobals());
+    const WASM = new Uint8Array(readFileSync(new URL('../plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url)));
+
+    /** An engine's records store on `wasm` and cache key `release` + `version`, its block uploads and meshes, with its two workers ready. */
+    async function engine(wasm: Uint8Array, release: string, version = 'plan a') {
+        FakeWorker.all = [];
+        vi.stubGlobal('Worker', FakeWorker);
+        vi.stubGlobal('fetch', async () => new Response(wasm));
+        // A page loads the bridge once: a new module graph is a new page.
+        vi.resetModules();
+        const { Records } = await import('./model');
+        const meshes: ArrayBuffer[] = [];
+        const records = new Records(async () => new ArrayBuffer(4), async () => undefined, () => {}, new AbortController().signal, mesh => meshes.push(mesh.bytes), () => {}, { release, version });
+        for (let i = 0; i < 20 && FakeWorker.all.length < 2; i++) await settle();
+        await settle();
+        const blocks = () => {
+            const out: number[][] = [];
+            const device = { queue: { writeTexture: (at: { origin?: number[] }, words: Uint32Array) => at.origin && out.push([...words]) } };
+            records.write(device as unknown as GPUDevice, {} as GPUTexture, [0, 0]);
+            return out;
+        };
+        return { records, meshes, blocks };
+    }
+
+    /**
+     * Frames about B, with its mesh unless `mesh` is false; the workers answer each build and mesh with bytes of
+     * the cell, a build of `rows` rows of B, and a failure for the cell `fails`. Returns the cells built, as `x-y` from B.
+     */
+    async function load({ records }: Awaited>, { mesh = true, rows = 1, fails = '' } = {}) {
+        const built: string[] = [];
+        const pause = () => new Promise(resolve => setTimeout(resolve, 10));
+        for (let frame = 0; frame < 30 && (frame < 8 || records.stats.building); frame++) {
+            records.update([{ node: B, distance: 0 }], mesh ? [{ node: B, distance: 0 }] : []);
+            await pause();
+            for (const worker of FakeWorker.all) {
+                for (const { id, cell } of worker.builds.splice(0)) {
+                    const name = `${cell.x - B.x}/${cell.y - B.y}`;
+                    built.push(name);
+                    if (name === fails) {
+                        worker.onmessage?.({ data: { id, ok: false, error: 'a fetch failed', trapped: false } });
+                        continue;
+                    }
+                    const words = Uint32Array.from({ length: (name === '0/0' ? rows : 1) * MODEL_ROW + 7 }, (_, i) => cell.x * 31 + cell.y * 17 + i);
+                    // No labels, so no mouths.
+                    words[2] = 0;
+                    worker.onmessage?.({ data: { id, ok: true, words, rim: new Uint32Array([cell.x, cell.y]), far: new Uint32Array(0), ms: 1, heap: 2 ** 20 } });
+                }
+                for (const { id, rims } of worker.meshes.splice(0)) worker.onmessage?.({ data: { id, ok: true, mesh: new Uint32Array([...rims, 0x4f424d03]).buffer, ms: 1 } });
+            }
+        }
+        // The cache writes after each build: wait until its bytes stop changing.
+        for (let i = 0, last = -1; i < 100 && records.stats.cacheBytes !== last; i++) {
+            last = records.stats.cacheBytes;
+            await pause();
+        }
+        expect(records.settled(B)).toBe(true);
+        return built;
+    }
+
+    it('gives a cell and its mesh as they were built, and misses with another wasm, input preparation or release', async () => {
+        vi.stubGlobal('caches', new FakeCaches());
+        const first = await engine(WASM, 'release a');
+        expect(await load(first)).toHaveLength(9);
+        const again = await engine(WASM, 'release a');
+        expect(await load(again)).toEqual([]);
+        // Blocks take rows in the order that they arrive.
+        const blocks = (side: typeof first) => side.blocks().map(words => words.join()).sort();
+        expect(again.records.stats.hits).toBe(9);
+        // toStrictEqual compares the bytes of ArrayBuffers; toEqual does not.
+        expect(again.meshes).toStrictEqual(first.meshes);
+        expect(blocks(again)).toEqual(blocks(first));
+        // A custom section changes the wasm's bytes, as a change of the crate or its rule tables does.
+        expect(await load(await engine(new Uint8Array([...WASM, 0, 2, 1, 0x78]), 'release a'))).toHaveLength(9);
+        expect(await load(await engine(WASM, 'release a', 'plan b'))).toHaveLength(9);
+        expect(await load(await engine(WASM, 'release b'))).toHaveLength(9);
+    });
+
+    it('places a cached block without room and builds it no more, and keeps no mesh that lacks a failed neighbour\'s rim, which it counts', async () => {
+        vi.stubGlobal('caches', new FakeCaches());
+        // A block of B larger than the texture: it never finds room, so it never has a mesh.
+        await load(await engine(WASM, 'release a'), { mesh: false, rows: 2100 });
+        expect(await load(await engine(WASM, 'release a'))).not.toContain('0/0');
+        vi.stubGlobal('caches', new FakeCaches());
+        const partial = await engine(WASM, 'release a');
+        expect(await load(partial, { fails: '1/1' })).toContain('1/1');
+        expect([partial.meshes.length, partial.records.stats.failed]).toEqual([1, 1]);
+        // B's block comes from the cache, its mesh does not: B builds again for its mesh's input.
+        expect(await load(await engine(WASM, 'release a'))).toEqual(['0/0', '1/1']);
+    });
+
+    it('drops a corrupt or partial entry, and the least recently used past the cap', async () => {
+        vi.stubGlobal('caches', new FakeCaches());
+        const cache = (await DeviceCache.open('cells', 'release', 'build', 3000))!;
+        const words = Uint32Array.from({ length: 300 }, (_, i) => i);
+        for (const x of [1, 2]) await cache.write(`${x}/0/cell`, [words, new Uint32Array([x])]);
+        expect((await cache.read('1/0/cell'))?.map(part => [...part])).toEqual([[...words], [1]]);
+        await cache.write('3/0/cell', [words, new Uint32Array([3])]);
+        // Three entries of a header, a digest and 301 words do not fit 3000 bytes: the second, used least recently, went.
+        expect([await cache.read('2/0/cell'), cache.bytes]).toEqual([undefined, 2 * 4 * (4 + 8 + 301)]);
+        const [name] = await caches.keys(), entries = (globalThis.caches as unknown as FakeCaches).caches.get(name)!;
+        const corrupt = entries.get('https://cache.invalid/1/0/cell')!, partial = entries.get('https://cache.invalid/3/0/cell')!;
+        new Uint32Array(corrupt.body)[20] ^= 1;
+        partial.body = partial.body.slice(0, 400);
+        expect([await cache.read('1/0/cell'), await cache.read('3/0/cell'), entries.size, cache.bytes]).toEqual([undefined, undefined, 0, 0]);
+    });
+});
diff --git a/builder/web/src/lib/trailview/terrain/model.ts b/builder/web/src/lib/trailview/terrain/model.ts
new file mode 100644
index 0000000000..2136c665a4
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/model.ts
@@ -0,0 +1,772 @@
+// The records of the cells about the eye on the device (`ground=plan`): built in plan workers from the
+// cells' inputs, kept nearest first within RECORDS_MB, in one texture of MODEL_ROW words per row that
+// the stamp pass reads (model.wgsl). Row 0 holds a table of the cells about the eye; each block takes
+// whole rows after it. One rank orders the rows: the block of a nearer cell is better, by the cell's own
+// distance to the eye. A cell builds only for rows that are free for it, or for its rim, which the mesh
+// of a neighbour with rows reads. The same build gives a cell's rim and, for the cells that the mesh
+// wants, keeps the input of its mesh in its worker, which meshes it once the rims of its eight neighbours
+// are here: each cell builds once. With a cache key, built cells and meshes go to the device cache
+// (device-cache.ts), which a cell reads before it collects its inputs. A worker's answer asks for the next
+// cells at once, also between frames.
+import { stopped } from '../stream/terrain';
+import { CAPS, DeviceCache } from './device-cache';
+import { bridge, planWorker } from '../plan/bridge';
+import { cellInputs, type CellInputs, type StoredTiles } from '../plan/inputs';
+import { HEAP_LIMIT } from '../plan/plan';
+import { feature_tiles, wanted } from '../plan/pkg/obc_ground_plan_bridge.js';
+import type { CellBuilt, Failed, Meshed, Missing, PlanRequest } from '../plan/plan-worker';
+import { distances, key, type Node } from './lod';
+import type { FeatureTiles } from './stamps';
+
+/** Words per row of the texture: MODEL_ROW of records.wgsl. */
+export const MODEL_ROW = 4096;
+/** The level of the nodes that are cells: zoom 16, NEAR of bins.ts. */
+export const CELL_LEVEL = 16;
+/**
+ * The records' GPU memory. The nearest cells hold it; a town shrinks how far they reach. It holds
+ * every wanted cell of a town view of the fixture.
+ */
+export const RECORDS_MB = 32;
+export const ROWS = (RECORDS_MB * 2 ** 20) / (MODEL_ROW * 4);
+/** The table's first word, as M_TABLE of model.wgsl, and its cells per side about the eye. */
+const TABLE_MAGIC = 0x4f42540a;
+const TABLE = 48;
+/**
+ * Plan workers, and the builds asked for per worker: one runs, and one waits with its inputs for the next free worker.
+ * Two workers halve the time to a full view after a jump.
+ */
+export const WORKERS = 2;
+const JOBS = 2;
+/**
+ * The rows that a build for rows starts with: free for its block, after the blocks of the nearer cells.
+ * A larger block (`large`), and the block of a cell that is tried with fewer free rows, can find no rows.
+ */
+export const RESERVE_ROWS = 384;
+
+type Ranked = { node: Node; distance: number };
+
+type Cell = {
+    node: Node;
+    distance: number;
+    /** The build on its way, and whether it keeps the cell's mesh input. A built cell keeps its block while it builds again. */
+    job?: number;
+    keep?: boolean;
+    rim?: Uint32Array;
+    /** The worker that keeps the cell's mesh input, and the request of the mesh on its way. */
+    worker?: number;
+    mesh?: 'asked' | 'done';
+    meshJob?: number;
+    /** A kept input was lost: the mesh still comes, but the cell's pages no longer wait for it. */
+    lost?: boolean;
+    /** The labels of its block that are junctions with a stop arm (mouthLabels). */
+    mouths?: Set;
+    /** The mesh asked for lacks the rim of a failed neighbour: it differs from a built one, so it is not cached. */
+    partial?: boolean;
+    /** The crate refused the far block of its last build. */
+    farFailed?: boolean;
+} & (
+    // `rows` is the block's size once known. An `over` cell's block has no rows: it asks again when the rank gives it rows.
+    // It holds `words`, its block, while a nearer block on its way decides whether it fits.
+    | { state: 'asked'; rows?: number }
+    | { state: 'built'; first: number; rows: number }
+    | { state: 'over'; rows: number; words?: Uint32Array }
+    | { state: 'empty' }
+    | { state: 'failed' });
+
+export interface RecordsStats {
+    /** Cells with a block, and their bytes on the device. */
+    cells: number;
+    bytes: number;
+    /** Metres from the eye to the farthest cell with a block, and to the farthest wanted cell. */
+    radius: number;
+    wanted: number;
+    building: number;
+    /** The median build of a cell in a worker, and of a mesh, in ms. */
+    build: number;
+    mesh: number;
+    /** The cells read from the device cache, and the bytes that it holds. */
+    hits: number;
+    cacheBytes: number;
+    restarts: number;
+    /** The largest heap of a worker, in bytes. */
+    heap: number;
+    /** The cells whose build failed or whose far block the crate refused. */
+    failed: number;
+    /**
+     * The builds that the workers answered; the blocks of ranked cells that found no rows and whose rim no mesh reads;
+     * each arrival of a block over RESERVE_ROWS, from a worker or the cache and again for each build of the same cell:
+     * a build for such a block can end without rows.
+     */
+    builds: number;
+    refused: number;
+    large: number;
+    error?: string;
+}
+
+/** Row ranges [first, count], sorted, with touching ranges joined. */
+const merged = (ranges: [number, number][]) => [...ranges].sort((a, b) => a[0] - b[0]).reduce<[number, number][]>((out, range) => {
+    const last = out[out.length - 1];
+    if (last && last[0] + last[1] === range[0]) last[1] += range[1];
+    else out.push([...range]);
+    return out;
+}, []);
+
+/** A cell's mesh (`mesh/mod.rs` of obc-ground-plan gives the bytes) and the first word of its block in the texture. */
+export interface CellMeshBytes { node: Node; bytes: ArrayBuffer; block: number; mouths: Set }
+
+/** As LABEL, the junction owner, the junction record (JR, JR_ARM) and ARM_STOP of the crate's `faces::records`. */
+const LABEL_WORDS = 12, OWNER_JUNCTION = 2, JR = 3, JR_ARM = 3, ARM_STOP = 1 << 17;
+
+/** The labels of a records block that are junctions with a stop arm: their faces draw with the mouth's look (plan/pieces.ts). */
+export function mouthLabels(words: Uint32Array): Set {
+    const out = new Set(), first = words[5];
+    for (let id = 0; id < words[2]; id++) {
+        const l = first + id * LABEL_WORDS;
+        if (((words[l] >>> 8) & 0xff) !== OWNER_JUNCTION) continue;
+        const jr = words[words[12] + words[l + 1]];
+        for (let k = 0; k < (words[jr + 2] & 0xff); k++) if (words[jr + JR + JR_ARM * k] & ARM_STOP) out.add(id);
+    }
+    return out;
+}
+
+/** The cell of a node of level CELL_LEVEL or finer. */
+export const cellOf = ({ level, x, y }: Node): Node => ({ level: CELL_LEVEL, x: x >> (level - CELL_LEVEL), y: y >> (level - CELL_LEVEL) });
+
+const around = ({ x, y }: Node): Node[] => [-1, 0, 1].flatMap(dy => [-1, 0, 1].flatMap(dx => (dx || dy ? [{ level: CELL_LEVEL, x: x + dx, y: y + dy }] : [])));
+
+/**
+ * A plan worker, its jobs by id, the build among them, its heap after its last build, the feature tiles that it parsed
+ * (as column/row), and per job on its way the tiles whose body it carries: a tile counts as parsed once that job
+ * answers with its build.
+ */
+interface Slot { worker: Worker; ready: boolean; jobs: Map; build?: number; heap: number; tiles: Set; carried: Map }
+
+/** A build asked for: it waits for its inputs, then for a free worker. */
+interface Job { id: number; name: string; cell: Cell; inputs?: CellInputs }
+
+export class Records {
+    private cells = new Map();
+    /** Free row ranges [first, count]; row 0 is the table. */
+    private free: [number, number][] = [[1, ROWS - 1]];
+    private uploads: { first: number; words: Uint32Array }[] = [];
+    /** The cells whose block arrived or left since the last `takeChanged`. */
+    private changed: Node[] = [];
+    /** The cells that want rows, nearest first, with their own metres from the eye. */
+    private rank = new Map();
+    /** The cells of the rank that get rows, and those that can still get rows once the nearer blocks on their way are known. */
+    private target = new Set();
+    private open = new Set();
+    private meshWanted = new Set();
+    private origin: [number, number] = [-1, -1];
+    private tableDirty = true;
+    private pool: Slot[] = [];
+    /** The builds not posted yet, in the order of their asks. */
+    private asked: Job[] = [];
+    private module?: WebAssembly.Module;
+    private words = 0;
+    private next = 0;
+    private times: number[] = [];
+    private meshTimes: number[] = [];
+    private restarts = 0;
+    private builds = 0;
+    private refused = 0;
+    private large = 0;
+    private error?: string;
+    private wantedM = 0;
+    private heap = 0;
+    private cache?: Promise;
+    /** The cache once open, for the stats. */
+    private opened?: DeviceCache;
+    private hits = 0;
+    /** The arguments of the last `update`, which every answer of a worker asks again with. */
+    private last?: Parameters;
+
+    /**
+     * `meshed` takes each cell's mesh as it arrives, `unmeshed` each cell whose mesh leaves. `cache` names the
+     * data of the tiles and the version of the plan worker's input preparation (`virtual:plan-version`): without
+     * it, nothing is cached.
+     */
+    constructor(private readonly features: FeatureTiles | undefined, private readonly stored: StoredTiles, private readonly onChange: () => void, private readonly stop: AbortSignal,
+        private readonly meshed: (mesh: CellMeshBytes) => void = () => {}, private readonly unmeshed: (node: Node) => void = () => {}, private readonly cacheKey?: { release: string; version: string }) {
+        stop.addEventListener('abort', () => this.pool.forEach(({ worker }) => worker.terminate()));
+        if (!features) {
+            this.error = 'the release has no feature tiles';
+            return;
+        }
+        void this.load();
+    }
+
+    private async load(): Promise {
+        try {
+            const { module, vocabulary, digest } = await bridge();
+            if (this.cacheKey) {
+                const { release, version } = this.cacheKey;
+                this.cache = DeviceCache.open('cells', release, `${digest}/${version}`, CAPS.cells).then(cache => (this.opened = cache), error => {
+                    console.warn(`The ground plan's device cache did not open: ${error}`);
+                    return undefined;
+                });
+            }
+            this.words = vocabulary.words.wanted;
+            this.module = module;
+            for (let k = 0; k < WORKERS; k++) this.spawn(k);
+        } catch (error) {
+            this.error = `the records bridge did not start: ${error instanceof Error ? error.message : error}`;
+            this.onChange();
+        }
+    }
+
+    private spawn(k: number): void {
+        if (this.stop.aborted) return;
+        const worker = planWorker();
+        this.pool[k] = { worker, ready: false, jobs: new Map(), heap: 0, tiles: new Set(), carried: new Map() };
+        worker.onmessage = ({ data }: MessageEvent<{ type: 'ready'; error?: string } | CellBuilt | Meshed | Missing | Failed>) => this.receive(k, worker, data);
+        worker.onerror = event => {
+            if (worker !== this.pool[k].worker) return;
+            this.error = `a records worker failed: ${event.message}`;
+            this.pool[k].ready = false;
+            this.onChange();
+        };
+        worker.postMessage({ type: 'start', module: this.module! } satisfies PlanRequest);
+    }
+
+    /** Ends worker k and starts another: its builds go back to not asked, its kept mesh inputs are gone. */
+    private restart(k: number): void {
+        const old = this.pool[k];
+        old.worker.terminate();
+        this.restarts++;
+        for (const name of old.jobs.values()) {
+            const cell = this.cells.get(name);
+            if (cell?.state === 'asked') this.cells.delete(name);
+            else if (cell) {
+                cell.job = undefined;
+                if (cell.mesh === 'asked') cell.mesh = undefined;
+            }
+        }
+        for (const cell of this.cells.values()) {
+            if (cell.worker !== k) continue;
+            cell.worker = undefined;
+            cell.lost = true;
+        }
+        this.spawn(k);
+    }
+
+    /**
+     * Ends worker k once its heap is full, no build waits, it is idle, and it keeps no input of a mesh still to ask:
+     * WASM memory never shrinks, and a restart that drops a kept input makes the cell build again.
+     */
+    private recycle(k: number): void {
+        const slot = this.pool[k];
+        if (slot.heap > HEAP_LIMIT && !slot.jobs.size && !this.asked.length && ![...this.cells.values()].some(cell => cell.worker === k)) this.restart(k);
+    }
+
+    private receive(k: number, worker: Worker, data: { type: 'ready'; error?: string } | CellBuilt | Meshed | Missing | Failed): void {
+        const slot = this.pool[k];
+        if (worker !== slot.worker) return;
+        if ('type' in data) {
+            if (data.error) this.error = `the records worker did not start: ${data.error}`;
+            else slot.ready = true;
+            return this.answered();
+        }
+        const carried = slot.carried.get(data.id) ?? [];
+        slot.carried.delete(data.id);
+        if ('missing' in data) {
+            for (let i = 0; i < data.missing.length; i += 2) slot.tiles.delete(`${data.missing[i]}/${data.missing[i + 1]}`);
+            const name = slot.jobs.get(data.id) ?? '', cell = this.cells.get(name);
+            // The job goes again with every body, so it cannot miss twice. The job of a cell that left the rank ends.
+            if (cell?.job === data.id && this.rank.has(name)) void this.resend(k, data.id, cell);
+            else {
+                if (cell?.job === data.id) cell.job = undefined;
+                slot.jobs.delete(data.id);
+                slot.build = undefined;
+                this.answered();
+            }
+            return;
+        }
+        if (slot.build === data.id) slot.build = undefined;
+        if ('words' in data) carried.forEach(tile => slot.tiles.add(tile));
+        const name = slot.jobs.get(data.id);
+        slot.jobs.delete(data.id);
+        const cell = name === undefined ? undefined : this.cells.get(name);
+        if (!data.ok) {
+            console.warn(`Ground plan cell ${name}: ${data.error}`);
+            if (cell?.job === data.id) {
+                cell.job = undefined;
+                if (cell.state === 'asked') Object.assign(cell, { state: 'failed' });
+                else cell.mesh = 'done';
+            } else if (cell?.mesh === 'asked' && cell.meshJob === data.id) {
+                cell.mesh = 'done';
+                cell.worker = undefined;
+            }
+            if (data.trapped) this.restart(k);
+        } else if ('words' in data) {
+            this.heap = Math.max(this.heap, data.heap);
+            slot.heap = data.heap;
+            if (cell?.job === data.id) {
+                cell.farFailed = 'error' in data.far;
+                if ('error' in data.far) console.warn(`Ground plan cell ${name}: far block: ${data.far.error}`);
+                this.times = [...this.times.slice(-31), data.ms];
+                this.builds++;
+                this.keep(cell, 'cell', [data.words, data.rim]);
+                if (cell.keep && this.meshWanted.has(name!)) cell.worker = k;
+                else if (cell.keep) worker.postMessage({ type: 'drop', cell: cell.node } satisfies PlanRequest);
+                this.built(cell, data.words, data.rim);
+            }
+        } else if (cell?.mesh === 'asked' && cell.meshJob === data.id) {
+            cell.worker = undefined;
+            if ('gone' in data) Object.assign(cell, { mesh: undefined, lost: true });
+            else {
+                if (!cell.partial) this.keep(cell, 'mesh', [new Uint32Array(data.mesh)]);
+                cell.mesh = undefined;
+                this.meshTimes = [...this.meshTimes.slice(-31), data.ms];
+                this.mesh(cell, data.mesh);
+            }
+        }
+        this.answered();
+    }
+
+    /** After an answer of a worker or the cache: the next cells are asked for at once, and the next frame draws what came. */
+    private answered(): void {
+        if (this.last && !this.stop.aborted) this.update(...this.last);
+        this.onChange();
+    }
+
+    /** Takes a cell's block and rim, from its worker or the cache. A built cell that built again for its mesh keeps its block. */
+    private built(cell: Cell, words: Uint32Array, rim: Uint32Array): void {
+        cell.job = undefined;
+        cell.rim = rim;
+        if (cell.state === 'built') return;
+        const rows = Math.ceil(words.length / MODEL_ROW);
+        if (rows > RESERVE_ROWS) this.large++;
+        Object.assign(cell, { state: 'over', rows, words });
+        this.decide();
+    }
+
+    /**
+     * The cells of the rank whose blocks fit the rows, nearest first, up to the first that does not fit: so no cell is
+     * refused while a farther cell gets rows. A known block takes its rows. A block not built yet needs RESERVE_ROWS,
+     * which it takes from the cells after it if `sure`. Where the reserve does not fit, the rows fill one cell at a
+     * time: a cell is tried while the mean of the nearer blocks fits and, if `sure`, only once each nearer block is
+     * known, with no cell after it. A block larger than the texture takes no part.
+     */
+    private fitting(sure: boolean): Set {
+        const out = new Set();
+        let left = ROWS - 1, known = 0, count = 0, coming = 0;
+        for (const name of this.rank.keys()) {
+            const cell = this.cells.get(name);
+            if (cell?.state === 'empty' || cell?.state === 'failed') continue;
+            const rows = cell && 'rows' in cell ? cell.rows : undefined;
+            if (rows !== undefined) {
+                if (rows > ROWS - 1) continue;
+                if (rows > left) break;
+                left -= rows;
+                known += rows;
+                count++;
+            } else if (RESERVE_ROWS <= left) {
+                if (sure) left -= RESERVE_ROWS;
+                coming++;
+            } else if ((sure && coming) || !count || left < known / count) break;
+            else if (sure) {
+                out.add(name);
+                break;
+            }
+            out.add(name);
+        }
+        return out;
+    }
+
+    /**
+     * Makes the target: the cells that get rows also if each block on its way takes RESERVE_ROWS. A block that arrived
+     * takes its rows when its cell is in the target. It waits while its cell is `open`: in the target if the nearer
+     * blocks on their way are small. Else it goes: its cell keeps the rim and the size.
+     */
+    private decide(): void {
+        this.target = this.fitting(true);
+        this.open = this.fitting(false);
+        for (const [name, cell] of this.cells) {
+            if (cell.state !== 'over' || !cell.words) continue;
+            if (this.target.has(name)) this.place(cell, cell.words);
+            else if (!this.open.has(name)) this.refuse(name, cell);
+        }
+    }
+
+    /** Lets the block of an `over` cell go, with the kept input of its mesh. */
+    private refuse(name: string, cell: Cell): void {
+        if (this.rank.has(name) && !around(cell.node).some(other => this.reads(key(other)))) this.refused++;
+        Object.assign(cell, { words: undefined });
+        this.unmesh(cell);
+    }
+
+    /** Whether a cell's mesh reads the rims of its neighbours: the mesh wants it, and it has rows or its build gets them. */
+    private reads(name: string): boolean {
+        const state = this.cells.get(name)?.state;
+        return this.meshWanted.has(name) && (state === 'built' || (this.target.has(name) && (state === undefined || state === 'asked')));
+    }
+
+    /** Draws a cell's mesh while the cell has its block and the mesh wants it. */
+    private mesh(cell: Cell, bytes: ArrayBuffer): void {
+        if (cell.state !== 'built' || !this.meshWanted.has(key(cell.node))) return;
+        cell.mesh = 'done';
+        this.meshed({ node: cell.node, bytes, block: cell.first * MODEL_ROW, mouths: cell.mouths ?? new Set() });
+    }
+
+    /** Writes a cell's entry to the device cache, off the critical path. */
+    private keep(cell: Cell, part: 'cell' | 'mesh', parts: Uint32Array[]): void {
+        void this.cache?.then(cache => cache?.write(`${cell.node.x}/${cell.node.y}/${part}`, parts)).catch(error => console.warn(`The ground plan's device cache did not keep ${key(cell.node)}: ${error}`));
+    }
+
+    /** A cell from the device cache: its block and rim, and its mesh when `mesh` and the cache holds it; undefined without the cell's entry. */
+    private async cached(node: Node, mesh: boolean): Promise<{ words: Uint32Array; rim: Uint32Array; mesh?: ArrayBuffer } | undefined> {
+        const cache = await this.cache;
+        if (!cache) return undefined;
+        try {
+            const [cell, meshed] = await Promise.all([cache.read(`${node.x}/${node.y}/cell`), mesh ? cache.read(`${node.x}/${node.y}/mesh`) : undefined]);
+            if (!cell) return undefined;
+            return { words: cell[0], rim: cell[1], mesh: meshed?.[0].buffer as ArrayBuffer | undefined };
+        } catch {
+            return undefined;
+        }
+    }
+
+    /** The built cells that leave for the block of a target cell, in order: those past the rank, then those past the target, each farthest first. */
+    private leaving(): [string, Cell][] {
+        return [...this.cells.entries()].filter(([name, c]) => c.state === 'built' && !this.target.has(name))
+            .sort(([a, ca], [b, cb]) => Number(this.rank.has(a)) - Number(this.rank.has(b)) || cb.distance - ca.distance);
+    }
+
+    /** Whether a run of `rows` free rows exists once the `leaving` cells go. */
+    private room(rows: number, leaving: [string, Cell][]): boolean {
+        const taken = leaving.flatMap(([, c]): [number, number][] => (c.state === 'built' ? [[c.first, c.rows]] : []));
+        return merged([...this.free, ...taken]).some(([, count]) => count >= rows);
+    }
+
+    /**
+     * Puts the block of a target cell into free rows; the `leaving` cells go, in order, until it fits. The target's
+     * blocks fit by their count of rows; where the free rows make no run of its size, the block goes.
+     */
+    private place(cell: Cell, words: Uint32Array): void {
+        const rows = Math.ceil(words.length / MODEL_ROW), leaving = this.leaving();
+        if (!this.room(rows, leaving)) return this.refuse(key(cell.node), cell);
+        let first = this.allocate(rows);
+        while (first === undefined) {
+            this.evict(leaving.shift()![1]);
+            first = this.allocate(rows);
+        }
+        Object.assign(cell, { state: 'built', first, rows, words: undefined, mouths: mouthLabels(words) });
+        const padded = new Uint32Array(rows * MODEL_ROW);
+        padded.set(words);
+        this.uploads.push({ first, words: padded });
+        this.changed.push(cell.node);
+        this.tableDirty = true;
+    }
+
+    private allocate(rows: number): number | undefined {
+        const k = this.free.findIndex(([, count]) => count >= rows);
+        if (k < 0) return undefined;
+        const [first, count] = this.free[k];
+        if (count === rows) this.free.splice(k, 1);
+        else this.free[k] = [first + rows, count - rows];
+        return first;
+    }
+
+    /** Takes a built cell's block off the rows, and its mesh off: the cell keeps its rim and its size. */
+    private evict(cell: Cell): void {
+        if (cell.state !== 'built') return;
+        this.free = merged([...this.free, [cell.first, cell.rows]]);
+        this.changed.push(cell.node);
+        this.tableDirty = true;
+        this.unmesh(cell);
+        Object.assign(cell, { state: 'over' });
+    }
+
+    /** Takes a cell's mesh off, and frees its kept input. */
+    private unmesh(cell: Cell): void {
+        if (cell.mesh === 'done') this.unmeshed(cell.node);
+        if (cell.worker !== undefined && cell.mesh !== 'asked') this.pool[cell.worker]?.worker.postMessage({ type: 'drop', cell: cell.node } satisfies PlanRequest);
+        cell.mesh = undefined;
+        cell.worker = undefined;
+    }
+
+    /**
+     * Takes the cells under the frame's wanted near pages and the cells of `mesh`, which get their meshes, each with
+     * its metres from the eye; `near` gives those of a neighbour of a mesh cell, which wants rows as they do. The
+     * workers build the next cells of the target and, for each mesh cell that has rows or gets them, its neighbours
+     * for their rims: in one near-first order, each neighbour as near as its mesh cell and, of two as near, the
+     * nearer cell first. So the eye's cell comes first, then its eight neighbours. With `meshLater` (the meshes do
+     * not draw) the neighbours build only after the whole target.
+     */
+    update(cells: Ranked[], mesh: Ranked[] = [], meshLater = false, near: (node: Node) => number = () => Infinity): void {
+        this.last = [cells, mesh, meshLater, near];
+        const meshNames = new Set(mesh.map(({ node }) => key(node)));
+        for (const name of this.meshWanted) {
+            const cell = this.cells.get(name);
+            if (cell && !meshNames.has(name)) this.unmesh(cell);
+        }
+        this.meshWanted = meshNames;
+        const ranked = new Map([...cells, ...mesh].map(entry => [key(entry.node), entry]));
+        for (const { node } of mesh) for (const other of around(node)) if (!ranked.has(key(other))) ranked.set(key(other), { node: other, distance: near(other) });
+        this.rank = new Map([...ranked].sort(([a, ca], [b, cb]) => ca.distance - cb.distance || (a < b ? -1 : 1)));
+        // A build not posted yet whose cell left the rank is not built.
+        this.asked = this.asked.filter(({ name, cell }) => {
+            if (this.rank.has(name)) return true;
+            cell.job = undefined;
+            return false;
+        });
+        for (const [name, cell] of this.cells) {
+            const own = this.rank.get(name);
+            if (own) cell.distance = own.distance;
+            // A cell past the rank keeps its block until a target cell takes its rows, and its posted build until it
+            // answers: the answer drops the mesh input that the worker kept for it.
+            else if (cell.state !== 'built' && cell.job === undefined) {
+                this.unmesh(cell);
+                this.cells.delete(name);
+            }
+        }
+        this.wantedM = cells.length ? cells[cells.length - 1].distance : 0;
+        this.decide();
+        // A mesh cell built without its input builds again first.
+        const again = mesh.filter(({ node }) => {
+            const cell = this.cells.get(key(node));
+            return cell?.state === 'built' && cell.job === undefined && cell.worker === undefined && cell.mesh === undefined;
+        });
+        // A target cell that lost its block asks again once its rows are free.
+        const rows = [...this.target].flatMap(name => {
+            const cell = this.cells.get(name);
+            return !cell || (cell.state === 'over' && cell.job === undefined && this.room(cell.rows, this.leaving())) ? [this.rank.get(name)!] : [];
+        });
+        const rims = mesh.filter(({ node }) => this.reads(key(node))).flatMap(({ node, distance }) => around(node).filter(other => !this.cells.has(key(other))).map(other => ({ node: other, distance })));
+        const own = (node: Node) => this.rank.get(key(node))?.distance ?? Infinity;
+        const nearest = (list: Ranked[]) => list.sort((a, b) => a.distance - b.distance || own(a.node) - own(b.node));
+        const order = meshLater ? [...nearest(rows), ...again, ...nearest(rims)] : [...again, ...nearest([...rims, ...rows])];
+        const asked = new Set();
+        for (const { node, distance } of order) {
+            if (asked.has(key(node))) continue;
+            asked.add(key(node));
+            if (!this.ask(node, distance)) break;
+        }
+        // A mesh goes to its worker before the next build.
+        for (const name of meshNames) this.meshIfReady(name);
+        this.dispatch();
+        this.pool.forEach((_, k) => this.recycle(k));
+    }
+
+    /**
+     * Asks for a cell, with its mesh input kept when the mesh wants it; false when the workers have their builds. The
+     * cell comes from the device cache, or its build waits for its inputs and then for a free worker.
+     */
+    private ask(node: Node, distance: number): boolean {
+        if (!this.module || this.asked.length + this.pool.filter(slot => slot.build !== undefined).length >= WORKERS * JOBS) return false;
+        const name = key(node), id = this.next++, keep = this.meshWanted.has(name);
+        const old = this.cells.get(name);
+        // A built cell keeps its block while it builds again for its mesh; an `over` cell keeps its size and its rim.
+        const cell: Cell = old?.state === 'built' ? old : old?.state === 'over' ? (Object.assign(old, { state: 'asked' }) as Cell) : { node, distance: this.rank.get(name)?.distance ?? distance, state: 'asked' };
+        Object.assign(cell, { job: id, keep });
+        this.cells.set(name, cell);
+        const job: Job = { id, name, cell };
+        this.asked.push(job);
+        const leave = () => this.asked.includes(job) && this.asked.splice(this.asked.indexOf(job), 1).length > 0;
+        void (async () => {
+            try {
+                const hit = await this.cached(node, keep);
+                if (!this.asked.includes(job)) return;
+                if (hit) {
+                    this.hits++;
+                    this.built(cell, hit.words, hit.rim);
+                    if (hit.mesh) this.mesh(cell, hit.mesh);
+                    // A placed block whose mesh the cache lacks builds again for the mesh's input; a block without rows has no mesh.
+                    const done = hit.mesh || !keep || cell.state !== 'built';
+                    if (done) leave();
+                    else cell.job = id;
+                    this.answered();
+                    if (done) return;
+                }
+                // A feature tile that every worker parsed goes by name.
+                const inputs = await cellInputs(node, { feature_tiles, wanted, words: this.words }, this.features!, this.stored, (column, row) => this.pool.every(slot => slot.tiles.has(`${column}/${row}`)));
+                if (!this.asked.includes(job)) return;
+                if (inputs === 'empty') {
+                    leave();
+                    return this.empty(cell);
+                }
+                job.inputs = inputs;
+                this.dispatch();
+            } catch (error) {
+                if (leave()) this.lose(cell, error);
+            }
+        })();
+        return true;
+    }
+
+    /**
+     * Posts the builds whose inputs are here to the free workers, in the order of their asks: a worker stays free for
+     * each earlier build whose inputs are on their way. So the eye's cell is the first build of its worker.
+     */
+    private dispatch(): void {
+        const free = this.pool.flatMap((slot, k) => (slot.ready && slot.build === undefined ? [k] : []));
+        for (let at = this.asked.findIndex(job => job.inputs); at >= 0 && at < free.length; at = this.asked.findIndex(job => job.inputs)) {
+            const [job] = this.asked.splice(at, 1);
+            this.post(free.shift()!, job.id, job.cell, job.inputs!);
+        }
+    }
+
+    /** Posts a build to worker k: a feature tile that the worker parsed goes by name, unless `bodies`. */
+    private post(k: number, id: number, cell: Cell, inputs: CellInputs, bodies = false): void {
+        const slot = this.pool[k];
+        const tiles = inputs.tiles.map(({ column, row, body }) => (!bodies && slot.tiles.has(`${column}/${row}`) ? { column, row } : { column, row, body }));
+        slot.jobs.set(id, key(cell.node));
+        slot.build = id;
+        slot.worker.postMessage({ type: 'cell', id, cell: cell.node, ...inputs, tiles, mesh: !!cell.keep } satisfies PlanRequest, tiles.flatMap(({ body }) => (body ? [body] : [])));
+        slot.carried.set(id, tiles.flatMap(({ column, row, body }) => (body ? [`${column}/${row}`] : [])));
+    }
+
+    /** Posts a build again with the body of every tile, after its worker missed one: so it cannot miss twice. */
+    private async resend(k: number, id: number, cell: Cell): Promise {
+        const slot = this.pool[k];
+        const leave = () => {
+            slot.jobs.delete(id);
+            if (slot.build === id) slot.build = undefined;
+        };
+        try {
+            const inputs = await cellInputs(cell.node, { feature_tiles, wanted, words: this.words }, this.features!, this.stored);
+            if (!slot.jobs.has(id) || slot !== this.pool[k]) return;
+            if (inputs !== 'empty') return this.post(k, id, cell, inputs, true);
+            leave();
+            this.empty(cell);
+        } catch (error) {
+            leave();
+            this.lose(cell, error);
+        }
+    }
+
+    /** A cell without a feature tile has no block. */
+    private empty(cell: Cell): void {
+        cell.job = undefined;
+        if (cell.state === 'asked') Object.assign(cell, { state: 'empty' });
+        this.answered();
+    }
+
+    /** A build whose inputs did not come: its cell fails, unless the engine stopped. */
+    private lose(cell: Cell, error: unknown): void {
+        if (stopped(error)) return;
+        cell.job = undefined;
+        if (cell.state === 'asked') Object.assign(cell, { state: 'failed' });
+        else cell.mesh = 'done';
+        this.answered();
+    }
+
+    /** Asks for a cell's mesh once it is built with its input kept and each neighbour is built or empty. */
+    private meshIfReady(name: string): void {
+        const cell = this.cells.get(name);
+        if (cell?.state !== 'built' || cell.worker === undefined || cell.mesh !== undefined || !cell.rim) return;
+        const rims: Uint32Array[] = [cell.rim];
+        let waiting = false, partial = false;
+        for (const other of around(cell.node)) {
+            const neighbour = this.cells.get(key(other));
+            if (neighbour?.rim) rims.push(neighbour.rim);
+            else if (neighbour?.state === 'failed') partial = true;
+            // A neighbour on its way, or not asked yet: `update` asks for it, for its rim.
+            else if (neighbour?.state !== 'empty') waiting = true;
+        }
+        if (waiting) return;
+        const slot = this.pool[cell.worker], id = this.next++;
+        const all = new Uint32Array(rims.reduce((sum, r) => sum + r.length, 0));
+        rims.reduce((at, r) => (all.set(r, at), at + r.length), 0);
+        Object.assign(cell, { mesh: 'asked', meshJob: id, partial });
+        slot.jobs.set(id, name);
+        slot.worker.postMessage({ type: 'mesh', id, cell: cell.node, rims: all } satisfies PlanRequest, [all.buffer]);
+    }
+
+    /** Whether a cell's block is to come: the cell can still get rows, and its block is not asked yet, on its way, or waits for a nearer one. */
+    private coming(name: string): boolean {
+        const cell = this.cells.get(name);
+        return this.open.has(name) && (!cell || cell.state === 'asked' || (cell.state === 'over' && !!cell.words));
+    }
+
+    /** Whether a page of a near node waits for its cell's block. Nothing waits for a cell that gets no rows, or once the records failed. */
+    waits(node: Node): boolean {
+        return node.level >= CELL_LEVEL && !this.error && this.coming(key(cellOf(node)));
+    }
+
+    /** Whether the pages of a cell wait for its mesh: the mesh wants the cell, it is not settled, and no kept input of it was lost. */
+    meshComing(node: Node): boolean {
+        const name = key(node);
+        return !this.error && this.meshWanted.has(name) && !this.cells.get(name)?.lost && !this.settled(node);
+    }
+
+    /** The rows of each built cell's block, for the determinism check. */
+    blocks(): { name: string; first: number; rows: number }[] {
+        return [...this.cells].flatMap(([name, cell]) => (cell.state === 'built' ? [{ name, first: cell.first, rows: cell.rows }] : []));
+    }
+
+    /** The first word of a cell's block in the texture, undefined while it has none. */
+    block(node: Node): number | undefined {
+        const cell = this.cells.get(key(node));
+        return cell?.state === 'built' ? cell.first * MODEL_ROW : undefined;
+    }
+
+    /** Whether a cell is settled for the mesh: meshed, or with no mesh to come, as a cell that gets no rows. */
+    settled(node: Node): boolean {
+        const name = key(node), cell = this.cells.get(name);
+        return cell?.state === 'built' ? cell.mesh === 'done' : !this.coming(name);
+    }
+
+    /** The cells whose block arrived or left since the last call: their pages are stamped again. */
+    takeChanged(): Node[] {
+        const out = this.changed;
+        this.changed = [];
+        return out;
+    }
+
+    /** Uploads the arrived blocks and the table of the cells about `eye` (a world point of level 30). */
+    write(device: GPUDevice, texture: GPUTexture, eye: [number, number]): void {
+        for (const { first, words } of this.uploads) device.queue.writeTexture({ texture, origin: [0, first] }, words, { bytesPerRow: MODEL_ROW * 4 }, [MODEL_ROW, words.length / MODEL_ROW]);
+        this.uploads = [];
+        const origin: [number, number] = [Math.floor(eye[0] / 2 ** 14) - TABLE / 2, Math.floor(eye[1] / 2 ** 14) - TABLE / 2];
+        if (!this.tableDirty && origin[0] === this.origin[0] && origin[1] === this.origin[1]) return;
+        this.origin = origin;
+        this.tableDirty = false;
+        const table = new Uint32Array(MODEL_ROW);
+        table.set([TABLE_MAGIC, origin[0], origin[1], TABLE, TABLE]);
+        for (const cell of this.cells.values()) {
+            const i = cell.node.x - origin[0], j = cell.node.y - origin[1];
+            if (cell.state === 'built' && i >= 0 && j >= 0 && i < TABLE && j < TABLE) table[5 + j * TABLE + i] = cell.first * MODEL_ROW;
+        }
+        device.queue.writeTexture({ texture }, table, { bytesPerRow: MODEL_ROW * 4 }, [MODEL_ROW, 1]);
+    }
+
+    /** A new device holds no block: every cell with rows asks again. */
+    lost(): void {
+        for (const cell of this.cells.values()) this.evict(cell);
+        this.changed = [];
+        this.uploads = [];
+        this.tableDirty = true;
+    }
+
+    /** True while a block is to come, or a mesh cell is not settled. False once the records failed, so a wait for an idle view ends. */
+    get loading(): boolean {
+        if (this.error) return false;
+        return [...this.open].some(name => this.coming(name)) || [...this.meshWanted].some(name => !this.settled(nodeOf(name)));
+    }
+
+    get stats(): RecordsStats {
+        const built = [...this.cells.values()].flatMap(c => (c.state === 'built' ? [c] : []));
+        const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)] ?? 0;
+        return {
+            cells: built.length, bytes: built.reduce((sum, c) => sum + c.rows * MODEL_ROW * 4, 0), radius: Math.max(0, ...built.map(c => c.distance)), wanted: this.wantedM,
+            building: this.asked.length + this.pool.reduce((sum, slot) => sum + (slot?.jobs.size ?? 0), 0), build: median(this.times), mesh: median(this.meshTimes), hits: this.hits, cacheBytes: this.opened?.bytes ?? 0,
+            restarts: this.restarts, heap: this.heap, failed: [...this.cells.values()].filter(c => c.state === 'failed' || c.farFailed).length,
+            builds: this.builds, refused: this.refused, large: this.large,
+            ...(this.error ? { error: this.error } : {}),
+        };
+    }
+}
+
+const nodeOf = (name: string): Node => {
+    const [level, x, y] = name.split('/').map(Number);
+    return { level, x, y };
+};
+
+/** The cells under near nodes, each once, nearest first, with the metres from the eye to their squares. */
+export function nearCells(nodes: Node[], eye: Parameters[0]): { node: Node; distance: number }[] {
+    const cells = new Map();
+    for (const node of nodes) if (node.level >= CELL_LEVEL) cells.set(key(cellOf(node)), cellOf(node));
+    return [...cells.values()].map(node => ({ node, distance: distances(eye, node)[0] })).sort((a, b) => a.distance - b.distance);
+}
diff --git a/builder/web/src/lib/trailview/terrain/model.wgsl b/builder/web/src/lib/trailview/terrain/model.wgsl
new file mode 100644
index 0000000000..3a63425bfa
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/model.wgsl
@@ -0,0 +1,472 @@
+// The one road model at a texel of a page: the crate's `faces::records::find` on the records of the
+// cell that holds the point, with the distances that the stamp writes into a page's textures. Every
+// side test is exact on integers, with find's (ε, ε²) rule at a tie, so the GPU and the CPU give a
+// point the same label. The records lie in model_words: a table of the cells about the eye, then the
+// blocks (model.ts).
+// #include heights.wgsl
+// #include mouth.wgsl
+
+// The stamp shapes and paints the ground from the records (`ground=plan`).
+override MODEL: bool = false;
+
+// The level of the nodes that are cells, CELL_LEVEL of model.ts: the records shape the pages of it
+// and finer. A coarser page is not stamped again when a block arrives or leaves.
+const M_CELL_LEVEL: u32 = 16u;
+// The table's first word, as TABLE_MAGIC of model.ts.
+const M_TABLE: u32 = 0x4f42540au;
+// Candidate kinds and surfaces, as records.rs and faces::Surface.
+const M_WAY: u32 = 0u;
+const M_POINT: u32 = 1u;
+const M_REGION: u32 = 2u;
+const M_OUTLINE: u32 = 5u;
+const S_CARRIAGEWAY: u32 = 2u;
+const S_CROSSING: u32 = 6u;
+const S_RAILBED: u32 = 7u;
+const M_BIN_UNITS: i32 = 4096;
+// The candidates that cover a point at most, and those whose edge lies near enough to change its paint.
+const M_COVER: u32 = 24u;
+const M_NEAR: u32 = 8u;
+// A round's chords leave its arc by at most this share of its radius (the overlay's 10° steps, with room).
+const M_SAGITTA: f32 = 0.0055;
+
+struct ModelPoint {
+    // The block of the cell that holds the point; 0 where no records hold it.
+    block: u32,
+    // The point in frame units from the cell's origin.
+    q: vec2i,
+    // The label (an index of the block's labels), M_NONE for terrain.
+    label: u32,
+    // The paved label that the paint draws: the point's own where it is paved, else the paved one across
+    // the nearest change within the reach; M_NONE for none.
+    painted: u32,
+    // Metres to the paved outline and the rail beds (negative inside) and to the core's outline: those
+    // and the ways' band layers but the slope.
+    d_paved: f32,
+    core: f32,
+    // Metres across from the middle of the painted label's host line (signed by side), along it, and its
+    // half-width; across is M_FAR where no host line lies in the bin.
+    across: f32,
+    along: f32,
+    half: f32,
+    // The first word of the bin's height lists, for height_at.
+    heights: u32,
+    // The stop arm line whose mouth holds the point in a junction's face (m_mouth), M_NONE for none.
+    mouth: u32,
+}
+
+// The product of two i32 as a signed 64-bit number: (low word, high word).
+fn m_mul(a: i32, b: i32) -> vec2u {
+    let x = u32(abs(a));
+    let y = u32(abs(b));
+    let x0 = x & 0xffffu;
+    let x1 = x >> 16u;
+    let y0 = y & 0xffffu;
+    let y1 = y >> 16u;
+    let p00 = x0 * y0;
+    let p01 = x0 * y1;
+    let p10 = x1 * y0;
+    let mid = (p00 >> 16u) + (p01 & 0xffffu) + (p10 & 0xffffu);
+    var lo = (p00 & 0xffffu) | (mid << 16u);
+    var hi = x1 * y1 + (p01 >> 16u) + (p10 >> 16u) + (mid >> 16u);
+    if ((a < 0) != (b < 0)) {
+        lo = ~lo + 1u;
+        hi = ~hi + select(0u, 1u, lo == 0u);
+    }
+    return vec2u(lo, hi);
+}
+
+// The sign of cross(a, b), exact for components of up to 31 bits.
+fn m_orient(a: vec2i, b: vec2i) -> i32 {
+    let l = m_mul(a.x, b.y);
+    let r = m_mul(a.y, b.x);
+    if (l.y != r.y) {
+        return select(-1, 1, bitcast(l.y) > bitcast(r.y));
+    }
+    if (l.x != r.x) {
+        return select(-1, 1, l.x > r.x);
+    }
+    return 0;
+}
+
+// Whether point p moved by (ε, ε²) lies left of the line through a along e, as records::left.
+fn m_left(e: vec2i, a: vec2i, p: vec2i) -> bool {
+    let s = m_orient(e, p - a);
+    if (s != 0) {
+        return s > 0;
+    }
+    return e.y < 0 || (e.y == 0 && e.x > 0);
+}
+
+// The change of the winding number from c to q, both moved by (ε, ε²), across edge ab, as
+// records::crossing. In doubled units.
+fn m_crossing(a: vec2i, b: vec2i, c: vec2i, q: vec2i) -> i32 {
+    // Segments whose boxes lie a unit or more apart do not cross, moved by (ε, ε²) or not.
+    if (any(max(a, b) < min(c, q)) || any(min(a, b) > max(c, q))) {
+        return 0;
+    }
+    let e = b - a;
+    let sq = m_left(e, a, q);
+    if (m_left(e, a, c) == sq) {
+        return 0;
+    }
+    let d = q - c;
+    let sa = m_orient(d, a - c);
+    let sb = m_orient(d, b - c);
+    let tie = d.y > 0 || (d.y == 0 && d.x < 0);
+    if (select(sa > 0, tie, sa == 0) == select(sb > 0, tie, sb == 0)) {
+        return 0;
+    }
+    return select(-1, 1, sq);
+}
+
+fn m_segment(a: vec2f, b: vec2f, q: vec2f) -> f32 {
+    let u = b - a;
+    let t = clamp(dot(q - a, u) / max(dot(u, u), 1e-9), 0.0, 1.0);
+    return length(q - a - t * u);
+}
+
+// Whether q lies past the cut at word `at`: on its right, within its length, as the overlay's `past`.
+fn m_past(at: u32, q: vec2i) -> bool {
+    let a = m_vertex(at);
+    let u = m_vertex(at + 2u) - a;
+    let v = q - a;
+    let along = dot(vec2f(u), vec2f(v));
+    return m_orient(u, v) < 0 && along >= 0.0 && along <= dot(vec2f(u), vec2f(u));
+}
+
+fn m_surface(block: u32, id: u32) -> u32 {
+    return select(mw(m_label(block, id)) & 0xffu, 0u, id == M_NONE);
+}
+
+// Whether a label is paved: a carriageway, a crossing or a rail bed, which the paint draws.
+fn m_paved(block: u32, id: u32) -> bool {
+    let s = m_surface(block, id);
+    return s == S_CARRIAGEWAY || s == S_CROSSING || s == S_RAILBED;
+}
+
+// The finish code (SURFACES of bins.ts) and the flags of a label's material line, 0 for none.
+fn model_finish(block: u32, id: u32) -> u32 {
+    if (id == M_NONE) {
+        return 0u;
+    }
+    let line = mw(m_label(block, id) + 2u);
+    return select(mw(block + mw(block + 6u) + M_LINE * line + 1u), 0u, line == M_NONE);
+}
+
+// The glob order of a line at q: of its sample nearest q among the bin's segments, as records::way_glob.
+fn m_way_glob(block: u32, line: u32, q: vec2i, segs: u32, n: u32) -> u32 {
+    let samples = block + mw(block + 7u);
+    let first = mw(block + mw(block + 6u) + M_LINE * line + 2u);
+    var best = M_FAR * M_FAR;
+    var glob = M_NONE;
+    for (var k = 0u; k < n; k++) {
+        let s = mw(segs + k);
+        if ((s & 0xffffu) != line) {
+            continue;
+        }
+        for (var e = 0u; e < 2u; e++) {
+            let w = samples + M_SAMPLE * (first + (s >> 16u) + e);
+            let d = vec2f(q - m_vertex(w));
+            if (dot(d, d) < best) {
+                best = dot(d, d);
+                glob = mw(w + 4u);
+            }
+        }
+    }
+    return glob;
+}
+
+fn m_glob(block: u32, ci: u32, q: vec2i, segs: u32, n: u32) -> u32 {
+    let k = m_cand(block, ci);
+    if (mw(k) == M_WAY) {
+        return m_way_glob(block, mw(k + 4u), q, segs, n);
+    }
+    return mw(k + 2u);
+}
+
+// The overlay's decision at q over the candidates that cover it, as records::decide: the least key,
+// then the least glob; a fan's label past a seam; a junction's region over its arms; a carriageway
+// over a rail bed is a crossing.
+// Whether a candidate's label is of line water: its material line has M_WATER.
+fn m_of_water(block: u32, k: u32) -> bool {
+    let line = mw(m_label(block, mw(k + 3u)) + 2u);
+    return line != M_NONE && (m_line_finish(block, line) & M_WATER) != 0u;
+}
+
+fn m_decide(block: u32, cover: array, count: u32, q: vec2i, segs: u32, n: u32) -> u32 {
+    // Where a zone covers q, line water does not count, as records::decide.
+    var zone = false;
+    for (var i = 0u; i < count; i++) {
+        let k = m_cand(block, cover[i]);
+        zone = zone || (mw(k) != M_REGION && mw(k) != M_OUTLINE && m_surface(block, mw(k + 3u)) == M_SURFACE_ZONE);
+    }
+    var best = M_NONE;
+    var rail = M_NONE;
+    for (var i = 0u; i < count; i++) {
+        let k = m_cand(block, cover[i]);
+        if (mw(k) == M_REGION || mw(k) == M_OUTLINE || (zone && m_of_water(block, k))) {
+            continue;
+        }
+        best = min(best, mw(k + 1u));
+        if (rail == M_NONE && m_surface(block, mw(k + 3u)) == S_RAILBED) {
+            rail = cover[i];
+        }
+    }
+    if (best == M_NONE) {
+        return M_NONE;
+    }
+    var win = M_NONE;
+    var win_glob = M_NONE;
+    for (var i = 0u; i < count; i++) {
+        let k = m_cand(block, cover[i]);
+        if (mw(k) == M_REGION || mw(k) == M_OUTLINE || mw(k + 1u) != best || (zone && m_of_water(block, k))) {
+            continue;
+        }
+        let g = m_glob(block, cover[i], q, segs, n);
+        if (win == M_NONE || g < win_glob) {
+            win = cover[i];
+            win_glob = g;
+        }
+    }
+    let k = m_cand(block, win);
+    if (mw(k) == M_FILL) {
+        return mw(k + 3u);
+    }
+    let extras = m_extras(block);
+    var id = mw(k + 3u);
+    var across = false;
+    for (var b = 0u; b < mw(k + 8u); b++) {
+        let e = extras + mw(k + 7u) + 5u * b;
+        if (m_past(e, q)) {
+            id = mw(e + 4u);
+            across = true;
+            break;
+        }
+    }
+    let l = m_label(block, id);
+    // A zone keeps itself in a region of its owner way, as records::decide.
+    if (((mw(l) >> 8u) & 0xffu) == 1u && !across && (mw(l) & 0xffu) != M_SURFACE_ZONE) {
+        let w = mw(l + 1u);
+        var region = M_NONE;
+        var region_key = vec2u(M_NONE);
+        for (var i = 0u; i < count; i++) {
+            let r = m_cand(block, cover[i]);
+            if (mw(r) != M_REGION) {
+                continue;
+            }
+            var mine = 0u;
+            var clear = true;
+            for (var p = 0u; p < mw(r + 10u); p++) {
+                let part = extras + mw(r + 9u) + 11u * p;
+                if (mw(part) != w) {
+                    continue;
+                }
+                mine++;
+                if ((mw(part + 1u) == 1u && m_past(part + 2u, q)) || (mw(part + 6u) == 1u && m_past(part + 7u, q))) {
+                    clear = false;
+                }
+            }
+            let key = vec2u(mw(r + 1u), mw(r + 2u));
+            if (mine > 0u && clear && (key.x < region_key.x || (key.x == region_key.x && key.y < region_key.y))) {
+                region = cover[i];
+                region_key = key;
+            }
+        }
+        if (region != M_NONE) {
+            id = mw(m_cand(block, region) + 3u);
+        }
+    }
+    let l2 = m_label(block, id);
+    if ((mw(l2) & 0xffu) == S_CARRIAGEWAY && rail != M_NONE) {
+        let rail_line = mw(m_label(block, mw(m_cand(block, rail) + 3u)) + 2u);
+        let want = vec4u(S_CROSSING | (mw(l2) & ~0xffu), mw(l2 + 1u), mw(l2 + 2u), rail_line);
+        for (var x = 0u; x < mw(block + 2u); x++) {
+            let lx = m_label(block, x);
+            if (all(vec4u(mw(lx), mw(lx + 1u), mw(lx + 2u), mw(lx + 3u)) == want)) {
+                id = x;
+                break;
+            }
+        }
+    }
+    return id;
+}
+
+// The block of the cell that holds world point p (units of 2^30 per world side), 0 for none.
+fn model_block(p: vec2i) -> u32 {
+    if (mw(0u) != M_TABLE) {
+        return 0u;
+    }
+    let c = (p >> vec2u(14u)) - vec2i(i32(mw(1u)), i32(mw(2u)));
+    let size = vec2i(i32(mw(3u)), i32(mw(4u)));
+    if (any(c < vec2i(0)) || any(c >= size)) {
+        return 0u;
+    }
+    return mw(5u + u32(c.y * size.x + c.x));
+}
+
+// The model at world point p, a texel centre: its label, its distances and the paved label within `reach`
+// metres for the paint.
+fn model_at(p: vec2i, reach: f32) -> ModelPoint {
+    let block = model_block(p);
+    if (block == 0u) {
+        return ModelPoint(0u, vec2i(0), M_NONE, M_NONE, M_FAR, M_FAR, M_FAR, 0.0, 0.0, 0u, M_NONE);
+    }
+    return model_point(block, (p & vec2i(16383)) * 16, reach);
+}
+
+// The model of a block at point q (frame units from the cell's origin).
+fn model_point(block: u32, q: vec2i, reach: f32) -> ModelPoint {
+    var out = ModelPoint(0u, vec2i(0), M_NONE, M_NONE, M_FAR, M_FAR, M_FAR, 0.0, 0.0, 0u, M_NONE);
+    out.block = block;
+    out.q = q;
+    let head = m_bin_head(block, vec2f(q));
+    if (head == 0u) {
+        return out;
+    }
+    let mpu = h_scale(block, vec2f(q));
+    let units = reach / mpu;
+    let qf = vec2f(q);
+    let bin = min(q / M_BIN_UNITS, vec2i(M_BINS - 1));
+    let c = 2 * (bin * M_BIN_UNITS + M_BIN_UNITS / 2) + 1;
+    let q2 = 2 * q;
+    let extras = m_extras(block);
+    var cover: array;
+    var count = 0u;
+    var near: array;
+    var near_d: array;
+    var nears = 0u;
+    var outline = M_NONE;
+    var rail = M_FAR;
+    var at = block + mw(head);
+    for (var item = 0u; item < (mw(head + 1u) >> 16u); item++) {
+        let ci = mw(at) & 0xffffu;
+        var wind = i32((mw(at) >> 16u) & 0xffu) - 128;
+        let k = m_cand(block, ci);
+        let kind = mw(k);
+        var d = M_FAR;
+        var run = at + 2u;
+        for (var r = 0u; r < mw(at + 1u); r++) {
+            let n = mw(run);
+            for (var e = 0u; e + 1u < n; e++) {
+                let a = m_vertex(run + 1u + 2u * e);
+                let b = m_vertex(run + 3u + 2u * e);
+                wind += m_crossing(2 * a, 2 * b, c, q2);
+                d = min(d, m_segment(vec2f(a), vec2f(b), qf));
+            }
+            run += 1u + 2u * n;
+        }
+        at = run;
+        var sd = select(d, -d, wind != 0);
+        if (kind == M_OUTLINE) {
+            outline = k;
+            out.d_paved = sd * mpu;
+            continue;
+        }
+        // A fan or round leaves out the disc of its circle, as `find`.
+        var in_disc = false;
+        for (var j = 0u; j < mw(k + 6u); j++) {
+            let disc = extras + mw(k + 5u) + M_DISC * j;
+            let r = mf(disc + 2u) - length(qf - vec2f(m_vertex(disc)));
+            in_disc = in_disc || r > 0.0;
+            sd = max(sd, r);
+        }
+        if (wind != 0 && !in_disc && count < M_COVER) {
+            cover[count] = ci;
+            count++;
+        }
+        let label = mw(k + 3u);
+        // The core is a way's: line water is no way, so its face and its bank stay out of the mask.
+        let surface = m_surface(block, label);
+        if (kind == M_BAND && surface != M_SURFACE_SLOPE && surface != M_SURFACE_WATER && surface != M_SURFACE_BANK) {
+            out.core = min(out.core, sd * mpu);
+        }
+        // The paved outline holds the carriageways; the paint draws the rail beds too.
+        if (kind != M_BAND && kind != M_REGION && m_surface(block, label) == S_RAILBED) {
+            rail = min(rail, sd * mpu);
+        }
+        // A paved candidate's edge near the point can change what the paint draws there.
+        if ((wind == 0 || in_disc) && sd < units && nears < M_NEAR && kind != M_BAND && kind != M_REGION && m_paved(block, label)) {
+            near[nears] = ci;
+            near_d[nears] = sd;
+            nears++;
+        }
+    }
+    // The outline polygon cuts each round's arc in chords; its disc moves the distance onto the arc, by no
+    // more than the chords' sagitta.
+    if (outline != M_NONE) {
+        let poly = out.d_paved;
+        for (var j = 0u; j < mw(outline + 6u); j++) {
+            let disc = extras + mw(outline + 5u) + M_DISC * j;
+            let r = mf(disc + 2u);
+            let arc = (r - length(qf - vec2f(m_vertex(disc)))) * mpu;
+            out.d_paved = max(out.d_paved, min(arc, poly + (r * M_SAGITTA + 1.0) * mpu));
+        }
+    }
+    out.d_paved = min(out.d_paved, rail);
+    out.core = min(out.core, out.d_paved);
+    let segs = at;
+    let n = mw(head + 1u) & 0xffffu;
+    out.heights = segs + n;
+    out.label = m_decide(block, cover, count, q, segs, n);
+    out.painted = select(M_NONE, out.label, m_paved(block, out.label));
+    // Outside the paved labels, the nearest paved candidate that the point would join across its edge.
+    if (out.painted == M_NONE) {
+        var nearest = M_FAR;
+        for (var i = 0u; i < nears; i++) {
+            if (near_d[i] >= nearest) {
+                continue;
+            }
+            var other = cover;
+            var m = count;
+            if (m < M_COVER) {
+                other[m] = near[i];
+                m++;
+            }
+            let id = m_decide(block, other, m, q, segs, n);
+            if (m_paved(block, id)) {
+                nearest = near_d[i];
+                out.painted = id;
+            }
+        }
+    }
+    // The metres across and along of the painted label's host lines: a junction's through pair (from its record), a
+    // way's own line (from its nearest segment in the bin), a stop arm's own line in its mouth. Their middles run on
+    // through it. A texel takes the look at its centre.
+    out.across = M_FAR;
+    let jr = m_junction(block, out.painted);
+    let mouth = m_mouth(block, jr, qf, mpu);
+    out.mouth = mouth.line;
+    var frame = mouth.place;
+    if (mouth.line == M_NONE && jr != M_NONE) {
+        frame = m_junction_frame(block, jr, qf, m_arms_with(jr, M_ARM_HOST), M_NONE, mpu).place;
+    }
+    if (jr != M_NONE) {
+        out.across = frame.x;
+        out.along = frame.y;
+        out.half = frame.z;
+    } else if (out.painted != M_NONE) {
+        let line = mw(m_label(block, out.painted) + 2u);
+        let samples = block + mw(block + 7u);
+        let lines = block + mw(block + 6u);
+        var best = M_FAR;
+        for (var k = 0u; k < n; k++) {
+            let s = mw(segs + k);
+            if ((s & 0xffffu) != line) {
+                continue;
+            }
+            let wa = samples + M_SAMPLE * (mw(lines + M_LINE * line + 2u) + (s >> 16u));
+            let wb = wa + M_SAMPLE;
+            let a = vec2f(m_vertex(wa));
+            let u = vec2f(m_vertex(wb)) - a;
+            let t = clamp(dot(qf - a, u) / max(dot(u, u), 1e-9), 0.0, 1.0);
+            let d = length(qf - a - t * u);
+            if (d < best) {
+                best = d;
+                out.across = sign(m_cross(u, qf - a)) * d * mpu;
+                out.along = mix(mf(wa + 3u), mf(wb + 3u), t);
+                out.half = mix(mf(wa + 2u), mf(wb + 2u), t) * mpu;
+            }
+        }
+    }
+    return out;
+}
diff --git a/builder/web/src/lib/trailview/terrain/mouth.wgsl b/builder/web/src/lib/trailview/terrain/mouth.wgsl
new file mode 100644
index 0000000000..e57abb7029
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/mouth.wgsl
@@ -0,0 +1,146 @@
+// A stop arm's mouth. In a junction's face with an arm of another look that stops at the host (M_ARM_STOP), the other
+// arms (the route) divide the plane about the node into sectors. In a sector with a stop arm, a point keeps the
+// junction's look on a route arm's stroke or in the mitre where the two route arms that bound the sector meet, and
+// wears the nearest stop arm's look elsewhere. The pieces (plan/mouth-in.wgsl) and the paint (model.wgsl) read the one
+// rule.
+// #include records.wgsl
+
+// The face's edge lies up to this outside a route arm's stroke (snap and chords): a point within it keeps the route.
+const ROUTE_EPS_M: f32 = 0.02;
+// The mitre of two route arms reaches at most this many of their greater half-width from the node.
+const MITRE_LIMIT: f32 = 4.0;
+const M_TAU: f32 = 6.2831853;
+
+// The first sample word of arm k's line.
+fn m_arm_samples(block: u32, jr: u32, k: u32) -> u32 {
+    return block + mw(block + 7u) + M_SAMPLE * mw(block + mw(block + 6u) + M_LINE * (mw(m_arm(jr, k)) & 0xffffu) + 2u);
+}
+
+// The direction of arm k at the node.
+fn m_arm_dir(jr: u32, k: u32) -> vec2f {
+    return unpack2x16snorm(mw(m_arm(jr, k) + 2u));
+}
+
+fn m_wrap(a: f32) -> f32 {
+    return a - M_TAU * floor(a / M_TAU);
+}
+
+// The signed distance in units from q to arm k's stroke: its centre line from the node to its last sample less the
+// half-width, with a flat end at the node. On its side `side` (+1 left, -1 right of its direction, 0 none) it is wider
+// by `widen` at the node, less so along it, and as wide as the line at the last sample.
+fn m_stroke(block: u32, jr: u32, k: u32, q: vec2f, side: f32, widen: f32) -> f32 {
+    let range = mw(m_arm(jr, k) + 1u);
+    let node = range & 0xffffu;
+    let last = range >> 16u;
+    let segments = max(node, last) - min(node, last);
+    let samples = m_arm_samples(block, jr, k);
+    var total = 0.0;
+    for (var m = 0u; m < segments; m++) {
+        let i = select(node - m, node + m, last > node);
+        let j = select(i - 1u, i + 1u, last > node);
+        total += length(vec2f(m_vertex(samples + M_SAMPLE * j) - m_vertex(samples + M_SAMPLE * i)));
+    }
+    var d = M_FAR;
+    var along = 0.0;
+    for (var m = 0u; m < segments; m++) {
+        let i = select(node - m, node + m, last > node);
+        let wa = samples + M_SAMPLE * i;
+        let wb = samples + M_SAMPLE * select(i - 1u, i + 1u, last > node);
+        let a = vec2f(m_vertex(wa));
+        let u = vec2f(m_vertex(wb)) - a;
+        let len = length(u);
+        let t = dot(q - a, u) / max(dot(u, u), 1e-9);
+        let c = clamp(t, 0.0, 1.0);
+        let wider = select(0.0, widen * (1.0 - (along + c * len) / max(total, 1e-6)), side * m_cross(u, q - a) > 0.0);
+        if (m == 0u && t < 0.0) {
+            d = min(d, max(abs(m_cross(u, q - a)) / max(len, 1e-6) - mf(wa + 2u) - wider, -t * len));
+        } else {
+            d = min(d, length(q - a - c * u) - mix(mf(wa + 2u), mf(wb + 2u), c) - wider);
+        }
+        along += len;
+    }
+    return d;
+}
+
+// The stop arm whose look q wears in the face of junction record jr (M_NONE for none), with its frame; line M_NONE
+// where q keeps the junction's look. An arm with no segment bounds no sector.
+fn m_mouth(block: u32, jr: u32, q: vec2f, mpu: f32) -> ArmFrame {
+    let keep = ArmFrame(M_NONE, vec3f(M_FAR, 0.0, 0.0));
+    if (jr == M_NONE) {
+        return keep;
+    }
+    let n = mw(jr + 2u) & 0xffu;
+    let v = q - vec2f(m_vertex(jr));
+    let aq = atan2(v.y, v.x);
+    // The route arms that bound q's sector: the nearest behind q and ahead of it, counter-clockwise.
+    var a = M_NONE;
+    var b = M_NONE;
+    var behind = M_TAU;
+    var ahead = M_TAU;
+    var any_stop = false;
+    for (var k = 0u; k < n; k++) {
+        let range = mw(m_arm(jr, k) + 1u);
+        if ((range & 0xffffu) == (range >> 16u)) {
+            continue;
+        }
+        if ((mw(m_arm(jr, k)) & M_ARM_STOP) != 0u) {
+            any_stop = true;
+            continue;
+        }
+        let u = m_arm_dir(jr, k);
+        let t = atan2(u.y, u.x);
+        if (m_wrap(aq - t) < behind) {
+            behind = m_wrap(aq - t);
+            a = k;
+        }
+        if (m_wrap(t - aq) < ahead) {
+            ahead = m_wrap(t - aq);
+            b = k;
+        }
+    }
+    if (!any_stop || a == M_NONE) {
+        return keep;
+    }
+    // A sector without a stop arm keeps the junction's look: its fillets shape it.
+    let ua = m_arm_dir(jr, a);
+    let ub = m_arm_dir(jr, b);
+    let ta = atan2(ua.y, ua.x);
+    let ha = mf(m_arm_samples(block, jr, a) + M_SAMPLE * (mw(m_arm(jr, a) + 1u) & 0xffffu) + 2u);
+    let hb = mf(m_arm_samples(block, jr, b) + M_SAMPLE * (mw(m_arm(jr, b) + 1u) & 0xffffu) + 2u);
+    // The facing edges at the node: where one arm's edge corner lies past the other's edge line (two arms of
+    // different widths that run on straight), the other widens to it at the node, back to its own width at its seam.
+    let na = vec2f(-ua.y, ua.x);
+    let nb = vec2f(ub.y, -ub.x);
+    let two = select(0.0, 1.0, a != b);
+    let wa = two * max(dot(nb, na) * hb - ha, 0.0);
+    let wb = two * max(dot(na, nb) * ha - hb, 0.0);
+    // The sector's stop arms, a bit each.
+    var stops = 0u;
+    var d = M_FAR;
+    for (var k = 0u; k < n; k++) {
+        let range = mw(m_arm(jr, k) + 1u);
+        if ((range & 0xffffu) == (range >> 16u)) {
+            continue;
+        }
+        if ((mw(m_arm(jr, k)) & M_ARM_STOP) != 0u) {
+            let u = m_arm_dir(jr, k);
+            stops |= select(0u, 1u << min(k, 31u), m_wrap(atan2(u.y, u.x) - ta) < behind + ahead);
+        } else {
+            let side = select(select(0.0, -1.0, k == b), 1.0, k == a) * two;
+            d = min(d, m_stroke(block, jr, k, q, side, select(wb, wa, k == a)));
+        }
+    }
+    if (stops == 0u) {
+        return keep;
+    }
+    // The mitre: each facing edge (widened) goes straight on past the node until it meets the other's, behind both
+    // arms' node lines; one route arm ends flat at the node.
+    if (a != b) {
+        let edges = max(dot(v, na) - ha - wa, dot(v, nb) - hb - wb);
+        d = min(d, max(max(edges, length(v) - MITRE_LIMIT * max(ha, hb)), max(dot(v, ua), dot(v, ub))));
+    }
+    if (d * mpu <= ROUTE_EPS_M) {
+        return keep;
+    }
+    return m_junction_frame(block, jr, q, stops, M_NONE, mpu);
+}
diff --git a/builder/web/src/lib/trailview/terrain/node-bytes.test.ts b/builder/web/src/lib/trailview/terrain/node-bytes.test.ts
new file mode 100644
index 0000000000..f9bd99479e
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/node-bytes.test.ts
@@ -0,0 +1,35 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+import { decodeNode, encodeNode, unpackNode } from './node-bytes';
+import { OWNER, type Node } from './lod';
+
+const body = ({ level, x, y }: Node) => {
+    const bytes = readFileSync(new URL(`../../../../tests/browser/trailview/fixture/features/${level}/${x}/${y}.bin`, import.meta.url));
+    return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
+};
+
+describe('node bytes', () => {
+    it('give back what the stamp worker posts for the coarse nodes and the owner nodes of a tile', async () => {
+        // The stamp worker's global.
+        Object.assign(globalThis, { self: globalThis });
+        const { bakeTile, meshes, stamps } = await import('./stamp-bake');
+        for (const tile of [{ level: 11, x: 1071, y: 721 }, { level: 13, x: 4288, y: 2887 }]) {
+            const baked = await bakeTile(tile, body(tile)), held = baked.filter(([node]) => node.level !== tile.level);
+            if (tile.level === 13) {
+                const mask = baked.find(([node]) => node.level === tile.level)![1];
+                expect(mask[0] | (mask[1] << 8)).toBe(held.reduce((bits, [node]) => bits | (1 << ((node.x & 3) + 4 * (node.y & 3))), 0));
+            }
+            expect(held.length).toBeGreaterThan(1);
+            for (const [node, bytes] of held) {
+                const value = await (node.level === OWNER ? meshes : stamps)(tile, node, body(tile));
+                expect(await unpackNode(bytes)).toStrictEqual(value);
+                expect(encodeNode(await unpackNode(bytes))).toStrictEqual(encodeNode(value));
+            }
+        }
+    }, 30_000);
+
+    it('refuse a value that JSON changes', () => {
+        for (const value of [{ a: NaN }, [-0], { a: Infinity }, { a: new Map() }, { a: new DataView(new ArrayBuffer(4)) }]) expect(() => encodeNode(value)).toThrow();
+        expect(decodeNode(encodeNode({ a: [1.5, null, true], b: new Float64Array([0.1, -2]), c: new ArrayBuffer(3) }))).toStrictEqual({ a: [1.5, null, true], b: new Float64Array([0.1, -2]), c: new ArrayBuffer(3) });
+    });
+});
diff --git a/builder/web/src/lib/trailview/terrain/node-bytes.ts b/builder/web/src/lib/trailview/terrain/node-bytes.ts
new file mode 100644
index 0000000000..6f2aa6ed24
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/node-bytes.ts
@@ -0,0 +1,112 @@
+// The bytes of what the stamp worker posts for a node: a baked node holds them, and the viewer reads them back.
+import { MeshoptDecoder } from 'meshoptimizer/decoder';
+
+/**
+ * The levels whose whole node the stamp layer holds, stamped with the ground plan. It holds the structure
+ * meshes of each owner node that has any, and at zoom 13 the u16 mask of the owner nodes that it holds.
+ */
+export const BAKED = { from: 9, to: 12 };
+
+/** The structure meshes of an owner node without a structure, as the worker posts them. */
+export const EMPTY_MESHES = { far: { structures: null, anchored: null }, near: { structures: null, anchored: null }, anchors: null, points: null };
+
+/**
+ * A mesh `{ vertices, indices, ...rest }` in the layer: `$mesh` and the rest. The distinct vertices `v` in the order
+ * of their first use, `w` of `s` bytes each, meshopt-coded; with `xy` their first two int32 words are int16 from
+ * that point. `r` holds, meshopt-coded, the distinct vertex of each of the `n` vertices (null when all differ),
+ * `i` the `ni` indices.
+ */
+export interface PackedMesh { n: number; w: number; s: number; xy: [number, number] | null; v: Uint8Array; r: Uint8Array | null; ni: number; i: Uint8Array }
+
+/** The typed arrays that the bytes hold, by their tags. */
+const ARRAYS = { Uint8Array, Uint16Array, Uint32Array, Int32Array, Float32Array, Float64Array };
+type Tag = keyof typeof ARRAYS | 'ArrayBuffer';
+/** A binary value in the JSON: its tag, its offset in the binary part and its bytes. */
+interface Slot { $: Tag; at: number; n: number }
+
+const align = (n: number) => (n + 7) & ~7;
+
+/**
+ * The bytes of `value`, plain objects, arrays, booleans, null, finite numbers, strings, ArrayBuffers and
+ * typed arrays: the length of the JSON as a little-endian u32, the JSON, then each binary value at an
+ * offset of 8 bytes. A value that JSON changes (NaN, ±Infinity, -0, a class instance) throws: decodeNode gives back `value` exactly.
+ */
+export function encodeNode(value: unknown): Uint8Array {
+    const parts: Uint8Array[] = [];
+    let end = 0;
+    const json = new TextEncoder().encode(JSON.stringify(value, (_, item: unknown) => {
+        if (typeof item === 'number' && (!Number.isFinite(item) || Object.is(item, -0))) throw new Error(`encodeNode: ${Object.is(item, -0) ? '-0' : item}`);
+        const tag = item instanceof ArrayBuffer ? 'ArrayBuffer' : ArrayBuffer.isView(item) ? item.constructor.name : undefined;
+        if (!tag && item !== null && typeof item === 'object' && !Array.isArray(item) && Object.getPrototypeOf(item) !== Object.prototype) throw new Error(`encodeNode: ${item.constructor.name}`);
+        if (!tag) return item;
+        if (tag !== 'ArrayBuffer' && !Object.hasOwn(ARRAYS, tag)) throw new Error(`encodeNode: ${tag}`);
+        const bytes = item instanceof ArrayBuffer ? new Uint8Array(item) : new Uint8Array((item as ArrayBufferView).buffer, (item as ArrayBufferView).byteOffset, (item as ArrayBufferView).byteLength);
+        const slot: Slot = { $: tag as Tag, at: end, n: bytes.byteLength };
+        parts.push(bytes);
+        end = align(end + bytes.byteLength);
+        return slot;
+    }));
+    const base = align(4 + json.byteLength), out = new Uint8Array(base + end);
+    new DataView(out.buffer).setUint32(0, json.byteLength, true);
+    out.set(json, 4);
+    let at = base;
+    for (const bytes of parts) {
+        out.set(bytes, at);
+        at += align(bytes.byteLength);
+    }
+    return out;
+}
+
+/** The value of bytes from encodeNode. Each binary value has an ArrayBuffer of its own. */
+export function decodeNode(bytes: Uint8Array): unknown {
+    const length = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true), base = bytes.byteOffset + align(4 + length);
+    const json = new TextDecoder().decode(bytes.subarray(4, 4 + length));
+    return JSON.parse(json, (_, item) => {
+        if (item === null || typeof item !== 'object' || typeof item.$ !== 'string') return item;
+        const { $, at, n } = item as Slot, buffer = bytes.buffer.slice(base + at, base + at + n) as ArrayBuffer;
+        return $ === 'ArrayBuffer' ? buffer : new ARRAYS[$](buffer);
+    });
+}
+
+/** A sequence of u32 from meshopt's index sequence code. */
+function sequence(count: number, code: Uint8Array): Uint32Array {
+    const out = new Uint32Array(count);
+    MeshoptDecoder.decodeIndexSequence(new Uint8Array(out.buffer), count, 4, code);
+    return out;
+}
+
+/** The mesh that a PackedMesh holds: the bytes of its vertices and its indices as the worker made them. */
+function unpackMesh({ n, w, s, xy, v, r, ni, i }: PackedMesh): { vertices: ArrayBuffer; indices: Uint32Array } {
+    const distinct = new Uint8Array(w * s);
+    MeshoptDecoder.decodeVertexBuffer(distinct, w, s, v);
+    const stride = xy ? s + 4 : s, wide = xy ? new Uint8Array(w * stride) : distinct;
+    if (xy) {
+        const from = new DataView(distinct.buffer), to = new DataView(wide.buffer);
+        for (let k = 0; k < w; k++) {
+            to.setInt32(k * stride, xy[0] + from.getInt16(k * s, true), true);
+            to.setInt32(k * stride + 4, xy[1] + from.getInt16(k * s + 2, true), true);
+            wide.set(distinct.subarray(k * s + 4, (k + 1) * s), k * stride + 8);
+        }
+    }
+    let vertices = wide;
+    if (r) {
+        const of = sequence(n, r);
+        vertices = new Uint8Array(n * stride);
+        for (let k = 0; k < n; k++) vertices.set(wide.subarray(of[k] * stride, (of[k] + 1) * stride), k * stride);
+    }
+    return { vertices: vertices.buffer, indices: sequence(ni, i) };
+}
+
+/** The value of a baked node: decodeNode, with each packed mesh as the worker posts it. */
+export async function unpackNode(bytes: Uint8Array): Promise {
+    await MeshoptDecoder.ready;
+    const value = decodeNode(bytes);
+    const walk = (item: unknown): unknown => {
+        if (item === null || typeof item !== 'object' || ArrayBuffer.isView(item) || item instanceof ArrayBuffer) return item;
+        if (Array.isArray(item)) return item.map(walk);
+        const { $mesh, ...rest } = item as { $mesh?: PackedMesh };
+        if ($mesh) return { ...unpackMesh($mesh), ...rest };
+        return Object.fromEntries(Object.entries(item).map(([key, next]) => [key, walk(next)]));
+    };
+    return walk(value);
+}
diff --git a/builder/web/src/lib/trailview/terrain/pages.test.ts b/builder/web/src/lib/trailview/terrain/pages.test.ts
index 1b2fc1fbcf..d40edd2fdf 100644
--- a/builder/web/src/lib/trailview/terrain/pages.test.ts
+++ b/builder/web/src/lib/trailview/terrain/pages.test.ts
@@ -4,7 +4,7 @@ import { anchorAt, UNITS } from '../frame/space';
 import { pageData, PAGE } from '../stream/heights';
 import type { TerrainSource } from '../stream/terrain';
 import { cdlod, distances, EYE_M, key, MAP, RANGE, select, size, type Node } from './lod';
-import { ARRIVALS, MODE, Pages, type StampSource, type Work } from './pages';
+import { ARRIVALS, MODE, Pages, touches, type StampSource, type Work } from './pages';
 
 const BOX = [8.37, 46.765, 8.46, 46.83] as const;
 const [west, north] = worldPixel([BOX[0], BOX[3]], UNITS), [east, south] = worldPixel([BOX[2], BOX[1]], UNITS);
@@ -176,46 +176,114 @@ describe('the page pools', () => {
         expect(wanted.some(node => !before.has(key(node)))).toBe(false);
     });
 
-    it('stay at their size, count a shortage in the frame that wants too many pages, and evict none that it wants', async () => {
-        const small = new Pages(source(), { stored: 400, synth: 20 }, BOUNDS, () => {});
-        await settle(small, wanted, 60);
-        const resident = [...small.pages.values()];
-        expect(resident.filter(page => page.kind === 'synth').length).toBeLessThanOrEqual(20);
-        expect(new Set(resident.map(page => page.slot)).size).toBe(resident.length);
-        expect(small.shortage).toBeGreaterThan(0);
-        expect(small.wanted.synth).toBeGreaterThan(20);
+    it('leave out the farthest pages of the finest level first, draw their parents in their place, and change nothing else', async () => {
+        const drawnOf = (pages: Pages) => wanted.filter(node => pages.pages.get(key(node))?.drawn !== undefined).map(key);
+        const levels = (counts: Record) => Array.from({ length: 19 }, (_, level) => counts[level] ?? 0);
+        const cell = ({ level, x, y }: Node) => ({ level: 16, x: x >> (level - 16), y: y >> (level - 16) });
+        const all = new Pages(source(), { stored: 400, synth: 600 }, BOUNDS, () => {});
+        await settle(all, wanted);
+        const synth = all.wanted.synth, full = new Pages(source(), { stored: 400, synth }, BOUNDS, () => {});
+        await settle(full, wanted);
+        expect(full.left).toEqual(levels({}));
+        expect(wanted.every(node => full.pages.get(key(node))?.ready)).toBe(true);
 
+        // One slot short: only the farthest page of level 18 leaves, and its parent draws there.
+        const short = new Pages(source(), { stored: 400, synth: synth - 1 }, BOUNDS, () => {});
+        await settle(short, wanted);
+        expect(short.idle).toBe(true);
+        expect(short.left).toEqual(levels({ 18: 1 }));
+        const gone = drawnOf(full).filter(name => !drawnOf(short).includes(name));
+        expect(gone).toHaveLength(1);
+        expect(drawnOf(short)).toEqual(drawnOf(full).filter(name => name !== gone[0]));
+        const ex = anchor.whole[0] + anchor.part[0], ey = anchor.whole[1] + anchor.part[1], s = size(18), left = wanted.find(node => key(node) === gone[0])!;
+        const centre = (node: Node) => Math.hypot((node.x + 0.5) * s - ex, (node.y + 0.5) * s - ey);
+        expect(left.level).toBe(18);
+        expect(wanted.filter(node => node.level === 18).every(node => centre(node) <= centre(left))).toBe(true);
+        expect(short.drawing(left)?.level).toBe(17);
+        expect(short.fallback(cell(left), 18)).toBe(17);
+        const slots = [...short.pages.values()].flatMap(page => (page.copy === undefined ? [page.slot] : [page.slot, page.copy]));
+        expect(new Set(slots).size).toBe(slots.length);
+
+        // Too few slots for level 16: no page of 17 or 18 draws, the farthest of 16 leave, and the eye's cell falls back past 17.
+        const coarse = wanted.filter(node => node.level <= 16 && node.level > 13).length, tiny = new Pages(source(), { stored: 400, synth: coarse - 1 }, BOUNDS, () => {});
+        await settle(tiny, wanted);
+        expect(tiny.left[16]).toBeGreaterThan(0);
+        expect(wanted.filter(node => node.level >= 17).some(node => tiny.pages.get(key(node))?.drawn !== undefined)).toBe(false);
+        expect(wanted.filter(node => node.level <= 14).every(node => tiny.pages.get(key(node))?.drawn !== undefined)).toBe(true);
+        const eye = { level: 18, x: Math.floor(ex / s), y: Math.floor(ey / s) };
+        expect(tiny.fallback(cell(eye), 18)).toBeLessThan(17);
+    });
+
+    it('keep the same pages in a short pool whatever the order in which the tiles arrive', async () => {
         const all = new Pages(source(), { stored: 400, synth: 600 }, BOUNDS, () => {});
         await settle(all, wanted);
-        const synth = all.wanted.synth, pages = new Pages(source(), { stored: 400, synth }, BOUNDS, () => {});
-        await settle(pages, wanted);
-        // One more synthesized node, a child of a drawn one, before the finer ones in the list.
-        const keys = new Set(wanted.map(key));
-        const extra = wanted.filter(node => node.level === 16).map(node => ({ level: 17, x: 2 * node.x, y: 2 * node.y })).find(node => !keys.has(key(node)))!;
-        const more = [...wanted, extra].sort((a, b) => a.level - b.level);
-        const work = pages.update(more, anchor);
-        expect(pages.shortage).toBe(1);
-        expect(work.syntheses).toEqual([]);
-        expect(wanted.every(node => pages.pages.get(key(node))?.ready)).toBe(true);
+        const late = (delay: (name: string) => number) => {
+            const tiles = source(), fetch = tiles.fetch;
+            tiles.fetch = async (z, x, y) => {
+                await new Promise(resolve => setTimeout(resolve, delay(`${z}/${x}/${y}`)));
+                return fetch(z, x, y);
+            };
+            return tiles;
+        };
+        const hash = (name: string) => [...name].reduce((h, c) => (31 * h + c.charCodeAt(0)) % 7, 0);
+        const kept = async (delay: (name: string) => number) => {
+            const pages = new Pages(late(delay), { stored: 400, synth: all.wanted.synth - 12 }, BOUNDS, () => {});
+            await settle(pages, wanted, 600);
+            expect(pages.idle).toBe(true);
+            return { drawn: wanted.filter(node => pages.pages.get(key(node))?.drawn !== undefined).map(key).sort(), left: [...pages.left] };
+        };
+        const first = await kept(hash), second = await kept(name => 6 - hash(name));
+        expect(first.left[18]).toBeGreaterThanOrEqual(12);
+        expect(second).toEqual(first);
+    });
+
+    it('name in each frame the pages under every box whose read key changes: arrivals, syntheses, evictions and restamps', async () => {
+        const ex = anchor.whole[0] + anchor.part[0], ey = anchor.whole[1] + anchor.part[1], s = size(16), order = (a: Node, b: Node) => a.level - b.level;
+        const half = (east: boolean) => select(cdlod({ anchor, above: 1.6 }, RANGE.least), BOUNDS, ({ level, x }) => (east ? (x + 1) * size(level) > ex : x * size(level) < ex)).wanted.sort(order);
+        const boxes = [-1, 0, 1].flatMap(j => [-1, 0, 1].map((i): [number, number, number, number] => {
+            const x = (Math.floor(ex / s) + i) * s, y = (Math.floor(ey / s) + j) * s;
+            return [x + 100, y + 100, x + s - 100, y + s - 100];
+        }));
+        // A pool that cannot hold both halves: a turn evicts.
+        const pages = new Pages(source(), { stored: 400, synth: 90 }, BOUNDS, () => {});
+        const read = (box: [number, number, number, number]) => `${pages.reads(box, 18, true)};${pages.reads(box, 18, false)}`;
+        let keys = boxes.map(read), changes = 0;
+        for (let i = 0; i < 240; i++) {
+            if (i === 150) pages.restamp({ level: 16, x: Math.floor(ex / s), y: Math.floor(ey / s) });
+            const work = pages.update(half(Math.floor(i / 60) % 2 === 0), anchor);
+            const now = boxes.map(read);
+            boxes.forEach((box, k) => {
+                if (now[k] === keys[k]) return;
+                changes++;
+                expect(work.touched.some(node => touches(node, box))).toBe(true);
+            });
+            keys = now;
+            await new Promise(resolve => setTimeout(resolve));
+        }
+        expect(changes).toBeGreaterThan(boxes.length);
+        // A frame that changes nothing names nothing.
+        await settle(pages, half(false));
+        expect(pages.update(half(false), anchor).touched).toEqual([]);
     });
 
     it('keep the stored pages that a synthesis reads when a page arrives in the same frame', async () => {
         const [w, n] = worldPixel([7.6, 47.25], UNITS), [e, s] = worldPixel([8.95, 46.46], UNITS);
         const at = (level: number) => ({ level, x: Math.floor((anchor.whole[0] + anchor.part[0]) / size(level)), y: Math.floor((anchor.whole[1] + anchor.part[1]) / size(level)) });
         const stored = at(13), around = [-1, 0, 1].flatMap(dy => [-1, 0, 1].map(dx => ({ level: 13, x: stored.x + dx, y: stored.y + dy })));
-        const pages = new Pages(source(), { stored: 9, synth: 10 }, [w, n, e, s], () => {});
-        // The pool holds the stored ancestor of the synthesis and its eight neighbours; zoom 13 is known absent.
+        // The pool holds the stored ancestor of the synthesis and its eight neighbours, and the page that fills the hole
+        // until they come; zoom 13 is known absent.
+        const pages = new Pages(source(), { stored: 10, synth: 10 }, [w, n, e, s], () => {});
         await settle(pages, [...around, at(14)]);
         expect(around.every(node => pages.pages.get(key(node))?.ready)).toBe(true);
         // A stored page far away is decoded and waits to arrive.
         const far = { level: 13, x: stored.x + 6, y: stored.y };
         pages.update([far], anchor);
         await new Promise(resolve => setTimeout(resolve));
+        // The arrival takes the slot of the page that filled the hole, not one that the synthesis reads.
         const work = pages.update([at(15), far], anchor);
         expect(work.syntheses.map(({ page, stored }) => [key(page.node), stored])).toEqual([[key(at(15)), 13]]);
-        expect(around.every(node => pages.pages.get(key(node))?.ready)).toBe(true);
-        // The arrival and the page that fills the hole at `far` find no slot.
-        expect(pages.shortage).toBe(2);
+        expect([...around, far].every(node => pages.pages.get(key(node))?.ready)).toBe(true);
+        expect(pages.left.every(count => count === 0)).toBe(true);
     });
 
     it('keep the inputs of a synthesis that arrive together in a pool that just holds them', async () => {
diff --git a/builder/web/src/lib/trailview/terrain/pages.ts b/builder/web/src/lib/trailview/terrain/pages.ts
index fc3dd9f73b..6b421c418f 100644
--- a/builder/web/src/lib/trailview/terrain/pages.ts
+++ b/builder/web/src/lib/trailview/terrain/pages.ts
@@ -2,8 +2,8 @@ import { EARTH_RADIUS } from '../frame/frame';
 import type { Anchor } from '../frame/space';
 import { PAGE, type PageData } from '../stream/heights';
 import { TILE_ZOOM, type TerrainSource, stopped } from '../stream/terrain';
-import { NEAR, type NodeStamps } from './bins';
-import { COARSEST, distances, FINEST, key, MAP, size, type Node } from './lod';
+import { NEAR, STAMP_WORDS, type NodeStamps } from './bins';
+import { CELL_LEVEL, COARSEST, distances, FINEST, key, MAP, size, type Node } from './lod';
 
 /** Tile requests in flight at most. */
 const LOADS = 6;
@@ -11,17 +11,29 @@ const LOADS = 6;
 const FILL = 7;
 /** Pages that arrive or are synthesized per frame at most. */
 export const ARRIVALS = 16;
-/** Words of stamp data per frame at most: the nodes of the frame's stamps. */
-export const STAMP_WORDS = 2 ** 20;
 /** Encoded tile bodies kept, so a new device gets the pages again without a request. */
 const BODIES = 64 * 2 ** 20;
 /** The modes of a stamp job, as in stamp.wgsl. */
 export const MODE = { HEIGHTS: 1, MASK: 4 } as const;
+/**
+ * While the camera moves, a page that holds a slot ranks as if it were this share as far: another takes its room only
+ * when it is nearer by the rest, so a page at the edge of a full pool does not leave and come back as the eye moves. A
+ * still view ranks by distance alone.
+ */
+const STAY = 0.8;
 /**
  * Half a texel of a level at the equator, in metres: a summit inside a texel with slopes of 1 rises
  * at most this far above the texel's mean, so the finer pages below a page keep to its range widened by it.
  */
 const summit = (level: number) => Math.PI * EARTH_RADIUS / 2 ** level / PAGE;
+/** Units about a point within which a bicubic reads the pages of a level: two texels. */
+const reach = (level: number) => 2 * size(level) / PAGE;
+
+/** Whether a node's page lies within a bicubic's reach of a box, where `Pages.reads` walks: a change of it can change the key. */
+export function touches({ level, x, y }: Node, box: [number, number, number, number]): boolean {
+    const s = size(level), r = reach(level);
+    return x * s <= box[2] + r && (x + 1) * s > box[0] - r && y * s <= box[3] + r && (y + 1) * s > box[1] - r;
+}
 
 export type Kind = 'stored' | 'synth';
 
@@ -42,6 +54,8 @@ export interface Page {
     drawn?: number;
     copy?: number;
     mask?: number;
+    /** The write of its drawn heights, counted over all pages: a reader of them (`reads`) reads again when it changes. */
+    made?: number;
 }
 
 /** What stamps a node: the binned features, while they are known. `get` asks for them, `known` does not. */
@@ -73,6 +87,8 @@ export interface Work {
     stamps: Stamp[];
     /** The pages that draw new heights. */
     fresh: Page[];
+    /** The nodes of the pages whose heights in the LOD map changed since the last frame: a reader there (`reads`) reads again. */
+    touched: Node[];
     /** The LOD map: MAP × MAP entries per level from 0 to FINEST, when it changed. */
     map?: Uint32Array;
     /** Per layer, the mask layer + 1 (0 for none), when they changed. */
@@ -90,26 +106,32 @@ interface Tile {
     empty?: boolean[];
 }
 
+/** A page that a frame needs, as `fit` ranks it: its slots, the inputs of its synthesis, and whether the frame wants it to draw. */
+interface Need { node: Node; name: string; kind: Kind; slots: number; inputs: string[]; wanted: boolean; far: number }
+
 /**
  * The page pools and what fills them. Stored pages come from the stored tiles, synthesized pages from
  * their deepest stored ancestor. The pools have a fixed size: the page that the frames wanted longest
- * ago leaves first, and a frame that wants more pages than a pool holds counts a shortage. The mask
- * layers go to the nearest near pages with features.
+ * ago leaves first. A frame that needs more pages than a pool holds leaves out the finest and farthest
+ * (`fit`). The mask layers go to the nearest near pages with features.
  */
 export class Pages {
     requests = 0;
     bytes = 0;
     failed = 0;
-    /** Wanted pages that found no free slot in the last frame. */
-    shortage = 0;
-    /** Wanted pages that are not ready yet in the last frame. */
+    /** Per level, the pages that the last frame needed and left out: they found no room in their pool. */
+    readonly left: number[] = Array(FINEST + 1).fill(0);
+    /** The wanted pages that the last frame left out, by name, and `fallback` by `level:cell`. */
+    private readonly leftOut = new Map();
+    private readonly fallbacks = new Map();
+    /** Wanted pages that fit and do not draw yet in the last frame. */
     missing = 0;
     /** Of them, the pages of `near` and of `eye` in the last update. */
     nearMissing = 0;
     eyeMissing = 0;
     private near = new Set();
     private eye = new Set();
-    /** Slots of each pool that the last frame's pages hold: a stamped copy holds a second stored one. */
+    /** Slots of each pool that the last frame's wanted pages need, those left out too: a stamped copy needs a second stored one. */
     wanted: Record = { stored: 0, synth: 0 };
     readonly pages = new Map();
     private readonly tiles = new Map();
@@ -137,6 +159,9 @@ export class Pages {
     /** The masks changed, or the reach of the paint, while the LOD map did not. */
     private masksDirty = true;
     private origins: [number, number][] = [];
+    private writes = 0;
+    /** The nodes of the pages whose heights in the LOD map changed since the last update returned: it returns them. */
+    private touched: Node[] = [];
 
     constructor(private readonly source: TerrainSource, readonly capacity: Record, private readonly bounds: [number, number, number, number], private readonly changed: () => void,
         private readonly stamps: StampSource = NO_STAMPS, readonly maskCapacity = 0) {
@@ -163,6 +188,28 @@ export class Pages {
         return out;
     }
 
+    /**
+     * What a reader of the heights in a box of world units gets from level `top` down, as a key: per
+     * level the pages within a bicubic's reach of the box, by their raw stored heights (`stored`) or their
+     * drawn ones, down to the first level whose pages there all know every height. The key changes when
+     * what the reader reads may change.
+     */
+    reads(box: [number, number, number, number], top: number, stored: boolean): string {
+        const out: (string | number)[] = [];
+        for (let level = top; level >= COARSEST; level--) {
+            const s = size(level), r = reach(level);
+            let whole = true;
+            for (let y = Math.floor((box[1] - r) / s); y <= Math.floor((box[3] + r) / s); y++) for (let x = Math.floor((box[0] - r) / s); x <= Math.floor((box[2] + r) / s); x++) {
+                const page = this.pages.get(`${level}/${x}/${y}`);
+                const has = !!page?.ready && (stored ? page.kind === 'stored' : page.drawn !== undefined);
+                out.push(has ? (stored ? 1 : page!.made!) : 0);
+                whole &&= has && page!.complete;
+            }
+            if (whole) break;
+        }
+        return out.join();
+    }
+
     /**
      * Whether a page that draws holds a node, at its level or a coarser one. If none does, the node draws
      * nothing: each bilinear quad that it reads has a texel in its own page of that level.
@@ -178,18 +225,16 @@ export class Pages {
     }
 
     /**
-     * Takes the pages that a frame wants, coarse and near first, and returns its GPU work. `near` and
+     * Takes the pages that a frame wants and that fit in the pools (`fit`), and returns its GPU work. `near` and
      * `eye` name the wanted pages that `nearMissing` and `eyeMissing` count; those of the eye field ask
-     * for their features and synthesize first.
+     * for their features and synthesize first. `moving` tells that the camera moved since the last frame.
      */
-    update(wanted: Node[], anchor: Anchor, near = new Set(), eye = new Set()): Work {
+    update(wanted: Node[], anchor: Anchor, near = new Set(), eye = new Set(), moving = false): Work {
         this.frame++;
-        this.near = near;
-        this.eye = eye;
-        this.shortage = 0;
+        this.near = new Set(near);
+        this.eye = new Set(eye);
         this.missing = this.nearMissing = this.eyeMissing = 0;
-        this.wanted = { stored: 0, synth: 0 };
-        const work: Work = { uploads: [], syntheses: [], stamps: [], fresh: [], origins: this.window(anchor) };
+        const work: Work = { uploads: [], syntheses: [], stamps: [], fresh: [], touched: [], origins: this.window(anchor) };
         // A node that nothing draws yet also wants its page of level FILL, which is a hole until it comes.
         const fills = new Map();
         for (const node of wanted) {
@@ -197,7 +242,8 @@ export class Pages {
             const up = node.level - FILL, fill = { level: FILL, x: node.x >> up, y: node.y >> up };
             fills.set(key(fill), fill);
         }
-        wanted = [...fills.values(), ...wanted.filter(node => eye.has(key(node))), ...wanted.filter(node => !eye.has(key(node)))];
+        const { fits, added } = this.fit([...fills.values(), ...wanted], anchor, moving ? STAY : 1);
+        wanted = [...fills.values(), ...added, ...wanted.filter(node => eye.has(key(node))), ...wanted.filter(node => !eye.has(key(node)))].filter(node => fits.has(key(node)));
         // Every wanted page is used before the first allocation, so none leaves for a later one of this frame.
         for (const node of wanted) {
             const page = this.pages.get(key(node));
@@ -212,11 +258,13 @@ export class Pages {
             const { node, data } = this.arrivals.shift()!;
             const tile = `${node.level - 1}/${node.x >> 1}/${node.y >> 1}`, heights: [number, number] = [data.min - summit(node.level), data.max + summit(node.level)];
             this.queued.set(tile, this.queued.get(tile)! - 1);
+            if (this.leftOut.has(key(node))) continue;
             const page = this.pages.get(key(node)) ?? this.allocate(node, 'stored', heights, this.needs.has(key(node)));
             if (!page || page.ready) continue;
             page.range = heights;
             page.complete = data.complete;
             page.ready = true;
+            this.touched.push(page.node);
             work.uploads.push({ page, data });
         }
         // A stored page draws once its stamps are on: as it is, or as a stamped copy.
@@ -226,12 +274,29 @@ export class Pages {
         for (const page of this.pages.values()) {
             if (page.kind === 'stored' && page.ready && page.drawn === undefined && page.used === this.frame && this.resolve(page, work)) fresh.push(page);
         }
+        for (const page of fresh) {
+            page.made = ++this.writes;
+            this.touched.push(page.node);
+        }
+        // A page left out holds no slot that a page that fits needs (`slot` evicts it), and draws until the page that stands in
+        // its place does: the finest of its ancestors that fits. Then its slot is free.
+        // Per level finer than a cell, by cell: the coarsest level that stands in place of a page left out.
+        this.fallbacks.clear();
+        for (const [name, node] of this.leftOut) {
+            const stand = this.standIn(node, fits), page = this.pages.get(name);
+            if (page && (!stand || this.pages.get(key(stand))?.drawn !== undefined)) this.release(page);
+            if (node.level <= CELL_LEVEL) continue;
+            const level = stand?.level ?? COARSEST, cell = `${node.level}:${key(cellOf(node))}`;
+            this.fallbacks.set(cell, Math.min(level, this.fallbacks.get(cell) ?? level));
+        }
         // The masks of drawn pages wait for the copies, which a stored page needs to draw at all.
         this.lateMasks(holders, work);
         if (fresh.length) this.dirty = true;
         if (this.dirty) work.map = this.map();
         if (this.dirty || this.masksDirty) work.masks = this.masks();
         this.dirty = this.masksDirty = false;
+        work.touched = this.touched;
+        this.touched = [];
         return work;
     }
 
@@ -247,12 +312,30 @@ export class Pages {
         this.dirty = true;
     }
 
+    /**
+     * Stamps the pages of `level` or finer inside node `area` again: a synthesized page leaves, a stored
+     * page loses its stamped copy and its mask. Until then the coarser page draws.
+     */
+    restamp(area: Node): void {
+        for (const [name, page] of this.pages) {
+            const { level, x, y } = page.node, up = level - area.level;
+            if (up < 0 || x >> up !== area.x || y >> up !== area.y || page.drawn === undefined) continue;
+            if (page.mask !== undefined) this.maskFree.push(page.mask);
+            if (page.copy !== undefined) this.free.stored.push(page.copy);
+            page.mask = page.copy = page.drawn = undefined;
+            if (page.kind === 'synth') {
+                this.pages.delete(name);
+                this.free.synth.push(page.slot);
+            }
+            this.dirty = this.masksDirty = true;
+            this.touched.push(page.node);
+        }
+    }
+
     private want(node: Node, work: Work, holders: Map): void {
         const page = this.pages.get(key(node));
         if (page) {
             page.used = this.frame;
-            this.wanted[page.kind]++;
-            if (page.copy !== undefined) this.wanted.stored++;
             if (page.drawn === undefined) {
                 this.miss(node);
                 // A ready stored page asks for its features in the frame's order: `resolve` puts them on.
@@ -262,7 +345,6 @@ export class Pages {
         }
         const stored = this.stored(node);
         if (stored !== 'no') {
-            this.wanted.stored++;
             this.miss(node);
             this.load(node);
             return;
@@ -270,7 +352,6 @@ export class Pages {
         const ancestor = this.storedAncestor(node);
         // No stored tile above the node knows a height: nothing draws there.
         if (!ancestor) return;
-        this.wanted.synth++;
         this.miss(node);
         if (ancestor === 'wait') return;
         // The features load while the inputs do.
@@ -316,11 +397,16 @@ export class Pages {
         return new Map(near.slice(0, this.maskCapacity).map(({ node }) => [key(node), node]));
     }
 
-    /** A mask-only job for each holder without a mask, nearest first, as the frame has room: a page synthesized while the pool was full gets its mask later. */
+    /**
+     * A mask-only job for each holder without a mask, nearest first, as the frame has room: a page synthesized
+     * while the pool was full gets its mask later. A page synthesized in this frame gets it in the next: its
+     * heights are in `out` until the quantize.
+     */
     private lateMasks(holders: Map, work: Work): void {
+        const synthesized = new Set(work.syntheses.map(({ page }) => page));
         for (const node of holders.values()) {
             const page = this.pages.get(key(node)), data = this.stamps.get(node)?.data;
-            if (!page || !data || page.kind !== 'synth' || page.drawn === undefined || page.mask !== undefined) continue;
+            if (!page || !data || page.kind !== 'synth' || page.drawn === undefined || page.mask !== undefined || synthesized.has(page)) continue;
             if (this.busy(work, data.length) || !this.mask(page, holders, work)) return;
             work.stamps.push({ page, out: 0, target: page.slot, data, mode: MODE.MASK });
         }
@@ -346,7 +432,7 @@ export class Pages {
         if (this.busy(work, stamps.data.length)) return false;
         const copy = this.slot('stored');
         if (copy === undefined) {
-            this.shortage++;
+            this.leave(page.node);
             return false;
         }
         page.copy = page.drawn = copy;
@@ -388,15 +474,20 @@ export class Pages {
 
     /** The deepest ancestor with a stored page once it is ready, `wait` before, and none where no tile above knows a height. */
     private storedAncestor(node: Node): Node | 'wait' | undefined {
+        const parent = this.deepest(node);
+        if (!parent) return undefined;
+        const page = this.pages.get(key(parent));
+        if (page) page.used = this.frame;
+        if (this.stored(parent) === 'yes' && page?.ready) return parent;
+        this.load(parent);
+        return 'wait';
+    }
+
+    /** The deepest ancestor whose tile may hold a stored page, and none where no tile above knows a height. */
+    private deepest(node: Node): Node | undefined {
         for (let { level, x, y } = node; level > COARSEST;) {
             level--; x >>= 1; y >>= 1;
-            const parent = { level, x, y }, state = this.stored(parent);
-            if (state === 'no') continue;
-            const page = this.pages.get(key(parent));
-            if (page) page.used = this.frame;
-            if (state === 'yes' && page?.ready) return parent;
-            this.load(parent);
-            return 'wait';
+            if (this.stored({ level, x, y }) !== 'no') return { level, x, y };
         }
         return undefined;
     }
@@ -520,12 +611,12 @@ export class Pages {
 
     /**
      * A slot for a page: a free one, or the one that the frames wanted longest ago. None when this
-     * frame wants them all: a shortage when the frame needs the new page too.
+     * frame wants them all: a page that the frame needs is then left out.
      */
     private allocate(node: Node, kind: Kind, heights: [number, number], needed: boolean): Page | undefined {
-        const slot = this.slot(kind);
+        const slot = this.slot(kind, node);
         if (slot === undefined) {
-            if (needed) this.shortage++;
+            if (needed) this.leave(node);
             return undefined;
         }
         // A synthesized page reads its stored ancestors only, and `heights` holds all that they draw.
@@ -535,18 +626,179 @@ export class Pages {
         return page;
     }
 
-    /** A free layer of a pool, or that of the page that the frames wanted longest ago, which leaves with its copy and mask. */
-    private slot(kind: Kind): number | undefined {
+    /**
+     * A free layer of a pool, or that of the page that the frames wanted longest ago, which leaves with its copy and mask. A page
+     * left out that still draws, until the page in its place does, leaves last: first for a page `node` above it, which draws in
+     * the frame of its slot.
+     */
+    private slot(kind: Kind, node?: Node): number | undefined {
         const free = this.free[kind].pop();
         if (free !== undefined) return free;
-        let oldest: Page | undefined;
-        for (const page of this.pages.values()) if (page.kind === kind && page.used < this.frame && (!oldest || page.used < oldest.used)) oldest = page;
+        let oldest: Page | undefined, last = Infinity;
+        for (const page of this.pages.values()) {
+            if (page.kind !== kind || page.used >= this.frame) continue;
+            const up = node ? page.node.level - node.level : 0;
+            const rank = !this.leftOut.has(key(page.node)) ? 0 : up > 0 && page.node.x >> up === node!.x && page.node.y >> up === node!.y ? 1 : 2;
+            if (rank < last || (rank === last && page.used < oldest!.used)) [oldest, last] = [page, rank];
+        }
         if (!oldest) return undefined;
-        this.pages.delete(key(oldest.node));
-        if (oldest.ready) this.dirty = true;
-        if (oldest.copy !== undefined) this.free.stored.push(oldest.copy);
-        if (oldest.mask !== undefined) this.maskFree.push(oldest.mask);
-        return oldest.slot;
+        this.release(oldest);
+        return this.free[kind].pop();
+    }
+
+    /** The page that stands in place of a node left out: the finest of its ancestors that fits. */
+    private standIn(node: Node, fits: Set): Node | undefined {
+        for (let { level, x, y } = node; level > COARSEST;) {
+            level--; x >>= 1; y >>= 1;
+            if (fits.has(`${level}/${x}/${y}`)) return { level, x, y };
+        }
+        return undefined;
+    }
+
+    /** A page leaves its pool, with its copy and its mask. */
+    private release(page: Page): void {
+        this.pages.delete(key(page.node));
+        if (page.ready) {
+            this.dirty = true;
+            this.touched.push(page.node);
+        }
+        if (page.copy !== undefined) this.free.stored.push(page.copy);
+        if (page.mask !== undefined) this.maskFree.push(page.mask);
+        this.free[page.kind].push(page.slot);
+    }
+
+    /**
+     * The pages that fit in the pools, and the pages that join the wanted ones to draw in place of those left out. Ranks
+     * the pages that a frame needs: the wanted ones, and the inputs of each synthesis, the stored ancestor and its eight
+     * neighbours. Coarse levels go first, in a level the nearest first, by the page's centre; while the camera moves, a
+     * page that holds a slot ranks as if `stay` times as far. Each pool takes the pages in that order until the first one
+     * that finds no room: it and every later page of that pool are left out (`cut`). The parent of a wanted page that is
+     * left out draws in its place, so it joins the wanted pages, and the pools take them again until no page joins. So a
+     * frame leaves out the finest and farthest pages, with a page one level coarser in their place where that fits, and a
+     * still view keeps the same pages, whatever the order of arrival. Sets `left` and `wanted`.
+     */
+    private fit(wanted: Node[], anchor: Anchor, stay: number): { fits: Set; added: Node[] } {
+        const { needs, need } = this.needsOf(anchor, stay);
+        for (const node of wanted) need(node, true);
+        const added: Node[] = [];
+        let fits: Set;
+        for (;;) {
+            fits = this.cut([...needs.values()]);
+            const before = added.length;
+            for (const [name, { level, x, y }] of this.leftOut) {
+                const parent = { level: level - 1, x: x >> 1, y: y >> 1 };
+                if (level <= COARSEST || needs.get(key(parent))?.wanted) continue;
+                need(parent, true);
+                if (!needs.get(key(parent))?.wanted) continue;
+                added.push(parent);
+                // It counts for the near field and the eye field as the page that it stands for.
+                if (this.near.has(name)) this.near.add(key(parent));
+                if (this.eye.has(name)) this.eye.add(key(parent));
+            }
+            if (added.length === before) break;
+        }
+        return { fits, added: added.filter(node => fits.has(key(node))) };
+    }
+
+    /**
+     * The slots per pool that the pages of levels coarser than `below` need for the wanted nodes `wanted`, their inputs too, as
+     * `fit` counts them: how much a frame of another quality would need.
+     */
+    demand(wanted: Node[], anchor: Anchor, below: number): Record {
+        const { needs, need } = this.needsOf(anchor, 1), out = { stored: 0, synth: 0 };
+        for (const node of wanted) need(node, true);
+        for (const { node, kind, slots } of needs.values()) if (node.level < below) out[kind] += slots;
+        return out;
+    }
+
+    /** The pages that wanted nodes need, as `need` adds them: their pools, slots, inputs and distances, as `fit` ranks them. */
+    private needsOf(anchor: Anchor, stay: number): { needs: Map; need: (node: Node, wanted: boolean) => void } {
+        const ex = anchor.whole[0] + anchor.part[0], ey = anchor.whole[1] + anchor.part[1];
+        const needs = new Map(), inputsOf = new Map();
+        const need = (node: Node, wanted: boolean): void => {
+            const name = key(node), had = needs.get(name);
+            if (had) {
+                had.wanted ||= wanted;
+                return;
+            }
+            const page = this.pages.get(name), s = size(node.level);
+            const far = Math.hypot((node.x + 0.5) * s - ex, (node.y + 0.5) * s - ey) * anchor.unit * (page ? stay : 1);
+            const entry: Need = { node, name, kind: 'stored', slots: 1, inputs: [], wanted, far };
+            if (page?.kind === 'synth' || (!page && this.stored(node) === 'no')) {
+                // A synthesized page that is not made yet needs its inputs.
+                const ancestor = page ? undefined : this.deepest(node);
+                if (!page && !ancestor) return;
+                entry.kind = 'synth';
+                if (ancestor) {
+                    const at = key(ancestor);
+                    if (!inputsOf.has(at)) {
+                        const inputs = this.around(ancestor).filter(near => this.stored(near) !== 'no');
+                        inputsOf.set(at, inputs.map(key));
+                        for (const near of inputs) need(near, false);
+                    }
+                    entry.inputs = inputsOf.get(at)!;
+                }
+            } else {
+                const stamps = this.stamps.known(node);
+                if (page?.copy !== undefined || (page?.drawn === undefined && stamps?.data && stamps.heights)) entry.slots = 2;
+            }
+            needs.set(name, entry);
+        };
+        return { needs, need };
+    }
+
+    /**
+     * Each pool takes its pages in rank order until the first that finds no room. The synthesized pool goes first, so that
+     * only the inputs of the syntheses that fit count in the stored pool; a synthesis whose input finds no room is left out
+     * then. Sets `left` and `wanted`.
+     */
+    private cut(needs: Need[]): Set {
+        const used = { stored: 0, synth: 0 }, fits = new Set();
+        this.wanted = { stored: 0, synth: 0 };
+        for (const entry of needs) {
+            used[entry.kind] += entry.slots;
+            if (entry.wanted) this.wanted[entry.kind] += entry.slots;
+        }
+        // The order matters only where a pool runs short.
+        if (used.stored > this.capacity.stored || used.synth > this.capacity.synth) needs.sort((a, b) => a.node.level - b.node.level || a.far - b.far || a.node.x - b.node.x || a.node.y - b.node.y);
+        this.left.fill(0);
+        this.leftOut.clear();
+        const take = (kind: Kind, entries: Need[]) => {
+            let room = this.capacity[kind];
+            for (const entry of entries) {
+                if (entry.slots > room) room = -1;
+                if (room < 0) this.leave(entry.node, entry.wanted);
+                else {
+                    room -= entry.slots;
+                    fits.add(entry.name);
+                }
+            }
+        };
+        const syntheses = needs.filter(entry => entry.kind === 'synth');
+        take('synth', syntheses);
+        const inputs = new Set(syntheses.flatMap(entry => (fits.has(entry.name) ? entry.inputs : [])));
+        take('stored', needs.filter(entry => entry.kind === 'stored' && (entry.wanted || inputs.has(entry.name))));
+        for (const entry of syntheses) {
+            if (!fits.has(entry.name) || entry.inputs.every(name => fits.has(name))) continue;
+            fits.delete(entry.name);
+            this.leave(entry.node, entry.wanted);
+        }
+        return fits;
+    }
+
+    /** Counts a page that the frame needs and leaves out; a wanted one never draws once a page draws in its place. */
+    private leave(node: Node, wanted = true): void {
+        this.left[node.level]++;
+        if (wanted) this.leftOut.set(key(node), node);
+    }
+
+    /**
+     * The coarsest level that stands in place of a page of `level` that the last frame left out in `cell`, a node of CELL_LEVEL;
+     * `level` where it left out none. It is the level that draws there once the pages that fit are in: while the page in its
+     * place loads, the page left out draws on, unless an allocation needed its slot first, as in a load.
+     */
+    fallback(cell: Node, level: number): number {
+        return this.fallbacks.get(`${level}:${key(cell)}`) ?? level;
     }
 
     /** The LOD map window of each level: MAP × MAP nodes about the eye. */
@@ -584,6 +836,9 @@ export class Pages {
 /** A reach that no view meets: no shader takes an infinity. */
 export const NO_LIMIT = 1e9;
 
+/** The node of CELL_LEVEL that holds a finer node. */
+const cellOf = ({ level, x, y }: Node): Node => ({ level: CELL_LEVEL, x: x >> (level - CELL_LEVEL), y: y >> (level - CELL_LEVEL) });
+
 /** The bands of `priority` above the error over distance, which is at most size(COARSEST) over a metre. */
 const NEAR_FIELD = 2 ** 30, HOLE = 2 ** 40;
 
diff --git a/builder/web/src/lib/trailview/terrain/pages.wgsl b/builder/web/src/lib/trailview/terrain/pages.wgsl
index 3980d59d14..5ae12e6b84 100644
--- a/builder/web/src/lib/trailview/terrain/pages.wgsl
+++ b/builder/web/src/lib/trailview/terrain/pages.wgsl
@@ -21,36 +21,6 @@ struct Job {
 // The float32 bits of an unknown height in `out`, before its 16-bit codes.
 const UNKNOWN32: u32 = 0xffffffffu;
 
-// Catmull-Rom weights of the four texels about a part t.
-fn spline(t: f32) -> vec4f {
-    return 0.5 * vec4f(-t + 2.0 * t * t - t * t * t, 2.0 - 5.0 * t * t + 3.0 * t * t * t, t + 4.0 * t * t - 3.0 * t * t * t, -t * t + t * t * t);
-}
-
-// The bicubic height of the finest stored level up to `top` that knows all 16 texels about a point.
-fn stored_base(u: vec2i, top: u32) -> f32 {
-    for (var level = top; level >= COARSEST; level--) {
-        let t = texel_of_units(u, level);
-        let wx = spline(t.part.x);
-        let wy = spline(t.part.y);
-        var sum = 0.0;
-        var complete = true;
-        for (var j = 0; j < 4 && complete; j++) {
-            for (var i = 0; i < 4; i++) {
-                let h = texel_height(level, t.whole + vec2i(i - 1, j - 1), true);
-                if (!known(h)) {
-                    complete = false;
-                    break;
-                }
-                sum += h * wx[i] * wy[j];
-            }
-        }
-        if (complete) {
-            return sum;
-        }
-    }
-    return NONE;
-}
-
 // The ordered bits of a height, so that unsigned atomics take the least and the greatest.
 fn ordered(h: f32) -> u32 {
     let b = bitcast(h);
diff --git a/builder/web/src/lib/trailview/terrain/records.wgsl b/builder/web/src/lib/trailview/terrain/records.wgsl
new file mode 100644
index 0000000000..e4f454722d
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/records.wgsl
@@ -0,0 +1,189 @@
+// The layout of a cell's records block (the crate's `faces::records`) and the reads of its words. A
+// block is a word offset into model_words; its offsets are relative to it.
+// #include model-words.wgsl
+
+const MODEL_ROW: u32 = 4096u;
+const M_BINS: i32 = 64;
+const M_BIN: f32 = 4096.0;
+const M_CELL: f32 = 262144.0;
+const M_CAND: u32 = 11u;
+const M_LABEL: u32 = 12u;
+const M_LINE: u32 = 18u;
+const M_SAMPLE: u32 = 12u;
+const M_DISC: u32 = 5u;
+const M_BLEND: u32 = 6u;
+const M_HEADER: u32 = 4u;
+const M_NONE: u32 = 0xffffffffu;
+const M_FAR: f32 = 1e9;
+// A junction record, as records::JR: node x, y; the arm count and the graph's junction; then M_JR_ARM words per arm:
+// its line with its flags (a host, a stop arm), its node and last sample, its direction at the node.
+const M_JUNCTION: u32 = 2u;
+const M_JR: u32 = 3u;
+const M_JR_ARM: u32 = 3u;
+const M_ARM_HOST: u32 = 0x10000u;
+const M_ARM_STOP: u32 = 0x20000u;
+// Line flags of the finish word, as records.rs: a rail, a way that wears lines, one that looks as a motorway, a
+// wall class, a deck's ceiling line (after every line of storey 0), line water, a path, a storey's line, and the
+// shift of its top's material (sections::Material, 4 bits).
+const M_RAIL: u32 = 256u;
+const M_MARKED: u32 = 512u;
+const M_MOTORWAY: u32 = 1024u;
+const M_WALL: u32 = 2048u;
+const M_CEILING: u32 = 4096u;
+const M_WATER: u32 = 8192u;
+const M_PATH: u32 = 16384u;
+// A line of a storey over the ground, after the ceiling lines: its leg bits (from 24) hold its storey.
+const M_STOREY: u32 = 32768u;
+const M_MATERIAL_SHIFT: u32 = 16u;
+// A line of a bridge's ground stretch: a wall at its edge is the bridge's, of concrete. A storey's line: from
+// M_BUILD_SHIFT, what its deck is made of (deck::Build, 2 bits) and whether its top is of planks (the third bit).
+const M_BRIDGE_GROUND: u32 = 1048576u;
+const M_BUILD_SHIFT: u32 = 21u;
+// Candidate kinds and the surfaces of the slope, line water, its bank and a culvert's zone, as records.rs and
+// faces::Surface.
+const M_BAND: u32 = 3u;
+const M_FILL: u32 = 4u;
+const M_SURFACE_SLOPE: u32 = 1u;
+const M_SURFACE_WATER: u32 = 9u;
+const M_SURFACE_BANK: u32 = 10u;
+const M_SURFACE_ZONE: u32 = 11u;
+// As MARGIN_M of records.rs: a bin lists every candidate edge within this of its square.
+const M_MARGIN: f32 = 3.0;
+
+fn mw(i: u32) -> u32 {
+    return textureLoad(model_words, vec2i(i32(i % MODEL_ROW), i32(i / MODEL_ROW)), 0).r;
+}
+
+fn mf(i: u32) -> f32 {
+    return bitcast(mw(i));
+}
+
+fn mi(i: u32) -> f32 {
+    return f32(bitcast(mw(i)));
+}
+
+fn m_cross(a: vec2f, b: vec2f) -> f32 {
+    return a.x * b.y - a.y * b.x;
+}
+
+fn m_cand(block: u32, ci: u32) -> u32 {
+    return block + mw(block + 4u) + ci * M_CAND;
+}
+
+fn m_vertex(at: u32) -> vec2i {
+    return vec2i(bitcast(mw(at)), bitcast(mw(at + 1u)));
+}
+
+// Metres per frame unit at the point (head word 10 is the cell's zoom-16 row): two cells that share
+// a point read the same scale.
+fn h_scale(block: u32, q: vec2f) -> f32 {
+    let v = f32(mw(block + 10u)) / 65536.0 + q.y / 17179869184.0;
+    return 40075016.686 / 17179869184.0 / cosh(3.14159265 * (1.0 - 2.0 * v));
+}
+
+fn m_label(block: u32, id: u32) -> u32 {
+    return block + mw(block + 5u) + id * M_LABEL;
+}
+
+// The junction record of label `id`, M_NONE for a label that no junction owns.
+fn m_junction(block: u32, id: u32) -> u32 {
+    if (id == M_NONE) {
+        return M_NONE;
+    }
+    let l = m_label(block, id);
+    if (((mw(l) >> 8u) & 0xffu) != M_JUNCTION) {
+        return M_NONE;
+    }
+    return block + mw(block + mw(block + 12u) + mw(l + 1u));
+}
+
+// The first word of arm k of junction record jr.
+fn m_arm(jr: u32, k: u32) -> u32 {
+    return jr + M_JR + M_JR_ARM * k;
+}
+
+// A line and a point's place in its frame: metres across from its middle (signed by side), along it, and its
+// half-width.
+struct ArmFrame {
+    line: u32,
+    place: vec3f,
+}
+
+// The arms of junction record jr whose flags hold `flags`, a bit each.
+fn m_arms_with(jr: u32, flags: u32) -> u32 {
+    var arms = 0u;
+    for (var k = 0u; k < min(mw(jr + 2u) & 0xffu, 32u); k++) {
+        arms |= select(0u, 1u << k, (mw(m_arm(jr, k)) & flags) == flags);
+    }
+    return arms;
+}
+
+// The nearest of the lines of a junction's `arms` (a bit each) and line `also`, and q's place in its frame, from their
+// segments in q's bin, which lists every segment of them that can be nearest to a point of the bin. Across is M_FAR
+// for none.
+fn m_junction_frame(block: u32, jr: u32, q: vec2f, arms: u32, also: u32, mpu: f32) -> ArmFrame {
+    let segs = m_bin_segments(block, q);
+    let samples = block + mw(block + 7u);
+    let lines = block + mw(block + 6u);
+    var best = M_FAR;
+    var out = ArmFrame(M_NONE, vec3f(M_FAR, 0.0, 0.0));
+    for (var i = 0u; i < segs.y; i++) {
+        let s = mw(segs.x + i);
+        let line = s & 0xffffu;
+        var take = line == also;
+        for (var k = 0u; k < min(mw(jr + 2u) & 0xffu, 32u); k++) {
+            take = take || (((arms >> k) & 1u) == 1u && (mw(m_arm(jr, k)) & 0xffffu) == line);
+        }
+        if (!take) {
+            continue;
+        }
+        let wa = samples + M_SAMPLE * (mw(lines + M_LINE * line + 2u) + (s >> 16u));
+        let wb = wa + M_SAMPLE;
+        let a = vec2f(m_vertex(wa));
+        let u = vec2f(m_vertex(wb)) - a;
+        let t = clamp(dot(q - a, u) / max(dot(u, u), 1e-9), 0.0, 1.0);
+        let d = length(q - a - t * u);
+        if (d < best) {
+            best = d;
+            out = ArmFrame(line, vec3f(sign(m_cross(u, q - a)) * d * mpu, mix(mf(wa + 3u), mf(wb + 3u), t), mix(mf(wa + 2u), mf(wb + 2u), t) * mpu));
+        }
+    }
+    return out;
+}
+
+// The finish word of a line, 0 for none.
+fn m_line_finish(block: u32, line: u32) -> u32 {
+    return select(mw(block + mw(block + 6u) + M_LINE * line + 1u), 0u, line == M_NONE);
+}
+
+fn m_extras(block: u32) -> u32 {
+    return block + mw(block + 8u);
+}
+
+// The header of q's bin (the closed cell square, as `find`), 0 outside the cell or for an empty bin.
+fn m_bin_head(block: u32, q: vec2f) -> u32 {
+    if (any(q < vec2f(0.0)) || any(q > vec2f(M_CELL))) {
+        return 0u;
+    }
+    let bin = min(vec2i(floor(q / M_BIN)), vec2i(M_BINS - 1));
+    let head = block + mw(block + 9u) + M_HEADER * u32(bin.y * M_BINS + bin.x);
+    return select(head, 0u, mw(head) == 0u);
+}
+
+// The word after the candidate item at `at`.
+fn m_skip_item(at: u32) -> u32 {
+    var next = at + 2u;
+    for (var r = 0u; r < mw(at + 1u); r++) {
+        next += 1u + 2u * mw(next);
+    }
+    return next;
+}
+
+// The first word and the count of the centre-line segments of q's bin.
+fn m_bin_segments(block: u32, q: vec2f) -> vec2u {
+    let head = m_bin_head(block, q);
+    if (head == 0u) {
+        return vec2u(0u);
+    }
+    return vec2u(block + mw(head) + (mw(head + 3u) >> 16u), mw(head + 1u) & 0xffffu);
+}
diff --git a/builder/web/src/lib/trailview/terrain/stamp-bake.ts b/builder/web/src/lib/trailview/terrain/stamp-bake.ts
new file mode 100644
index 0000000000..4cdd7a6d71
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/stamp-bake.ts
@@ -0,0 +1,97 @@
+// The bake of `planner/trailview-stamps`: the stamp worker's output for the baked nodes of a feature tile, as
+// node bytes. It runs in Node, where `self` is the global object that receives the worker's `onmessage`.
+import { MeshoptEncoder } from 'meshoptimizer/encoder';
+import './stamp-worker';
+import { BAKED, EMPTY_MESHES, encodeNode, type PackedMesh } from './node-bytes';
+import { OWNER, size, type Node } from './lod';
+import { WATER_VERTEX } from './water-mesh';
+import { DEEPEST } from '../stream/features';
+import { STRUCTURE_VERTEX } from '../structures/mesh';
+import { ANCHORED_VERTEX } from '../structures/anchored';
+import type { NodeMeshes } from '../structures/node';
+import type { NodeFeatures } from './stamps';
+import type { Request } from './stamp-worker';
+
+const worker = self as unknown as { onmessage: (event: { data: unknown }) => void; postMessage: (message: { result?: unknown; error?: string }) => void };
+
+/** The nodes that read feature tile `tile` and that the layer holds: the BAKED levels, and the owner level for its structure meshes. */
+function nodesOf(tile: Node): Node[] {
+    const level = tile.level === DEEPEST ? OWNER : tile.level + 1;
+    if (level !== OWNER && (level < BAKED.from || level > BAKED.to)) return [];
+    const side = 2 ** (level - tile.level);
+    return Array.from({ length: side * side }, (_, i) => ({ level, x: tile.x * side + (i % side), y: tile.y * side + Math.floor(i / side) }));
+}
+
+/** What the stamp worker posts for a job of `node` with the ground plan. */
+function posted(what: Request, tile: Node, node: Node, body: ArrayBuffer): Promise {
+    return new Promise((resolve, reject) => {
+        worker.postMessage = ({ result, error }) => (error === undefined ? resolve(result as T) : reject(new Error(error)));
+        worker.onmessage({ data: { id: 0, tile, node, body, what, plan: true } });
+    });
+}
+
+/** The stamps of `node`, and the structure meshes of an owner node, as the stamp worker posts them. */
+export const stamps = (tile: Node, node: Node, body: ArrayBuffer) => posted('stamps', tile, node, body);
+export const meshes = (tile: Node, node: Node, body: ArrayBuffer) => posted('meshes', tile, node, body);
+
+const code = (values: Uint32Array) => MeshoptEncoder.encodeIndexSequence(new Uint8Array(values.buffer, values.byteOffset, values.byteLength), values.length, 4);
+
+/**
+ * A mesh as the layer holds it (PackedMesh): its equal vertices once, in the order of their first use, and with
+ * `middle` its first two int32 words as int16 from there, when all fit.
+ */
+function packMesh(mesh: { vertices: ArrayBuffer; indices: Uint32Array }, stride: number, middle: [number, number] | null): object {
+    const [first, second, ...others] = Object.keys(mesh);
+    if (first !== 'vertices' || second !== 'indices') throw new Error(`packMesh: keys ${Object.keys(mesh)}`);
+    const { vertices, indices } = mesh, source = new Uint8Array(vertices), words = new DataView(vertices), n = source.byteLength / stride;
+    const seen = new Map(), of = new Uint32Array(n), distinct: number[] = [], latin1 = new TextDecoder('latin1');
+    for (let k = 0; k < n; k++) {
+        const name = latin1.decode(source.subarray(k * stride, (k + 1) * stride));
+        of[k] = seen.get(name) ?? seen.set(name, distinct.push(k) - 1).get(name)!;
+    }
+    const near = (k: number, c: number) => Math.abs(words.getInt32(k * stride + 4 * c, true) - middle![c] + 0.5) < 32768;
+    const xy = middle && distinct.every(k => near(k, 0) && near(k, 1)) ? middle : null;
+    const w = distinct.length, s = xy ? stride - 4 : stride, out = new Uint8Array(w * s), view = new DataView(out.buffer);
+    distinct.forEach((k, j) => {
+        if (!xy) return out.set(source.subarray(k * stride, (k + 1) * stride), j * s);
+        view.setInt16(j * s, words.getInt32(k * stride, true) - xy[0], true);
+        view.setInt16(j * s + 2, words.getInt32(k * stride + 4, true) - xy[1], true);
+        out.set(source.subarray(k * stride + 8, (k + 1) * stride), j * s + 4);
+    });
+    const $mesh: PackedMesh = { n, w, s, xy, v: MeshoptEncoder.encodeVertexBuffer(out, w, s), r: w === n ? null : code(of), ni: indices.length, i: code(indices) };
+    return { $mesh, ...Object.fromEntries(others.map(name => [name, (mesh as unknown as Record)[name]])) };
+}
+
+/** The structure meshes of an owner node, packed. */
+function packMeshes(meshes: NodeMeshes, middle: [number, number]): object {
+    const reach = ({ structures, anchored }: NodeMeshes['far']) => ({
+        structures: structures && packMesh(structures, 4 * STRUCTURE_VERTEX, middle),
+        anchored: anchored && packMesh(anchored, 4 * ANCHORED_VERTEX, null),
+    });
+    return { ...meshes, far: reach(meshes.far), near: reach(meshes.near) };
+}
+
+/**
+ * The bytes of each baked node of feature tile `tile` with body `body`: a whole node with its water mesh packed,
+ * or the packed structure meshes of each owner node that has any, and at the tile itself the u16 mask of those.
+ */
+export async function bakeTile(tile: Node, body: ArrayBuffer): Promise<[Node, Uint8Array][]> {
+    await MeshoptEncoder.ready;
+    const out: [Node, Uint8Array][] = [], empty = encodeNode(EMPTY_MESHES);
+    let mask = 0;
+    for (const [k, node] of nodesOf(tile).entries()) {
+        const middle: [number, number] = [(node.x + 0.5) * size(node.level), (node.y + 0.5) * size(node.level)];
+        if (node.level !== OWNER) {
+            const result = await stamps(tile, node, body);
+            out.push([node, encodeNode({ ...result, water: result.water && packMesh(result.water, 4 * WATER_VERTEX, middle) })]);
+            continue;
+        }
+        // The layer holds an owner node's structure meshes alone: the bake asks for no other job of it.
+        const made = await meshes(tile, node, body), bytes = encodeNode(made);
+        if (bytes.length === empty.length && bytes.every((byte, i) => byte === empty[i])) continue;
+        mask |= 1 << k;
+        out.push([node, encodeNode(packMeshes(made, middle))]);
+    }
+    if (tile.level === DEEPEST) out.push([tile, new Uint8Array(new Uint16Array([mask]).buffer)]);
+    return out;
+}
diff --git a/builder/web/src/lib/trailview/terrain/stamp-cache.test.ts b/builder/web/src/lib/trailview/terrain/stamp-cache.test.ts
new file mode 100644
index 0000000000..5d48585dc5
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/stamp-cache.test.ts
@@ -0,0 +1,78 @@
+import { readFileSync } from 'node:fs';
+import { gunzipSync } from 'node:zlib';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { FakeCaches } from '../../../../test-support/fake-caches';
+import { decodeFeatures } from '../stream/features';
+import { floorsOf, portalBoxes, structureMeshes } from '../structures/node';
+import { nodeStamps } from './bins';
+import { EMPTY_MESHES } from './node-bytes';
+import { Stamps } from './stamps';
+import { waterMesh } from './water-mesh';
+
+const TILE = { level: 13, x: 4286, y: 2888 };
+const features = decodeFeatures(new Uint8Array(gunzipSync(readFileSync(new URL(`../../../../tests/browser/trailview/fixture/features/13/${TILE.x}/${TILE.y}.bin`, import.meta.url)))));
+
+/** A stamp worker that makes each job as stamp-worker.ts does, from the fixture's tile. */
+class StampWorker {
+    static asked = 0;
+    static fails = false;
+    onmessage?: (event: { data: unknown }) => void;
+
+    postMessage({ id, node, what }: { id: number; node: typeof TILE; what: string }): void {
+        StampWorker.asked++;
+        if (StampWorker.fails && what === 'meshes') return queueMicrotask(() => this.onmessage?.({ data: { id, error: 'no memory' } }));
+        const result = what === 'meshes' ? structureMeshes(features, TILE, node)
+            : { ...nodeStamps(features, TILE, node, true), water: waterMesh(features, TILE, node), meshes: null, floors: floorsOf(features, TILE, node), portals: portalBoxes(features, TILE, node) };
+        queueMicrotask(() => this.onmessage?.({ data: { id, result } }));
+    }
+
+    terminate(): void {}
+}
+
+// Nodes of the fixture's tile with stamps and a water mesh, at levels 15 and 17.
+const nodes = [{ level: 15, x: 17144, y: 11553 }, { level: 17, x: 68582, y: 46208 }];
+const load = async (version: string) => {
+    const stamps = new Stamps(async () => new ArrayBuffer(4), () => {}, new AbortController().signal, true, undefined, { release: 'release', version });
+    for (const node of nodes) stamps.get(node);
+    stamps.send(() => 0);
+    for (let i = 0; i < 50 && (stamps.loading || nodes.some(node => !stamps.known(node))); i++) await new Promise(resolve => setTimeout(resolve, 5));
+    // The cache writes after the node arrives.
+    await new Promise(resolve => setTimeout(resolve, 20));
+    return nodes.map(node => stamps.known(node));
+};
+
+describe('the device cache of stamped nodes', () => {
+    beforeEach(() => {
+        vi.stubGlobal('caches', new FakeCaches());
+        vi.stubGlobal('Worker', StampWorker);
+        StampWorker.asked = 0;
+        StampWorker.fails = false;
+    });
+    afterEach(() => {
+        vi.unstubAllGlobals();
+        vi.restoreAllMocks();
+    });
+
+    it('gives a node as the worker made it, and misses with another stamp version', async () => {
+        const made = await load('a');
+        expect(made.every(node => node?.data && node.water)).toBe(true);
+        expect(made.map(node => !!node?.meshes)).toEqual([true, false]);
+        const again = await load('a');
+        // The stamps of both nodes and the structure meshes of the owner node: the cache holds the owner node whole.
+        expect(StampWorker.asked).toBe(3);
+        // toStrictEqual compares the classes of the typed arrays and buffers too.
+        expect(again).toStrictEqual(made);
+        await load('b');
+        expect(StampWorker.asked).toBe(6);
+    });
+
+    it('does not hold an owner node whose structure meshes failed: the next load makes it again', async () => {
+        vi.spyOn(console, 'warn').mockImplementation(() => {});
+        StampWorker.fails = true;
+        expect((await load('a'))[0]?.meshes).toBe(EMPTY_MESHES);
+        StampWorker.fails = false;
+        await load('a');
+        // Both loads asked for the owner node's stamps and meshes; the other node's stamps came from the cache.
+        expect(StampWorker.asked).toBe(5);
+    });
+});
diff --git a/builder/web/src/lib/trailview/terrain/stamp-core.wgsl b/builder/web/src/lib/trailview/terrain/stamp-core.wgsl
index bd2bb0b1e1..95af0c8728 100644
--- a/builder/web/src/lib/trailview/terrain/stamp-core.wgsl
+++ b/builder/web/src/lib/trailview/terrain/stamp-core.wgsl
@@ -104,6 +104,13 @@ const BUCKETS: u32 = 11u;
 // As KERB_M of roads.wgsl: a corner keeps its kerb where its sidewalk narrows to nothing.
 const CORNER_KERB_M: f32 = 0.18;
 
+// Where a road's cut or fill meets the ground, the ground rounds over DAYLIGHT_M of height instead of a
+// crease. Near the road the slope keeps its crease: the rounding grows from SOFT_FROM_M to SOFT_FULL_M past
+// the core.
+const DAYLIGHT_M: f32 = 0.8;
+const SOFT_FROM_M: f32 = 1.5;
+const SOFT_FULL_M: f32 = 4.0;
+
 const PI: f32 = 3.14159265;
 // As EARTH_RADIUS of frame.ts.
 const RADIUS: f32 = 6371000.0;
@@ -305,6 +312,32 @@ fn widen(x: f32, reach: f32, slope: f32) -> f32 {
     return slope * x * reach / (reach - x);
 }
 
+// The ground before the clamp: a soft minimum with the top of a cut, a soft maximum with the foot of a fill.
+fn rounded(base: f32, s: Stamp) -> f32 {
+    var h = base;
+    if (s.cut) {
+        let r = DAYLIGHT_M * smoothstep(SOFT_FROM_M, SOFT_FULL_M, s.cut_x);
+        let k = max(r - abs(h - s.hi), 0.0) / max(r, 1e-3);
+        h = min(h, s.hi) - k * k * r * 0.25;
+    }
+    if (s.fill) {
+        let r = DAYLIGHT_M * smoothstep(SOFT_FROM_M, SOFT_FULL_M, s.fill_x);
+        let k = max(r - abs(h - s.lo), 0.0) / max(r, 1e-3);
+        h = max(h, s.lo) + k * k * r * 0.25;
+    }
+    return h;
+}
+
+// The ground at a point after the stamps: a known base rounded at a bound of the cones, then clamped to them.
+fn stamped_ground(base: f32, s: Stamp) -> f32 {
+    return clamp(rounded(base, s), s.lo, s.hi);
+}
+
+// The height of a record over that ground: a paved one keeps its height, every other one keeps within the bounds.
+fn stamp_bounded(h: f32, paved: bool, s: Stamp) -> f32 {
+    return select(clamp(h, s.lo, s.hi), h, paved);
+}
+
 fn word(at: u32) -> u32 {
     return stamp_data[at];
 }
diff --git a/builder/web/src/lib/trailview/terrain/stamp-sources.test.ts b/builder/web/src/lib/trailview/terrain/stamp-sources.test.ts
new file mode 100644
index 0000000000..f5043208f6
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/stamp-sources.test.ts
@@ -0,0 +1,24 @@
+import { fileURLToPath } from 'node:url';
+import { describe, expect, it } from 'vitest';
+import { stampBundle } from '../../../../vite/stamp-bundle';
+
+const ROOT = fileURLToPath(new URL('../../../../../../', import.meta.url));
+
+/**
+ * The files that `stamp_sources` of host/obc-data-steps/src/planner.rs digests: the TypeScript of
+ * src/lib/trailview/ but its tests and packages, the JSON of data/trailview/, and the npm packages
+ * through package-lock.json.
+ */
+const digested = (file: string) =>
+    (/^builder\/web\/src\/lib\/trailview\/.+\.ts$/.test(file) && !file.endsWith('.test.ts') && !file.includes('/pkg/')) ||
+    /^data\/trailview\/.+\.json$/.test(file) ||
+    file.startsWith('builder/web/node_modules/');
+
+describe('stamp sources', () => {
+    it('hold every module of the stamp bake', async () => {
+        const { modules } = await stampBundle();
+        expect(modules.length).toBeGreaterThan(10);
+        const outside = modules.map(id => (id.startsWith(ROOT) ? id.slice(ROOT.length) : id)).filter(file => !digested(file));
+        expect(outside).toEqual([]);
+    }, 30_000);
+});
diff --git a/builder/web/src/lib/trailview/terrain/stamp-worker.ts b/builder/web/src/lib/trailview/terrain/stamp-worker.ts
index 0cf73aa783..e5d527d0af 100644
--- a/builder/web/src/lib/trailview/terrain/stamp-worker.ts
+++ b/builder/web/src/lib/trailview/terrain/stamp-worker.ts
@@ -1,26 +1,58 @@
-// Bins the features of a node's feature tile for stamp.wgsl and makes the node's water mesh and audit
-// samples, off the main thread.
-import { decodedTile } from '../stream/features';
+// Bins the features of a node's feature tile for stamp.wgsl and makes the node's water mesh, an owner node's
+// structure meshes and the audit samples, off the main thread.
+import { decodedTile, DEEPEST, heldTile, pinTile, tileBudget, wantTiles, type Feature } from '../stream/features';
 import { auditSamples, waterLevels } from './audit-samples';
 import { nodeStamps, type Node } from './bins';
 import { waterMesh } from './water-mesh';
 import { floorsOf, portalBoxes, structureMeshes } from '../structures/node';
 
-export type Request = 'stamps' | 'samples';
+/** What a job makes of a node: its stamps with its water, floors and portals, an owner node's structure meshes, or its audit samples. */
+export type Request = 'stamps' | 'meshes' | 'samples';
 
-self.onmessage = async ({ data: { id, tile, node, body, what } }: MessageEvent<{ id: number; tile: Node; node: Node; body: ArrayBuffer; what: Request }>) => {
+/**
+ * The 2 × 2 tiles of each zoom coarser than 13 read last, pinned in the byte budget: an eye near a tile
+ * corner reads all four, and the shapes of a zoom 8 tile take about half a second. The pins hold at most
+ * a third of the budget, so the deep tiles keep the 32 MiB of the other workers.
+ */
+const COARSE = 4;
+tileBudget(48 * 2 ** 20);
+const coarse = new Map();
+
+/** The features of a tile from its body, or as the worker still holds them without one; undefined where it holds none. */
+function tileFeatures(tile: Node, body?: ArrayBuffer): Promise | undefined {
+    const name = `${tile.level}/${tile.x}/${tile.y}`, features = body ? decodedTile(name, body) : heldTile(name);
+    if (features && tile.level < DEEPEST) {
+        const last = [...(coarse.get(tile.level) ?? []).filter(other => other !== name), name];
+        pinTile(name, true);
+        while (last.length > COARSE) pinTile(last.shift()!, false);
+        coarse.set(tile.level, last);
+    }
+    return features;
+}
+
+/**
+ * A request without `body` reads the tile that an earlier request brought; where the worker no longer holds it, the
+ * answer is `missing`. `wanted` names the tiles of the nodes on their way, still wished or without their structure
+ * meshes, and of the near levels' nodes that the last frame read: the worker keeps them past its budget.
+ */
+self.onmessage = async ({ data: { id, tile, node, body, what, plan, wanted = [] } }: MessageEvent<{ id: number; tile: Node; node: Node; body?: ArrayBuffer; what: Request; plan: boolean; wanted?: string[] }>) => {
+    wantTiles(wanted);
     try {
-        const features = await decodedTile(`${tile.level}/${tile.x}/${tile.y}`, body);
+        const held = tileFeatures(tile, body);
+        if (!held) return void self.postMessage({ id, missing: true });
+        const features = await held;
         if (what === 'samples') {
             const result = { samples: auditSamples(features, tile, node), ...waterLevels(features, tile) };
             self.postMessage({ id, result }, { transfer: [result.samples.buffer] });
+        } else if (what === 'meshes') {
+            const result = structureMeshes(features, tile, node, plan), { far, near, anchors, points } = result;
+            const buffers = [far.structures, far.anchored, near.structures, near.anchored].flatMap(mesh => (mesh ? [mesh.vertices, mesh.indices.buffer] : []));
+            self.postMessage({ id, result }, { transfer: [...buffers, ...(anchors ? [anchors] : []), ...(points ? [points.buffer] : [])] });
         } else {
-            const result = { ...nodeStamps(features, tile, node), water: waterMesh(features, tile, node), meshes: structureMeshes(features, tile, node), floors: floorsOf(features, tile, node), portals: portalBoxes(features, tile, node) };
-            const { far, near, anchors } = result.meshes;
-            const meshes = [result.water, far.structures, far.anchored, near.structures, near.anchored].flatMap(mesh => (mesh ? [mesh.vertices, mesh.indices.buffer] : []));
-            if (anchors) meshes.push(anchors);
-            if (result.meshes.points) meshes.push(result.meshes.points.buffer);
-            self.postMessage({ id, result }, { transfer: [...(result.data ? [result.data.buffer] : []), ...meshes, ...[result.floors, result.portals].flatMap(words => (words ? [words.buffer] : []))] });
+            // The structure meshes are a job of their own (`meshes`): a node's stamps never wait for them.
+            const result = { ...nodeStamps(features, tile, node, plan), water: waterMesh(features, tile, node), meshes: null, floors: floorsOf(features, tile, node), portals: portalBoxes(features, tile, node) };
+            const water = result.water ? [result.water.vertices, result.water.indices.buffer] : [];
+            self.postMessage({ id, result }, { transfer: [...(result.data ? [result.data.buffer] : []), ...water, ...[result.floors, result.portals].flatMap(words => (words ? [words.buffer] : []))] });
         }
     } catch (error) {
         self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
diff --git a/builder/web/src/lib/trailview/terrain/stamp.wgsl b/builder/web/src/lib/trailview/terrain/stamp.wgsl
index 7b8199a6ce..6589258aab 100644
--- a/builder/web/src/lib/trailview/terrain/stamp.wgsl
+++ b/builder/web/src/lib/trailview/terrain/stamp.wgsl
@@ -1,10 +1,12 @@
 // The stamp pass: each page that arrives or is synthesized gets its node's stamps before the mesh,
 // drawnHeight and the normals read it. A stored page keeps its raw heights for the syntheses below
 // it and draws a stamped copy; a synthesized page reads the raw stored pages only, so no level ever
-// upsamples a stamped parent. Near pages get the feature mask.
+// upsamples a stamped parent. Near pages get the feature mask. With MODEL the records of the cells
+// shape and paint the ways; today's stamps then hold only the water and the structures.
 // #include drawn-height.wgsl
 // #include stamp-core.wgsl
 // #include mask-walk.wgsl
+// #include model.wgsl
 
 struct StampJob {
     // The node's first texel at its level.
@@ -15,7 +17,8 @@ struct StampJob {
     // The page in `out` that receives the heights, and that holds the synthesized base.
     out: u32,
     // The raw stored page that is the base, or SYNTHESIZED for the base in `out`; for a mask alone,
-    // the drawn page.
+    // the drawn page, or SYNTHESIZED for a page synthesized in the frame: its layer gets the heights in
+    // `out` only after the stamps.
     base: u32,
     mode: u32,
     mask: u32,
@@ -32,6 +35,11 @@ struct StampJob {
 // features.wgsl reads it.
 @group(0) @binding(6) var mask_in: texture_2d_array;
 @group(0) @binding(7) var snaps: texture_storage_2d_array;
+// With MODEL, per mask texel: the paint of the paved label (paint_texel) and how far the heights moved
+// the ground, four texels of a row in one texel, as features.wgsl reads them.
+@group(0) @binding(9) var paint_out: texture_storage_2d_array;
+@group(0) @binding(10) var moved_out: texture_storage_2d_array;
+var moved_share: array;
 
 const SYNTHESIZED: u32 = 0xffffffffu;
 // The float32 bits of an unknown height in `out`, as in pages.wgsl.
@@ -62,12 +70,10 @@ const SNAP_TEXELS: f32 = 3.0;
 const SNAP_OUT_TEXELS: f32 = 3.75;
 // How far past a way's edge the snap compares the ground, past the bench that a path's stamp holds level.
 const UPHILL_TEXELS: f32 = 3.0;
-// Where a road's cut or fill meets the ground, the ground rounds over DAYLIGHT_M of height instead of a
-// crease. Near the road the slope keeps its crease: the rounding grows from SOFT_FROM_M to SOFT_FULL_M past
-// the core.
-const DAYLIGHT_M: f32 = 0.8;
-const SOFT_FROM_M: f32 = 1.5;
-const SOFT_FULL_M: f32 = 4.0;
+// As MOVED_RANGE_M of features.wgsl.
+const MOVED_RANGE_M: f32 = 0.5;
+// The paint finds the paved label across a change this many texels away.
+const PAINT_TEXELS: f32 = 2.0;
 
 // As in pages.wgsl: the ordered bits of a height, so that unsigned atomics take the least and the greatest.
 fn ordered(h: f32) -> u32 {
@@ -84,30 +90,20 @@ fn code_distance(code: f32) -> f32 {
     return MASK_KNEE * sinh((2.0 * code - 1.0) * asinh(MASK_RANGE / MASK_KNEE));
 }
 
-// The ground before the clamp: a soft minimum with the top of a cut, a soft maximum with the foot of a fill.
-fn rounded(base: f32, s: Stamp) -> f32 {
-    var h = base;
-    if (s.cut) {
-        let r = DAYLIGHT_M * smoothstep(SOFT_FROM_M, SOFT_FULL_M, s.cut_x);
-        let k = max(r - abs(h - s.hi), 0.0) / max(r, 1e-3);
-        h = min(h, s.hi) - k * k * r * 0.25;
-    }
-    if (s.fill) {
-        let r = DAYLIGHT_M * smoothstep(SOFT_FROM_M, SOFT_FULL_M, s.fill_x);
-        let k = max(r - abs(h - s.lo), 0.0) / max(r, 1e-3);
-        h = max(h, s.lo) + k * k * r * 0.25;
-    }
-    return h;
-}
-
 @compute @workgroup_size(8, 8)
-fn stamp(@builtin(global_invocation_id) id: vec3u) {
+fn stamp(@builtin(global_invocation_id) id: vec3u, @builtin(local_invocation_id) lane: vec3u) {
     let job = stamp_jobs[id.z];
     let t = job.first + vec2i(id.xy);
     let shift = 22u - job.level;
     let p = (t << vec2u(shift)) + vec2i(1 << (shift - 1u));
     let s = stamp_at(job.level, job.first, job.data, p);
+    var mp = ModelPoint(0u, vec2i(0), M_NONE, M_NONE, M_FAR, M_FAR, M_FAR, 0.0, 0.0, 0u, M_NONE);
+    if (MODEL && job.level >= M_CELL_LEVEL) {
+        mp = model_at(p, PAINT_TEXELS * unit_metres(p.y) * f32(1 << shift));
+    }
     var h = NONE;
+    // The ground that the ways shape: the plain terrain after the water and the structures.
+    var ground = NONE;
     if ((job.mode & HEIGHTS) != 0u) {
         let at = job.out * 65536u + id.y * 256u + id.x;
         var base = NONE;
@@ -117,7 +113,8 @@ fn stamp(@builtin(global_invocation_id) id: vec3u) {
         } else {
             base = slot_height(job.base, t);
         }
-        h = select(NONE, clamp(rounded(base, s), s.lo, s.hi), known(base));
+        ground = select(NONE, stamped_ground(base, s), known(base));
+        h = model_height(mp, ground, s);
         out[at] = select(UNKNOWN32, bitcast(h), known(h));
         if (known(h)) {
             atomicMin(&extent[2u * job.out], ordered(h));
@@ -126,19 +123,89 @@ fn stamp(@builtin(global_invocation_id) id: vec3u) {
     }
     if ((job.mode & MASK) != 0u) {
         if ((job.mode & HEIGHTS) == 0u) {
-            h = slot_height(job.base, t);
+            h = page_height(job, t);
+            // A late mask: the plain terrain is the bicubic that made the page.
+            if (MODEL) {
+                let plain = stored_base(p, job.level);
+                ground = select(NONE, stamped_ground(plain, s), known(plain));
+            }
+        }
+        if (MODEL) {
+            textureStore(mask_out, in_layer(job.mask, t), job.mask >> 6u, model_mask(mp, s));
+            textureStore(paint_out, in_layer(job.mask, t), job.mask >> 6u, paint_texel(mp));
+        } else {
+            // A cut or a fill face of a road, where the look draws a retaining wall if it is steep.
+            let faced = known(h) && ((s.fill && h <= s.lo + FACE_M) || (s.cut && h >= s.hi - FACE_M));
+            let flags = select(0u, WALL_FLAG, faced) | select(0u, CONFLICT_FLAG, s.conflict) | select(0u, FORD_FLAG, s.ford && s.road < 0.0) | select(0u, TAKEN_FLAG, s.taken);
+            let surface = select(0u, s.surface, s.road < MASK_RANGE);
+            let across = clamp(s.across / (2.0 * select(MASK_RANGE, TRACK_RANGE, surface >= TRACK_CODE)) + 0.5, 0.0, 1.0);
+            let walk = f32(walk_byte(s.walk, s.shoulder, s.trodden, s.marked)) / 255.0;
+            textureStore(mask_out, in_layer(job.mask, t), job.mask >> 6u,
+                vec4f(distance_code(s.road), select(walk, fract(s.sleepers), surface >= TRACK_CODE), across, f32(surface | (flags << 4u)) / 255.0));
+        }
+    }
+    if (MODEL) {
+        moved_share[lane.y * 8u + lane.x] = select(0.0, clamp(abs(h - ground) / MOVED_RANGE_M, 0.0, 1.0), known(h) && known(ground));
+        workgroupBarrier();
+        if ((job.mode & MASK) != 0u && (lane.x & 3u) == 0u) {
+            let k = lane.y * 8u + lane.x;
+            let at = in_layer(job.mask, t);
+            textureStore(moved_out, vec2i(at.x >> 2u, at.y), job.mask >> 6u, vec4f(moved_share[k], moved_share[k + 1u], moved_share[k + 2u], moved_share[k + 3u]));
         }
-        // A cut or a fill face of a road, where the look draws a retaining wall if it is steep.
-        let faced = known(h) && ((s.fill && h <= s.lo + FACE_M) || (s.cut && h >= s.hi - FACE_M));
-        let flags = select(0u, WALL_FLAG, faced) | select(0u, CONFLICT_FLAG, s.conflict) | select(0u, FORD_FLAG, s.ford && s.road < 0.0) | select(0u, TAKEN_FLAG, s.taken);
-        let surface = select(0u, s.surface, s.road < MASK_RANGE);
-        let across = clamp(s.across / (2.0 * select(MASK_RANGE, TRACK_RANGE, surface >= TRACK_CODE)) + 0.5, 0.0, 1.0);
-        let walk = f32(walk_byte(s.walk, s.shoulder, s.trodden, s.marked)) / 255.0;
-        textureStore(mask_out, in_layer(job.mask, t), job.mask >> 6u,
-            vec4f(distance_code(s.road), select(walk, fract(s.sleepers), surface >= TRACK_CODE), across, f32(surface | (flags << 4u)) / 255.0));
     }
 }
 
+// The height of the records at a texel over the ground that the water and the structures shaped. A
+// water's core and, off the paved area, a bore's cover and a deck's underside bound it, so a road runs
+// on onto its deck.
+fn model_height(mp: ModelPoint, ground: f32, s: Stamp) -> f32 {
+    if (!MODEL || mp.block == 0u || !known(ground)) {
+        return ground;
+    }
+    let hk = height_at(mp.block, vec2f(mp.q), mp.label, ground, mp.heights);
+    return stamp_bounded(hk.x, hk.y == H_PAVED, s);
+}
+
+// The finish of the painted label; in a stop arm's mouth, the arm's own.
+fn painted_finish(mp: ModelPoint) -> u32 {
+    return select(model_finish(mp.block, mp.painted), m_line_finish(mp.block, mp.mouth), mp.mouth != M_NONE);
+}
+
+// The feature mask of a texel from the records: the distance to the core's outline, which every reader
+// takes for a way's edge; the metres across of the way whose core it is, so that |across| less the
+// distance is its half-width; a way of the records counts as surface code 1. The water and the
+// structures keep their flags, and the records' water face takes the texel, so no plant stands in it.
+fn model_mask(mp: ModelPoint, s: Stamp) -> vec4f {
+    let road = mp.block != 0u && mp.core < MASK_RANGE;
+    let water = mp.block != 0u && mp.label != M_NONE && m_surface(mp.block, mp.label) == M_SURFACE_WATER;
+    let flags = select(0u, CONFLICT_FLAG, s.conflict) | select(0u, FORD_FLAG, s.ford && mp.core < 0.0) | select(0u, TAKEN_FLAG, s.taken || water);
+    let side = select(1.0, sign(mp.across), mp.across != M_FAR && mp.across != 0.0);
+    let half = select(mp.half, 0.0, mp.across == M_FAR);
+    let across = clamp(side * min(max(mp.core, 0.0) + half, MASK_RANGE) / (2.0 * MASK_RANGE) + 0.5, 0.0, 1.0);
+    let walk = f32(walk_byte(0.0, false, (painted_finish(mp) & 0xffu) == 6u, false)) / 255.0;
+    return vec4f(distance_code(mp.core), walk, across, f32(select(0u, 1u, road) | (flags << 4u)) / 255.0);
+}
+
+// The paint of a texel in the mask's format, read by mask_in of features.wgsl: the distance to the paved
+// outline, the walk byte (or a track's sleepers), the metres across from the host's middle (a road's on the
+// distance's asinh scale), and the finish code of the painted label (0 none) in the low 4 bits of a byte with
+// its top's material (sections::Material, at most 15) above them. A road of a lesser class paints in the main road's asphalt.
+fn paint_texel(mp: ModelPoint) -> vec4f {
+    let finish = painted_finish(mp);
+    var code = select(finish & 0xffu, 1u, (finish & 0xffu) == 2u);
+    if (mp.block == 0u || mp.painted == M_NONE || mp.d_paved >= MASK_RANGE) {
+        code = 0u;
+    }
+    let track = code >= TRACK_CODE;
+    let metres = select(mp.across, MASK_RANGE, mp.across == M_FAR);
+    let across = select(distance_code(metres), clamp(metres / (2.0 * TRACK_RANGE) + 0.5, 0.0, 1.0), track);
+    // Lines on the asphalt of a way that wears them (the records' flag); a soil path is trodden.
+    let marked = (finish & M_MARKED) != 0u;
+    let walk = f32(walk_byte(0.0, false, code == 6u, marked)) / 255.0;
+    let material = select(0u, (finish >> M_MATERIAL_SHIFT) & 15u, code != 0u);
+    return vec4f(distance_code(mp.d_paved), select(walk, fract(mp.along / SLEEPER_M), track), across, f32(code | (material << 4u)) / 255.0);
+}
+
 // The rise per metre of a value at the four texels about a vertex's corner.
 fn rise_of(c: array, metres: f32) -> vec2f {
     return vec2f(c[1] + c[3] - c[0] - c[2], c[2] + c[3] - c[0] - c[1]) * 0.5 / metres;
@@ -152,7 +219,7 @@ fn corner_value(c: array, rise: vec2f, past: vec2f) -> f32 {
 // The height that a job's page holds at a texel, inside the page.
 fn page_height(job: StampJob, t: vec2i) -> f32 {
     let p = clamp(t, job.first, job.first + vec2i(255));
-    if ((job.mode & HEIGHTS) == 0u) {
+    if ((job.mode & HEIGHTS) == 0u && job.base != SYNTHESIZED) {
         return slot_height(job.base, p);
     }
     let v = vec2u(p - job.first);
diff --git a/builder/web/src/lib/trailview/terrain/stamps.test.ts b/builder/web/src/lib/trailview/terrain/stamps.test.ts
new file mode 100644
index 0000000000..b968f3d979
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/stamps.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest';
+import { EMPTY_MESHES } from './node-bytes';
+import { Stamps, type BakedNodes } from './stamps';
+import type { Node } from './lod';
+import type { Request } from './stamp-worker';
+
+const WORKER = { ...EMPTY_MESHES, anchors: new ArrayBuffer(4) };
+const name = ({ level, x, y }: Node) => `${level}/${x}/${y}`;
+
+/**
+ * A stamp worker whose structure meshes hold a 4-byte `anchors` (so they are the worker's). `jobs` are the jobs in the
+ * order in which it got them, which is the order in which a worker takes them; `answer` answers the first `count` jobs
+ * that wait. Without `held` each job answers at once.
+ */
+function fakeWorker(held = false) {
+    const jobs: string[] = [], waiting: (() => void)[] = [];
+    Object.assign(globalThis, {
+        Worker: class {
+            onmessage?: (event: { data: unknown }) => void;
+            postMessage({ id, what, node }: { id: number; what: Request; node: Node }) {
+                jobs.push(`${what} ${name(node)}`);
+                const stamps = { data: null, heights: false, mask: false, water: null, meshes: null, floors: null, portals: null };
+                const answer = () => this.onmessage?.({ data: { id, result: what === 'meshes' ? WORKER : stamps } });
+                if (held) waiting.push(answer);
+                else queueMicrotask(answer);
+            }
+            terminate() {}
+        },
+    });
+    return { jobs, answer: (count = waiting.length) => waiting.splice(0, count).forEach(answer => answer()) };
+}
+
+const settle = () => new Promise(resolve => setTimeout(resolve, 0));
+
+/** The features of `node` through Stamps with the stamp layer `baked`, once nothing is on its way. */
+async function load(node: Node, baked: BakedNodes) {
+    const { jobs } = fakeWorker();
+    const stamps = new Stamps(async () => new ArrayBuffer(8), () => {}, new AbortController().signal, true, baked);
+    expect(stamps.get(node)).toBeUndefined();
+    stamps.send(() => 0);
+    for (let i = 0; i < 20 && (stamps.loading || !stamps.known(node)); i++) await settle();
+    return { features: stamps.known(node), jobs };
+}
+
+const L12 = { level: 12, x: 2143, y: 1443 }, L15 = { level: 15, x: 17153, y: 11551 };
+const mask = (bits: number) => new Uint8Array(new Uint16Array([bits]).buffer);
+const corrupt = new Uint8Array([3, 0, 0, 0, 1]);
+
+describe('stamps from the stamp layer', () => {
+    it('come from the worker where a node does not decode', async () => {
+        const coarse = await load(L12, async () => corrupt);
+        expect(coarse.jobs).toEqual([`stamps ${name(L12)}`]);
+        // The mask holds the node (bit 1 + 4 × 3), but its bytes are corrupt: the worker's structure job makes the meshes.
+        const owner = await load(L15, async z => (z === 13 ? mask(1 << 13) : corrupt));
+        expect(owner.jobs).toEqual([`stamps ${name(L15)}`, `meshes ${name(L15)}`]);
+        expect(owner.features?.meshes).toBe(WORKER);
+    });
+
+    it('give an owner node that the mask does not hold no meshes, without a request', async () => {
+        const asked: number[] = [];
+        const owner = await load(L15, async z => (asked.push(z), z === 13 ? mask(1 << 2) : corrupt));
+        expect(asked).toEqual([13]);
+        expect(owner.jobs).toEqual([`stamps ${name(L15)}`]);
+        expect(owner.features?.meshes).toEqual(EMPTY_MESHES);
+    });
+});
+
+describe('the stamp requests', () => {
+    it('go out as answers come, the last frame\'s wishes by rank, without another frame', async () => {
+        fakeWorker();
+        const stamps = new Stamps(async () => new ArrayBuffer(8), () => {}, new AbortController().signal);
+        // More wishes than requests in flight.
+        const nodes = Array.from({ length: 12 }, (_, i) => ({ level: L15.level, x: L15.x + i, y: L15.y }));
+        for (const node of nodes) stamps.get(node);
+        stamps.send(node => node.x);
+        for (let i = 0; i < 40 && (stamps.loading || nodes.some(node => !stamps.known(node))); i++) await settle();
+        expect(nodes.filter(node => !stamps.known(node)?.meshes)).toEqual([]);
+    });
+});
+
+describe('the structure meshes of an owner node', () => {
+    const owners = [0, 1, 2].map(i => ({ level: 15, x: L15.x + i, y: L15.y })), near = (i: number) => ({ level: 18, x: 8 * L15.x + i, y: 8 * L15.y });
+    /** Stamps on a worker that holds its answers, after a frame that wishes for `nodes` with `rank`. */
+    const frame = async (nodes: Node[], rank: (node: Node) => number) => {
+        const worker = fakeWorker(true), stamps = new Stamps(async () => new ArrayBuffer(8), () => {}, new AbortController().signal);
+        const wish = async (more: Node[], order: (node: Node) => number) => {
+            for (const node of more) stamps.get(node);
+            stamps.send(order);
+            await settle();
+        };
+        const answer = async (count?: number) => {
+            worker.answer(count);
+            await settle();
+        };
+        await wish(nodes, rank);
+        return { stamps, jobs: worker.jobs, wish, answer };
+    };
+
+    it('wait for every stamp request, and a stamp wish that comes later waits for one structure job at most', async () => {
+        // The owner nodes hold the eye, so they rank first: their stamps go first, their meshes after every stamp.
+        const { stamps, jobs, wish, answer } = await frame([...owners, near(0), near(1)], node => (node.level === 15 ? node.x - L15.x : 10));
+        expect(jobs).toEqual([...owners.map(node => `stamps ${name(node)}`), `stamps ${name(near(0))}`, `stamps ${name(near(1))}`]);
+        // The owner nodes' stamps came, two stamp requests are on their way: no structure job.
+        await answer(3);
+        expect(jobs.length).toBe(5);
+        await answer();
+        // One structure job, of the first owner node in the rank. No other follows while it is on its way.
+        expect(jobs.slice(5)).toEqual([`meshes ${name(owners[0])}`]);
+        // The camera moves: a new stamp wish goes to the worker behind that one job, and the last owner node now ranks first.
+        await wish([near(2)], node => (node.level === 15 ? L15.x + 2 - node.x : 10));
+        expect(jobs.slice(6)).toEqual([`stamps ${name(near(2))}`]);
+        await answer();
+        expect(stamps.known(owners[0])?.meshes).toBe(WORKER);
+        expect(jobs.slice(7)).toEqual([`meshes ${name(owners[2])}`]);
+        await answer();
+        await answer();
+        expect(jobs.slice(8)).toEqual([`meshes ${name(owners[1])}`]);
+        expect(stamps.loading).toBe(false);
+        expect(owners.map(node => stamps.known(node)?.meshes)).toEqual([WORKER, WORKER, WORKER]);
+    });
+});
diff --git a/builder/web/src/lib/trailview/terrain/stamps.ts b/builder/web/src/lib/trailview/terrain/stamps.ts
index 3d06bb986e..6ce8017808 100644
--- a/builder/web/src/lib/trailview/terrain/stamps.ts
+++ b/builder/web/src/lib/trailview/terrain/stamps.ts
@@ -1,6 +1,8 @@
-import { featureTile, type NodeStamps } from './bins';
-import { key, type Node } from './lod';
-import { STAMP_WORDS, type StampSource } from './pages';
+import { featureTile, NEAR, type NodeStamps } from './bins';
+import { CAPS, DeviceCache } from './device-cache';
+import { key, OWNER, type Node } from './lod';
+import { BAKED, decodeNode, EMPTY_MESHES, encodeNode, unpackNode } from './node-bytes';
+import type { StampSource } from './pages';
 import type { Request } from './stamp-worker';
 import type { NodeMeshes } from '../structures/node';
 import type { WaterMesh } from './water-mesh';
@@ -11,7 +13,10 @@ const NODE_BYTES = 64 * 2 ** 20, ENTRY_BYTES = 64;
 /** Requests to the worker in flight at most. */
 const REQUESTS = 8;
 
-/** What a node stamps, its water, its structures and kinds, their floors and the boxes of its tunnels' portals, from the worker. */
+/**
+ * What a node stamps, its water, the floors of its structures and the boxes of its tunnels' portals, from the worker;
+ * and the structures and kinds of an owner node: null until their own job answers, and for every other node.
+ */
 export interface NodeFeatures extends NodeStamps {
     water: WaterMesh | null;
     meshes: NodeMeshes | null;
@@ -19,7 +24,12 @@ export interface NodeFeatures extends NodeStamps {
     portals: Float64Array | null;
 }
 
+/** The worker's answer where it no longer holds a tile whose body went to it. */
+const MISSING = Symbol('missing');
+
 const NOTHING: NodeFeatures = { data: null, heights: false, mask: false, water: null, meshes: null, floors: null, portals: null };
+/** Whether a node lacks nothing: an owner node of a tile has its structure meshes. */
+const whole = (node: Node, features: NodeFeatures) => node.level !== OWNER || features === NOTHING || features.meshes !== null;
 const meshBytes = (mesh: { vertices: ArrayBuffer; indices: Uint32Array } | null) => (mesh ? mesh.vertices.byteLength + mesh.indices.byteLength : 0);
 const kindBytes = ({ far, near, anchors, points }: NodeMeshes) =>
     [far.structures, far.anchored, near.structures, near.anchored].reduce((n, mesh) => n + meshBytes(mesh), (anchors?.byteLength ?? 0) + (points?.byteLength ?? 0));
@@ -28,6 +38,8 @@ const bytesOf = ({ data, water, meshes, floors, portals }: NodeFeatures) =>
 
 /** The body of feature tile z/x/y, undefined where it is absent. */
 export type FeatureTiles = (z: number, x: number, y: number) => Promise;
+/** The bytes of node z/x/y of the stamp layer (node-bytes.ts), undefined where the layer holds none. */
+export type BakedNodes = (z: number, x: number, y: number) => Promise;
 
 /** The audit samples of a node, as audit.wgsl reads them, and the water levels of its feature tile. */
 export interface NodeSamples {
@@ -47,57 +59,204 @@ const NO_SAMPLES: NodeSamples = { samples: new Uint32Array(0), lakes: 0, mixed:
 export class Stamps implements StampSource {
     private readonly nodes = new Map();
     private nodeBytes = 0;
-    private readonly pending = new Set();
+    /** The nodes on their way, and the feature tile of each. */
+    private readonly pending = new Map();
+    private readonly masks = new Map>();
+    /** The nodes that the frame asked for and that are not on their way. */
+    private readonly wishes = new Map();
+    /** The last frame's wishes that did not go yet, by rank: each answer sends the next. */
+    private queue: Node[] = [];
+    /** The owner nodes that are known without their structure meshes, whether one's meshes are on their way, and the last frame's rank. */
+    private readonly unbuilt = new Map();
+    private building = false;
+    private rank: (node: Node) => number = () => 0;
+    /** The feature tiles of the frame's wishes, and of the near levels' nodes that the frame read and the frame before. */
+    private queued = new Set();
+    private nearRead = new Set();
+    private nearTiles = new Set();
     private readonly worker?: Worker;
     private readonly waiting = new Map void; reject: (error: Error) => void }>();
     private next = 0;
+    private readonly cache?: Promise;
+    /** The feature tiles whose body went to the worker: it keeps them decoded while its budget holds them. */
+    private readonly sent = new Set();
     failed = 0;
+    /** How often the nodes hit a limit of their stamps (NodeStamps.limits). */
+    limits = 0;
 
-    /** An abort of `stop` ends the worker. */
-    constructor(private readonly tiles: FeatureTiles | undefined, private readonly changed: () => void, stop: AbortSignal) {
+    /**
+     * An abort of `stop` ends the worker. With `plan` the records draw the ways (nodeStamps of bins.ts). A node
+     * that `baked` holds comes from it, with the same bytes as from the worker. With `cache`, the release and the
+     * version of the stamp code (`virtual:stamp-version`), the nodes go to the device cache.
+     */
+    constructor(private readonly tiles: FeatureTiles | undefined, private readonly changed: () => void, stop: AbortSignal, readonly plan = false, private readonly baked?: BakedNodes, cache?: { release: string; version: string }) {
         if (!tiles) return;
+        if (cache) this.cache = DeviceCache.open('stamps', cache.release, `${cache.version}/${plan}`, CAPS.stamps).catch(error => {
+            console.warn(`The stamps' device cache did not open: ${error}`);
+            return undefined;
+        });
         const worker = this.worker = new Worker(new URL('./stamp-worker.ts', import.meta.url), { type: 'module' });
         stop.addEventListener('abort', () => worker.terminate());
         this.worker.onmessage = ({ data }) => {
             const wait = this.waiting.get(data.id);
             this.waiting.delete(data.id);
             if (data.error) wait?.reject(new Error(data.error));
-            else wait?.resolve(data.result);
+            else wait?.resolve(data.missing ? MISSING : data.result);
         };
     }
 
-    /** Whether features are on their way: each wakes the engine when it arrives. */
+    /** Whether features are on their way: each wakes the engine when it arrives. A wish waits only while REQUESTS are. */
     get loading(): boolean {
-        return this.pending.size > 0;
+        return this.pending.size > 0 || this.unbuilt.size > 0;
     }
 
-    /** The node's stamps and water, undefined while they are on their way. */
+    /** The node's stamps and water, undefined while they are on their way: the node is a wish of this frame until `send`. */
     get(node: Node): NodeFeatures | undefined {
         const tile = featureTile(node);
         if (!this.tiles || !tile) return NOTHING;
         const known = this.known(node);
         if (known) return known;
         const name = key(node);
-        if (!this.pending.has(name) && this.pending.size < REQUESTS) {
-            this.pending.add(name);
-            this.ask(tile, node, 'stamps').then(stamps => {
-                // A frame takes at most STAMP_WORDS: a node with more would wait forever, so it stamps nothing.
-                if ((stamps.data?.length ?? 0) <= STAMP_WORDS) return this.keep(name, stamps);
-                console.warn(`Node ${name}: ${stamps.data!.length} words of stamps, more than a frame takes`);
-                this.keep(name, { ...stamps, data: null, heights: false, mask: false });
-            }, error => {
-                // A tile that fails stamps nothing, as an absent one.
-                if (!stopped(error)) console.warn(`Feature tile ${key(tile)}: ${error instanceof Error ? error.message : error}`);
-                this.failed++;
-                this.keep(name, NOTHING);
-            }).finally(() => {
-                this.pending.delete(name);
-                this.changed();
-            });
-        }
+        if (!this.pending.has(name)) this.wishes.set(name, node);
         return undefined;
     }
 
+    /**
+     * Asks the worker for the frame's wishes, the lowest `rank` first, while it has fewer than REQUESTS
+     * on their way. The rest go as answers come, until the next frame states its wishes again.
+     */
+    send(rank: (node: Node) => number): void {
+        const ranks = new Map([...this.wishes.values()].map(node => [node, rank(node)]));
+        this.queue = [...ranks.keys()].sort((a, b) => ranks.get(a)! - ranks.get(b)!);
+        this.queued = new Set(this.queue.map(node => key(featureTile(node)!)));
+        [this.nearTiles, this.nearRead] = [this.nearRead, new Set()];
+        this.wishes.clear();
+        this.rank = rank;
+        this.refill();
+    }
+
+    /**
+     * The stamps first: the structure meshes of an owner node are a job of their own, which goes to the worker only
+     * while no stamp request is on its way, and one at a time. The worker takes its jobs in turn, so a stamp wish
+     * waits for one structure job at most, whenever it comes. Of the owner nodes without meshes, the next is the
+     * lowest in the last frame's rank.
+     */
+    private refill(): void {
+        while (this.pending.size < REQUESTS && this.queue.length) {
+            const node = this.queue.shift()!;
+            if (!this.pending.has(key(node)) && !this.nodes.has(key(node))) this.request(node);
+        }
+        if (this.pending.size || this.building) return;
+        let next: Node | undefined;
+        for (const node of this.unbuilt.values()) if (!next || this.rank(node) < this.rank(next)) next = node;
+        if (next) this.build(next);
+    }
+
+    private request(node: Node): void {
+        const tile = featureTile(node)!, name = key(node);
+        this.pending.set(name, key(tile));
+        this.stamps(tile, node).then(stamps => {
+            this.limits += stamps.limits ?? 0;
+            this.keep(name, stamps);
+            if (!whole(node, stamps)) this.unbuilt.set(name, node);
+        }, error => {
+            // A tile that fails stamps nothing, as an absent one.
+            if (!stopped(error)) console.warn(`Feature tile ${key(tile)}: ${error instanceof Error ? error.message : error}`);
+            this.failed++;
+            this.keep(name, NOTHING);
+        }).finally(() => {
+            this.pending.delete(name);
+            this.refill();
+            this.changed();
+        });
+    }
+
+    /** A node's stamps from the device cache, or from the worker, which the cache then keeps. */
+    private async stamps(tile: Node, node: Node): Promise {
+        const cache = await this.cache, name = key(node);
+        const hit = await cache?.read(name).catch(() => undefined);
+        if (hit) return decodeNode(new Uint8Array(hit[0].buffer)) as NodeFeatures;
+        const made = await this.features(tile, node);
+        this.save(node, made);
+        return made;
+    }
+
+    /** Keeps a node in the device cache, an owner node once it has its structure meshes: a cached node is whole. */
+    private save(node: Node, made: NodeFeatures): void {
+        if (made === NOTHING || !whole(node, made)) return;
+        // Off the critical path; a value that encodeNode cannot give back exactly is not kept.
+        void this.cache?.then(cache => cache?.write(key(node), [new Uint32Array(encodeNode(made).buffer)])).catch(() => {});
+    }
+
+    /**
+     * A BAKED node with the ground plan, and an owner node's structure meshes, from the stamp layer where it holds
+     * them; the rest from the worker. The mask of a feature tile says which of its owner nodes have meshes: the
+     * others are EMPTY_MESHES and cost no request. An owner node that the layer cannot give its meshes waits for
+     * the worker's structure job.
+     */
+    private async features(tile: Node, node: Node): Promise {
+        if (this.plan && node.level >= BAKED.from && node.level <= BAKED.to) {
+            const baked = await this.read(node);
+            if (baked) return baked as NodeFeatures;
+        }
+        const [stamps, meshes] = await Promise.all([this.ask(tile, node, 'stamps'), node.level === OWNER && this.baked ? this.layerMeshes(tile, node) : undefined]);
+        return stamps === NOTHING || !meshes ? stamps : { ...stamps, meshes };
+    }
+
+    /** An owner node's structure meshes as the stamp layer gives them; undefined where it cannot. */
+    private async layerMeshes(tile: Node, node: Node): Promise {
+        const mask = await this.mask(tile);
+        if (mask === undefined) return undefined;
+        return (mask >> ((node.x & 3) + 4 * (node.y & 3))) & 1 ? ((await this.read(node)) as NodeMeshes | undefined) : EMPTY_MESHES;
+    }
+
+    /**
+     * The structure meshes of an owner node from the worker: the node is whole when they come. A job that fails gives
+     * none for this session and is not kept on the device: the next load asks again.
+     */
+    private build(node: Node): void {
+        const name = key(node);
+        this.building = true;
+        this.ask(featureTile(node)!, node, 'meshes').catch(error => {
+            if (!stopped(error)) console.warn(`The structure meshes of ${name}: ${error instanceof Error ? error.message : error}`);
+            this.failed++;
+            return EMPTY_MESHES;
+        }).then(meshes => {
+            const known = this.nodes.get(name);
+            if (!known) return;
+            const built = { ...known, meshes };
+            this.keep(name, built);
+            // The worker's answer is never the constant itself.
+            if (meshes !== EMPTY_MESHES) this.save(node, built);
+        }).finally(() => {
+            this.building = false;
+            this.unbuilt.delete(name);
+            this.refill();
+            this.changed();
+        });
+    }
+
+    /** The node as the stamp layer holds it; undefined where it holds none or its bytes do not decode. */
+    private async read(node: Node): Promise {
+        try {
+            const bytes = await this.baked?.(node.level, node.x, node.y);
+            return bytes && (await unpackNode(bytes));
+        } catch {
+            return undefined;
+        }
+    }
+
+    /** The mask of the owner nodes of feature tile `tile` that the stamp layer holds; undefined without one. */
+    private mask(tile: Node): Promise {
+        const name = key(tile);
+        let mask = this.masks.get(name);
+        if (!mask) {
+            const read = this.baked!(tile.level, tile.x, tile.y).then(bytes => (bytes?.byteLength === 2 ? bytes[0] | (bytes[1] << 8) : undefined));
+            this.masks.set(name, (mask = read.catch(() => undefined)));
+        }
+        return mask;
+    }
+
     /** The audit samples of a node. */
     async samples(node: Node): Promise {
         const tile = featureTile(node);
@@ -106,7 +265,9 @@ export class Stamps implements StampSource {
 
     /** The node's stamps and water once they are known, without a request. */
     known(node: Node): NodeFeatures | undefined {
-        if (!this.tiles || !featureTile(node)) return NOTHING;
+        const tile = featureTile(node);
+        if (!this.tiles || !tile) return NOTHING;
+        if (node.level >= NEAR) this.nearRead.add(key(tile));
         const name = key(node), known = this.nodes.get(name);
         if (known) {
             this.nodes.delete(name);
@@ -123,17 +284,34 @@ export class Stamps implements StampSource {
         for (const [first, kept] of this.nodes) {
             if (this.nodeBytes <= NODE_BYTES) break;
             this.nodes.delete(first);
+            this.unbuilt.delete(first);
             this.nodeBytes -= bytesOf(kept);
         }
     }
 
+    /** The body of a tile goes once, and again where the worker no longer holds it. */
     private async ask(tile: Node, node: Node, what: Request): Promise {
-        const body = await this.tiles!(tile.level, tile.x, tile.y);
-        if (!body) return ({ stamps: NOTHING, samples: NO_SAMPLES } as const)[what] as T;
+        const name = key(tile), sent = this.sent.has(name), body = sent ? undefined : await this.tiles!(tile.level, tile.x, tile.y);
+        if (!sent && !body) return ({ stamps: NOTHING, meshes: EMPTY_MESHES, samples: NO_SAMPLES } as const)[what] as T;
         const id = this.next++;
-        return new Promise((resolve, reject) => {
-            this.waiting.set(id, { resolve: resolve as (result: unknown) => void, reject });
-            this.worker!.postMessage({ id, tile, node, body, what }, [body]);
+        const answer = await new Promise((resolve, reject) => {
+            this.waiting.set(id, { resolve, reject });
+            this.worker!.postMessage({ id, tile, node, body, what, plan: this.plan, wanted: this.wanted() }, body ? [body] : []);
+            if (body) this.sent.add(name);
         });
+        if (answer !== MISSING) return answer as T;
+        this.sent.delete(name);
+        return this.ask(tile, node, what);
+    }
+
+    /**
+     * The feature tiles of the nodes on their way, still wished or without their structure meshes, and of the near levels'
+     * nodes that the last frame read: the worker keeps them. The eye's own tile has no wish for seconds between its waves of levels.
+     */
+    private wanted(): string[] {
+        const tiles = new Set([...this.pending.values(), ...this.queued, ...this.nearTiles, ...[...this.unbuilt.values()].map(node => key(featureTile(node)!))]);
+        // A tile that no job reads now sends its body again when one does: the worker may have let it go.
+        for (const name of this.sent) if (!tiles.has(name)) this.sent.delete(name);
+        return [...tiles];
     }
 }
diff --git a/builder/web/src/lib/trailview/terrain/terrain.test.ts b/builder/web/src/lib/trailview/terrain/terrain.test.ts
index 61d8876615..a4163a8ccd 100644
--- a/builder/web/src/lib/trailview/terrain/terrain.test.ts
+++ b/builder/web/src/lib/trailview/terrain/terrain.test.ts
@@ -1,11 +1,12 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
 import { anchorAt } from '../frame/space';
 import { TILE_ZOOM } from '../stream/terrain';
-import { cdlod, GRID, RANGE, select, size } from './lod';
-import { gridIndices, SYNTH_PAGES, Terrain } from './terrain';
+import { CALM, cdlod, GRID, RANGE, select, size } from './lod';
+import { MODE, type Page } from './pages';
+import { gridIndices, stampJobs, stepQuality, SYNTH_PAGES, SYNTHESIZED, Terrain } from './terrain';
 
 describe('the synthesized pool', () => {
-    it('holds what the least range wants of the half of the world ahead, so no shortage takes away the finest level', () => {
+    it('holds what the least range wants of the half of the world ahead, so no page is left out', () => {
         const anchor = anchorAt(8.38, 46.8), east = anchor.whole[0] + anchor.part[0];
         for (const above of [1.6, 30, 300]) {
             const { wanted } = select(cdlod({ anchor, above }, RANGE.least), [0, 0, 2 ** 30, 2 ** 30], ({ level, x }) => (x + 1) * size(level) >= east);
@@ -14,6 +15,23 @@ describe('the synthesized pool', () => {
     });
 });
 
+describe('the stamp jobs', () => {
+    const page = (kind: Page['kind'], slot: number, drawn: number): Page => ({ node: { level: 18, x: 1, y: 2 }, kind, slot, used: 0, range: [0, 0], complete: true, ready: true, drawn, mask: 3 });
+
+    it('read the heights of a page synthesized in the frame from `out`, a stored page\'s from its raw layer, and a mask alone from the drawn layer', () => {
+        const fresh = page('synth', 7, 7), old = page('synth', 8, 8), stored = page('stored', 2, 40);
+        const stamps = [
+            { page: fresh, out: 0, target: 7, data: null, mode: MODE.MASK },
+            { page: old, out: 0, target: 8, data: null, mode: MODE.MASK },
+            { page: stored, out: 1, target: 40, data: null, mode: MODE.HEIGHTS },
+            { page: fresh, out: 0, target: 7, data: null, mode: MODE.HEIGHTS | MODE.MASK },
+        ];
+        const words = new Uint32Array(stampJobs(stamps, new Set([fresh])).jobs), step = words.length / stamps.length;
+        // `base`, the sixth word of a StampJob.
+        expect(stamps.map((_, k) => words[step * k + 5])).toEqual([SYNTHESIZED, 8, 2, SYNTHESIZED]);
+    });
+});
+
 describe('the paint of the near field', () => {
     const node = { level: 18, x: 1, y: 2 }, name = '18/1/2', anchor = { whole: [0, 0], part: [0, 0], unit: 1 };
     const painted = (stamps: { data: Uint32Array | null; heights: boolean; mask: boolean }) => (Terrain.prototype as unknown as { painted: (nodes: unknown[], near: Set, at: unknown) => boolean }).painted
@@ -25,14 +43,50 @@ describe('the paint of the near field', () => {
     });
 });
 
+describe('the quality', () => {
+    /** The qualities of the frames of a still view whose pages coarser than the meshes' need demand[q] slots at quality q, in a pool of `capacity`. */
+    const still = (demand: number[], capacity: number, from: number) => {
+        let state = { quality: from, calm: 0, held: false };
+        return Array.from({ length: 3 * CALM }, () => {
+            const q = state.quality;
+            state = stepQuality(state, demand[q] > capacity, true, false, () => q + 1 < demand.length && demand[q + 1] < demand[q], () => demand[q - 1] <= capacity);
+            return state.quality;
+        });
+    };
+
+    it('comes to a fixed quality for fixed pages and pools, and steps only where a step lowers the demand', () => {
+        // A usual screen: no step makes the range smaller, so the pages left out alone answer the shortage.
+        expect(still([90], 70, 0).every(q => q === 0)).toBe(true);
+        // A large screen: from either side, the finest quality whose demand fits, which then stays.
+        const demand = [120, 100, 80, 65, 60];
+        for (const from of [0, 2, 4]) expect(still(demand, 70, from).slice(5).every(q => q === 3)).toBe(true);
+        // A pool that no quality fits: the coarsest.
+        expect(still(demand, 50, 0).slice(5).every(q => q === 4)).toBe(true);
+    });
+});
+
 describe('the frames of a still view', () => {
-    const working = (quality: number) => Object.assign(Object.create(Terrain.prototype), {
-        pages: { idle: true, loads: 0, capacity: { stored: 100, synth: 100 }, wanted: { stored: 10, synth: 10 } }, stamps: { loading: false }, newContent: false, calm: 1, quality,
+    const working = (calm: number) => Object.assign(Object.create(Terrain.prototype), {
+        pages: { idle: true, loads: 0 }, stamps: { loading: false }, newContent: false, calm,
     }).working;
 
-    it('go on while the quality can rise, and end once it is at its best', () => {
-        expect(working(1)).toBe(true);
-        expect(working(0)).toBe(false);
+    it('go on for the frame after a quality step, in which a finer quality is tried, and then end', () => {
+        expect(working(0)).toBe(true);
+        expect(working(1)).toBe(false);
+    });
+});
+
+describe('the attach to a device', () => {
+    // Stops the attach at its first use of the device: what it does to the records comes before.
+    const recordsLost = async (resources: object | undefined) => {
+        const lost = vi.fn(), gpu = { get device(): never { throw new Error('no device'); } };
+        await expect(Terrain.prototype.attach.call({ resources, records: { lost }, pages: { lost() {} } } as never, gpu as never, {} as never)).rejects.toThrow('no device');
+        return lost.mock.calls.length;
+    };
+
+    it('keeps the records built before the first device, and drops those that a lost device held', async () => {
+        expect(await recordsLost(undefined)).toBe(0);
+        expect(await recordsLost({})).toBe(1);
     });
 });
 
diff --git a/builder/web/src/lib/trailview/terrain/terrain.ts b/builder/web/src/lib/trailview/terrain/terrain.ts
index a5cd43e254..5d1bc43b8b 100644
--- a/builder/web/src/lib/trailview/terrain/terrain.ts
+++ b/builder/web/src/lib/trailview/terrain/terrain.ts
@@ -4,33 +4,39 @@ import { VFOV } from '../frame/camera';
 import { CURVATURE, type Frame } from '../frame/frame';
 import { anchorAt, cubic, lodSpace, renderMap, UNITS, type Anchor } from '../frame/space';
 import type { Gpu } from '../gpu/device';
+import { hashBytes, hashRegions, type Region } from '../gpu/hashes';
 import { CLIP_DISTANCES } from '../gpu/include';
 import { layouts } from '../gpu/layouts';
 import { wgsl } from '../gpu/wgsl';
 import { PAGE } from '../stream/heights';
 import type { TerrainSource } from '../stream/terrain';
 import { DEPTH, sceneFormat } from '../resolve/targets';
-import { featureTile, NEAR, profileTable, waterAt } from './bins';
-import { cdlod, COARSEST, distances, EYE_M, FINEST, GRID, key, MAP, NEAR_M, RANGE, select, size, type Node, type Rule } from './lod';
-import { ARRIVALS, copies, MODE, NO_LIMIT, Pages, STAMP_WORDS, type Kind, type Page, type Stamp, type Work } from './pages';
-import { Stamps, type FeatureTiles } from './stamps';
+import { featureTile, NEAR, profileTable, STAMP_WORDS, waterAt } from './bins';
+import { CALM, cdlod, COARSEST, distances, EYE_M, FINEST, GRID, key, MAP, NEAR_M, RANGE, select, size, type Node, type Rule } from './lod';
+import { ARRIVALS, copies, MODE, NO_LIMIT, Pages, type Kind, type Page, type Stamp, type Work } from './pages';
+import { Stamps, type BakedNodes, type FeatureTiles } from './stamps';
 import { OPAQUE, Water } from './water';
 import type { RoadPiece } from '../roads/piece';
 import { Roads, type RoadStats } from '../roads/roads';
+import { Plan } from '../plan/plan';
+import { cellOf, MODEL_ROW, nearCells, Records, ROWS, type RecordsStats } from './model';
+import { CELLS_BYTES, COARSEST_MESH, meshCells, Pieces, stampNodes, type PiecesStats } from '../plan/pieces';
+import { CLIFF_JOB_BYTES, cliffJobs, packCliffJobs, type CliffJob } from './cliff';
 import { Structures } from '../structures/structures';
 import { BOX } from '../structures/node';
 
 /**
  * GPU memory for pages: the stored and the synthesized budgets for a laptop, in MiB. The feature masks
- * take their share of the synthesized budget. On a usual screen the range is the least, so the first
- * shortage of synthesized pages takes away the finest level, whose mesh alone holds a path's edges:
- * the pool holds what a frame wants at the least range, whichever way it looks.
+ * take their share of the synthesized budget. A shortage of synthesized pages leaves out the farthest
+ * pages of the finest level, and their parents draw in their place: the pool holds what a frame wants at
+ * the least range, whichever way it looks.
  */
 const BUDGET: Record = { stored: 104 * 2 ** 20, synth: 67 * 2 ** 20 };
 /**
  * Feature masks of the near pages, 4 bytes per texel: 32 MiB of the synthesized budget. The views of
  * the test box draw up to 106 near pages with features, and every one of them needs its mask: a
- * page without one draws its roads unpainted.
+ * page without one draws its roads unpainted. With `ground=plan`, each mask also has its paint (32 MiB in all),
+ * its moves (8 MiB) and its cliff share (8 MiB): 48 MiB more, outside both budgets.
  */
 const MASKS = 128, MASK_BYTES = PAGE * PAGE * MASKS * 4;
 /** 16-bit heights. */
@@ -45,8 +51,6 @@ const MAX_HOLES = 32;
 const MAX_NODES = 4096;
 /** The grid cell that a level has at the far end of its range, in pixels. */
 const CELL_PIXELS = 4;
-/** Frames without a shortage before the quality rises again, when each pool would still have room: the share that it fills at most. */
-const CALM = 120, ROOM = 0.6;
 /** Heights that a node of unknown range may have, and the margin about a known range: micro-relief and bicubic overshoot. */
 const ANY_HEIGHT: [number, number] = [-500, 9000];
 const MARGIN = 50;
@@ -58,10 +62,12 @@ const CHECKS = 64;
 const PROBE_STEP = 1;
 const READBACKS = 3;
 const RAD = Math.PI / 180;
+/** The workgroups of a cliff job, as ROW in cliff.wgsl. */
+const CLIFF_ROW = 32;
 /** Bytes of `Surface` and `Job` in the WGSL, and of a node instance. */
 const SURFACE_BYTES = 416, JOB_BYTES = 24, STAMP_JOB_BYTES = 32, NODE_BYTES = 16;
 /** A stamp job whose base is the synthesized page in `out`, as SYNTHESIZED in stamp.wgsl. */
-const SYNTHESIZED = 0xffffffff;
+export const SYNTHESIZED = 0xffffffff;
 /** Audit samples per run at most, words per sample, and words of results, as in audit.wgsl. */
 const SAMPLES = 2 ** 18, SAMPLE_WORDS = 12, COUNTS = 45, FOUND = 64;
 /** Cells per strip of the grid's index order. */
@@ -78,6 +84,8 @@ export interface View {
     viewProj: Float32Array;
     /** Pixels of the render target's height. */
     pixels: number;
+    /** The horizontal view direction in world units (x east, y south); undefined when the view looks nearly straight down or up. */
+    ahead?: [number, number];
 }
 
 export interface TerrainStats {
@@ -89,6 +97,8 @@ export interface TerrainStats {
     capacity: Record;
     /** 0 is the best; each step draws coarser to stay in the pools. */
     quality: number;
+    /** Per level, the pages that the last frame left out: they found no room in their pool. */
+    left: number[];
     /** The stamp jobs of the last frame: heights on near pages, heights on coarser pages (lakes), and masks only. */
     jobs: { near: number; coarse: number; masks: number };
     /** Masks in use. */
@@ -96,8 +106,13 @@ export interface TerrainStats {
     /** Water and structure meshes of the last frame that did not fit in their pools. */
     waterDropped: number;
     structuresDropped: number;
+    /** How often the stamp worker hit a limit of a node's stamps: it left a primitive out, or took a cell origin near a shore. */
+    stampLimits: number;
     /** The corridors of the last frame. */
     roads: RoadStats;
+    /** With `ground=plan`, the records on the device, and the meshes near the eye. */
+    records?: RecordsStats;
+    pieces?: PiecesStats;
 }
 
 /** What the audit counts, as audit.wgsl does. */
@@ -122,6 +137,12 @@ interface Resources extends Pipelines {
     mask: GPUTexture;
     masks: GPUBuffer;
     snaps: GPUTexture;
+    /** With `ground=plan`: the records, and per mask their paint and the move of their heights (stamp.wgsl), and the cliff share (cliff.wgsl). */
+    model: GPUTexture;
+    paint: GPUTexture;
+    moved: GPUTexture;
+    cliffShare: GPUTexture;
+    cliffJobs: GPUBuffer;
     stampJobs: GPUBuffer;
     stampData: GPUBuffer;
     profiles: GPUBuffer;
@@ -130,6 +151,8 @@ interface Resources extends Pipelines {
     scales: GPUBuffer;
     nodes: GPUBuffer;
     holes: GPUBuffer;
+    /** With `ground=plan`: the cells whose meshes draw, as plan/cells.wgsl reads them. */
+    cells: GPUBuffer;
     synthJobs: GPUBuffer;
     synthOut: GPUBuffer;
     extent: GPUBuffer;
@@ -147,6 +170,9 @@ interface Resources extends Pipelines {
     eyeGroup: GPUBindGroup;
     stampGroup: GPUBindGroup;
     snapGroup: GPUBindGroup;
+    /** The cliff pass: its jobs and output, and the feature mask without the cliff share, which it writes. */
+    cliffGroup: GPUBindGroup;
+    cliffFeatures: GPUBindGroup;
     featureGroup: GPUBindGroup;
     emptyGroup: GPUBindGroup;
     /** The draw of the nodes with a tunnel's portal, after `attachParts`: until then they draw without their hole. */
@@ -168,6 +194,13 @@ export class Terrain {
     private readonly structures: Structures;
     private readonly roads: Roads;
     private roadsFree = false;
+    /** The ground plan, only with `ground=plan`. */
+    readonly plan?: Plan;
+    /** The records that shape and paint the ways, and the meshes near the eye, only with `ground=plan`. */
+    private readonly records?: Records;
+    private readonly pieces?: Pieces;
+    /** The meshes' attach, which `attach` starts: they draw the view about the eye, so they compile beside the first frame. */
+    private piecesAttached?: Promise;
     /**
      * The probed ground under the eye at `lonLat`: NaN where no level knows it, a slope of 0 where no
      * level knows a point about it, and the frame that it comes from.
@@ -185,9 +218,14 @@ export class Terrain {
     private wantedNodes: Node[] = [];
     private work?: Work;
     private jobs = { near: 0, coarse: 0, masks: 0 };
+    /** With `ground=plan`: the frame's jobs of the cliff pass, and the mask layer and node of each page with a mask by name in the last frame. */
+    private cliffs: CliffJob[] = [];
+    private readonly masked = new Map();
     private anchor?: Anchor;
+    /** The quality, its calm frames, and whether it holds until the camera moves (stepQuality). */
     private quality = 0;
     private calm = 0;
+    private held = false;
     private selection = 0;
     private frameNumber = 0;
     private probing = 0;
@@ -206,23 +244,40 @@ export class Terrain {
     private lonLat: [number, number] = [0, 0];
     /** The camera of the last frame, for the audit: only what the frame shows counts. */
     private seen?: { viewProj: Float32Array; z: number; forward: Float64Array };
+    /** The anchor and the view projection of the last frame: the pages rank with a margin while they change. */
+    private camera: number[] = [];
     private floor = 0;
     private instances = new Int32Array(0);
     /** The road and path profiles, as stamp-core.wgsl reads them. */
     private readonly profileTable: Float32Array;
 
-    /** An abort of `stop` ends the stamp worker. */
-    constructor(private readonly frame: Frame, source: TerrainSource, features: FeatureTiles | undefined, bounds: Bounds, private readonly changed: () => void, stop: AbortSignal) {
+    /**
+     * An abort of `stop` ends the stamp worker. `plan` builds the ground plan; `finest` caps the finest level and `pool` scales
+     * the page pools (debug options). The stamps read the nodes that `baked` holds. `cache` names the data of the tiles and the
+     * versions of the stamp code and of the plan's input preparation, under which the nodes' stamps and the plan's cells are
+     * cached on the device.
+     */
+    constructor(private readonly frame: Frame, source: TerrainSource, features: FeatureTiles | undefined, bounds: Bounds, private readonly changed: () => void, stop: AbortSignal, plan = false, private readonly finest = FINEST, baked?: BakedNodes, cache?: { release: string; version: string; plan: string }, pool = 1) {
         const [west, north] = worldPixel([bounds[0], bounds[3]], UNITS), [east, south] = worldPixel([bounds[2], bounds[1]], UNITS);
         this.bounds = [west, north, east, south];
         // Whole layers inside the two budgets; the synthesized pool takes its share, the stored pool the rest.
         const pages = Math.floor((BUDGET.stored + BUDGET.synth - MASK_BYTES) / PAGE_BYTES / LAYER_PAGES) * LAYER_PAGES;
         this.profileTable = profileTable();
-        this.stamps = new Stamps(features, changed, stop);
-        this.roads = new Roads(features, (z, x, y) => this.pages.body(z, x, y), changed, stop);
+        this.stamps = new Stamps(features, changed, stop, plan, baked, plan ? cache : undefined);
+        // With the ground plan the records draw the ways: no corridor holds one.
+        this.roads = new Roads(plan ? undefined : features, (z, x, y) => this.pages.body(z, x, y), changed, stop);
+        if (plan) this.plan = new Plan(features, (z, x, y) => this.pages.body(z, x, y), this.bounds, changed, stop);
         this.water = new Water(this.stamps);
         this.structures = new Structures(this.stamps);
-        this.pages = new Pages(source, { stored: pages - SYNTH_PAGES, synth: SYNTH_PAGES }, this.bounds, changed, this.stamps, MASKS);
+        const pieces = this.pieces = plan ? new Pieces(node => this.stamps.get(node)?.data) : undefined;
+        const records = this.records = plan
+            ? new Records(features, (z, x, y) => this.pages.body(z, x, y), changed, stop, mesh => pieces!.add(mesh.node, mesh.bytes, mesh.block, mesh.mouths), node => pieces!.remove(node), cache && { release: cache.release, version: cache.plan })
+            : undefined;
+        // A near page waits for its cell's records. A page of the level that the meshes draw over also waits for its cell's mesh
+        // to hold its heights: until then the coarser page draws, never the far look up close.
+        const waits = (node: Node) => records!.waits(node) || (node.level === pieces!.level && (records!.meshComing(cellOf(node)) || pieces!.ready(cellOf(node)) === false));
+        const stamps = records ? { get: (node: Node) => (waits(node) ? undefined : this.stamps.get(node)), known: (node: Node) => (waits(node) ? undefined : this.stamps.known(node)) } : this.stamps;
+        this.pages = new Pages(source, { stored: Math.round(pool * (pages - SYNTH_PAGES)), synth: Math.round(pool * SYNTH_PAGES) }, this.bounds, changed, stamps, MASKS);
     }
 
     get idle(): boolean {
@@ -236,7 +291,7 @@ export class Terrain {
 
     /** Whether road meshes or feature tiles, which carry the structure meshes, are on their way. The view about the eye waits for none. */
     get meshesLoading(): boolean {
-        return this.roads.loading || this.stamps.loading;
+        return this.roads.loading || this.stamps.loading || (!!this.plan?.debug && this.plan.loading) || !!this.records?.loading || !!this.pieces?.loading;
     }
 
     /**
@@ -264,15 +319,10 @@ export class Terrain {
 
     /** True while the terrain needs frames that no tile load, feature tile or probe will ask for. */
     get working(): boolean {
-        // A frame that changed nothing while feature tiles are on their way waits for them. Only frames
-        // count the calm that raises the quality, so a still view goes on until it rises.
-        return (!this.pages.idle && this.pages.loads === 0 && (this.newContent || !this.stamps.loading)) || this.calm === 0 || this.raisable;
-    }
-
-    /** Whether the quality can rise: each pool would still have room. */
-    private get raisable(): boolean {
-        const { capacity, wanted } = this.pages;
-        return this.quality > 0 && wanted.stored < ROOM * capacity.stored && wanted.synth < ROOM * capacity.synth;
+        // A frame that changed nothing while feature tiles are on their way waits for them. A still view takes the frame after a
+        // quality step, in which a finer quality is tried (stepQuality). Only frames count the calm that brings the meshes back, so
+        // a still view goes on until they do.
+        return (!this.pages.idle && this.pages.loads === 0 && (this.newContent || !this.stamps.loading)) || this.calm === 0 || !!this.pieces?.returning;
     }
 
     /** A new view: a probe from before it never sets the ground. */
@@ -294,8 +344,10 @@ export class Terrain {
             if (page.mask !== undefined) masks++;
         }
         return {
-            nodes: this.nodes.length, triangles: 2 * GRID * GRID * this.nodes.length, selection: this.selection, resident, capacity: { ...this.pages.capacity }, quality: this.quality,
-            jobs: this.jobs, masks, waterDropped: this.water.dropped, structuresDropped: this.structures.dropped, roads: this.roads.stats,
+            nodes: this.nodes.length, triangles: 2 * GRID * GRID * this.nodes.length, selection: this.selection, resident, capacity: { ...this.pages.capacity }, quality: this.quality, left: [...this.pages.left],
+            jobs: this.jobs, masks, waterDropped: this.water.dropped, structuresDropped: this.structures.dropped, stampLimits: this.stamps.limits, roads: this.roads.stats,
+            ...(this.records ? { records: this.records.stats } : {}),
+            ...(this.pieces ? { pieces: this.pieces.stats } : {}),
         };
     }
 
@@ -335,34 +387,46 @@ export class Terrain {
      * again, from the kept tile bodies.
      */
     async attach(gpu: Gpu, frameUniform: GPUBuffer): Promise {
+        // Blocks go to a device only once it has resources: the cells built before the first attach upload at its first frame.
+        if (this.resources) this.records?.lost();
         this.resources = undefined;
         this.pages.lost();
         const { device } = gpu, pages = this.pages.capacity.stored + this.pages.capacity.synth;
         const layers = Math.ceil(pages / LAYER_PAGES), side = PAGE * Math.sqrt(LAYER_PAGES);
         const texels = PAGE * PAGE;
-        const usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST;
+        // COPY_SRC for the determinism check's reads (`hashes`).
+        const usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
         const heights = gpu.texture('pages', { size: [side, side, layers], format: 'r16uint', usage }, layers * side * side * 2);
         // The masks: written by the stamp pass, read by the shaders that draw.
         const mask = gpu.texture('features', {
-            size: [side, Math.ceil(Math.min(MASKS, LAYER_PAGES) / 8) * PAGE, Math.ceil(MASKS / LAYER_PAGES)], format: 'rgba8unorm', usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING,
+            size: [side, Math.ceil(Math.min(MASKS, LAYER_PAGES) / 8) * PAGE, Math.ceil(MASKS / LAYER_PAGES)], format: 'rgba8unorm', usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC,
         }, MASK_BYTES);
         const snaps = gpu.texture('features', {
-            size: [PAGE / 4, PAGE / 4, MASKS], format: 'r32uint', usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING,
+            size: [PAGE / 4, PAGE / 4, MASKS], format: 'r32uint', usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC,
         }, MASKS * SNAP_BYTES);
+        // The records, the paint of each mask in the mask's format, and the move of the heights, four texels of a row in one texel.
+        const plan = !!this.records, written = GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC;
+        const model = gpu.texture('records', { size: plan ? [MODEL_ROW, ROWS] : [1, 1], format: 'r32uint', usage }, plan ? MODEL_ROW * ROWS * 4 : 4);
+        const paint = gpu.texture('features', { size: plan ? [mask.width, mask.height, mask.depthOrArrayLayers] : [1, 1, 1], format: 'rgba8unorm', usage: written }, plan ? MASK_BYTES : 4);
+        const moved = gpu.texture('features', { size: plan ? [mask.width / 4, mask.height, mask.depthOrArrayLayers] : [1, 1, 1], format: 'rgba8unorm', usage: written }, plan ? MASK_BYTES / 4 : 4);
+        const cliffShare = gpu.texture('features', { size: [moved.width, moved.height, moved.depthOrArrayLayers], format: 'rgba8unorm', usage: written }, plan ? MASK_BYTES / 4 : 4);
         const storage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST;
         const buffer = (pool: string, bytes: number, usage: number) => gpu.buffer(pool, bytes, usage);
-        const r: Omit = {
+        const r: Omit = {
             gpu, heights,
-            mask, snaps,
+            mask, snaps, model, paint, moved, cliffShare,
+            // A page with a mask has one whole job or one toward each of its eight neighbours (cliffJobs).
+            cliffJobs: buffer('compute', (plan ? 8 * MASKS : 1) * CLIFF_JOB_BYTES, storage),
             masks: buffer('features', (2 + pages) * 4, storage),
             stampJobs: buffer('compute', ARRIVALS * STAMP_JOB_BYTES, storage),
             stampData: buffer('compute', STAMP_WORDS * 4, storage),
             profiles: buffer('compute', this.profileTable.byteLength, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST),
             surface: buffer('terrain', SURFACE_BYTES, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST),
             map: buffer('terrain', (FINEST + 1) * MAP * MAP * 4, storage),
-            scales: buffer('terrain', pages * 8, storage),
+            scales: buffer('terrain', pages * 8, storage | GPUBufferUsage.COPY_SRC),
             nodes: buffer('terrain', MAX_NODES * NODE_BYTES, storage),
             holes: buffer('terrain', (1 + 3 * MAX_HOLES) * 16, storage),
+            cells: buffer('plan', plan ? CELLS_BYTES : 256, storage),
             synthJobs: buffer('compute', ARRIVALS * JOB_BYTES, storage),
             synthOut: buffer('compute', ARRIVALS * texels * 4, GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC),
             extent: buffer('compute', ARRIVALS * 8, storage),
@@ -377,56 +441,77 @@ export class Terrain {
         device.queue.writeBuffer(r.profiles, 0, this.profileTable);
         device.queue.writeBuffer(r.scales, 0, new Float32Array(2 * pages).fill(1));
 
-        const L = gpu.once(terrainLayouts), { surface: surfaceLayout, features: featureLayout } = gpu.once(layouts), pipelines = await gpu.once(terrainPipelines);
+        const L = gpu.once(terrainLayouts), { surface: surfaceLayout, features: featureLayout } = gpu.once(layouts), pipelines = await gpu.once(terrainPipelines(plan));
+        this.masked.clear();
         const group = (layout: GPUBindGroupLayout, resources: GPUBindingResource[]) => device.createBindGroup({ layout, entries: resources.map((resource, binding) => ({ binding, resource })) });
         const view = (texture: GPUTexture) => texture.createView({ dimension: '2d-array' });
         // No mask yet, and a reach of the paint that no view meets.
         device.queue.writeBuffer(r.masks, 0, new Float32Array(2 + pages).fill(NO_LIMIT, 0, 1));
         this.resources = {
             ...r, ...pipelines,
-            stampGroup: group(L.stamp, [{ buffer: r.stampJobs }, { buffer: r.stampData }, { buffer: r.synthOut }, { buffer: r.extent }, { buffer: r.profiles }, view(r.mask)]),
+            stampGroup: device.createBindGroup({
+                layout: L.stamp, entries: [
+                    ...[{ buffer: r.stampJobs }, { buffer: r.stampData }, { buffer: r.synthOut }, { buffer: r.extent }, { buffer: r.profiles }, view(r.mask)].map((resource, binding) => ({ binding, resource })),
+                    { binding: 8, resource: r.model.createView() }, { binding: 9, resource: view(r.paint) }, { binding: 10, resource: view(r.moved) },
+                ],
+            }),
             snapGroup: device.createBindGroup({
                 layout: L.snap, entries: [{ binding: 0, resource: { buffer: r.stampJobs } }, { binding: 2, resource: { buffer: r.synthOut } }, { binding: 4, resource: { buffer: r.profiles } }, { binding: 6, resource: view(r.mask) }, { binding: 7, resource: view(r.snaps) }],
             }),
-            featureGroup: group(featureLayout, [{ buffer: r.masks }, view(r.mask), view(r.snaps)]),
+            cliffGroup: group(L.cliff, [{ buffer: r.cliffJobs }, view(r.cliffShare)]),
+            cliffFeatures: group(featureLayout, [{ buffer: r.masks }, view(r.mask), view(r.snaps), view(r.paint), view(r.moved), view(gpu.texture('features', { size: [1, 1, 1], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING }, 4))]),
+            featureGroup: group(featureLayout, [{ buffer: r.masks }, view(r.mask), view(r.snaps), view(r.paint), view(r.moved), view(r.cliffShare)]),
             emptyGroup: group(L.empty, []),
             surfaceGroup: group(surfaceLayout, [{ buffer: r.surface }, { buffer: r.map }, heights.createView({ dimension: '2d-array' }), { buffer: r.scales }, device.createSampler()]),
-            meshGroup: group(L.mesh, [{ buffer: frameUniform }, { buffer: r.nodes }, { buffer: r.holes }]),
+            meshGroup: group(L.mesh, [{ buffer: frameUniform }, { buffer: r.nodes }, { buffer: r.holes }, { buffer: r.cells }]),
             synthGroup: group(L.job, [{ buffer: r.synthJobs }, { buffer: r.synthOut }, { buffer: r.extent }]),
             quantizeGroup: group(L.quantize, [{ buffer: r.synthJobs }, { buffer: r.synthOut }, { buffer: r.extent }, { buffer: r.codes }, { buffer: r.scales }]),
             probeGroup: group(L.probe, [{ buffer: r.points }, { buffer: r.probed }]),
             eyeGroup: device.createBindGroup({ layout: L.eye, entries: [{ binding: 2, resource: { buffer: frameUniform } }] }),
         };
+        this.piecesAttached = this.pieces?.attach(gpu, frameUniform, r.cells, model, r.profiles);
+        // `attachParts` reports a failure.
+        this.piecesAttached?.catch(() => {});
     }
 
     /**
      * Takes the water, the structures and the holes of the tunnels' portals on the device of `attach`:
      * they draw once compiled. `frames` are the frame uniforms of the eye's view and of the sun's, whose
-     * casters draw into the shadow map.
+     * casters draw into the shadow map. It also waits for the meshes that `attach` started.
      */
     async attachParts(frames: GPUBuffer[]): Promise {
         const r = this.resources!;
         await Promise.all([
-            this.water.attach(r.gpu, frames[0], r.nodes), this.structures.attach(r.gpu, frames, r.holes), this.roads.attach(r.gpu, frames),
-            r.gpu.once(holedPipeline).then(pipeline => void (r.holedMesh = pipeline)),
+            this.water.attach(r.gpu, frames[0], r.nodes, r.cells), this.structures.attach(r.gpu, frames, r.holes, r.cells), this.roads.attach(r.gpu, frames), this.piecesAttached,
+            r.gpu.once(this.records ? planHoledPipeline : holedPipeline).then(pipeline => void (r.holedMesh = pipeline)),
         ]);
+        this.pieces?.castWith(frames[1]);
     }
 
     /**
      * Selects the nodes for a view and takes the pages that they want, and the pages of `reads`, which
-     * the ground's relief reads. A frame that wants more pages than a pool holds draws coarser from the
-     * next frame on: quality goes down before memory goes up.
+     * the ground's relief reads. A page that finds no room in its pool is left out, the finest and
+     * farthest first (Pages.fit), and the coarser page draws in its place; the quality goes down only
+     * as `stepQuality` has it. Before `attach` it only asks for the records and the stamps of the meshes,
+     * so that their workers start before the device draws.
      */
     update(view: View, reads: Node[] = []): void {
         const r = this.resources;
-        if (!r) return;
-        this.frameNumber++;
         const anchor = anchorAt(...view.lonLat), eye = { anchor, above: view.above };
         const rule = this.rule(eye, view.pixels);
         const forward = renderMap(this.frame, anchor);
         const start = performance.now();
         const { nodes, wanted } = select(rule, this.bounds, node => this.visible(node, eye, forward, view));
         this.selection = performance.now() - start;
+        // Below COARSEST_MESH the meshes rest: their cells stay, but build after the target and wish for no stamp.
+        const meshes = this.pieces ? meshCells(rule, eye) : [], resting = rule.finest < COARSEST_MESH;
+        if (this.records) {
+            const ground = { anchor, above: 0 };
+            this.records.update(nearCells(wanted, ground), meshes, resting, node => distances(ground, node)[0]);
+            for (const cell of this.records.takeChanged()) this.pages.restamp(cell);
+        }
+        if (!r) return this.sendStamps(resting ? [] : meshes, eye, forward, view);
+        this.frameNumber++;
         const ex = anchor.whole[0] + anchor.part[0], ey = anchor.whole[1] + anchor.part[1];
         const far = (node: Node) => Math.hypot((node.x + 0.5) * size(node.level) - ex, (node.y + 0.5) * size(node.level) - ey) / size(node.level);
         const order = (a: Node, b: Node) => a.level - b.level || far(a) - far(b), keys = new Set(wanted.map(key));
@@ -436,11 +521,13 @@ export class Terrain {
         const nearField = new Set(field(NEAR_M).map(key));
         // The eye field: its nodes and the parents that they morph toward.
         const eyeField = new Set(field(EYE_M).flatMap(({ level, x, y }) => [key({ level, x, y }), key({ level: level - 1, x: x >> 1, y: y >> 1 })]).filter(name => keys.has(name)));
-        const work = this.pages.update([...wanted, ...reads.filter(node => !keys.has(key(node)))].sort(order), anchor, nearField, eyeField);
+        const camera = [...anchor.whole, ...anchor.part, ...view.viewProj], moving = camera.some((v, i) => v !== this.camera[i]);
+        this.camera = camera;
+        const work = this.pages.update([...wanted, ...reads.filter(node => !keys.has(key(node)))].sort(order), anchor, nearField, eyeField, moving);
         // After the update, so that a page draws in the frame that it arrives in. The nodes that draw the
         // detail of the look come first, those with a tunnel's portal first of all, with its hole. A node
-        // coarser than NEAR draws without the detail only when its distance keeps it from splitting: a
-        // shortage can make a coarser level the finest, under the eye. Each pipeline draws near to far,
+        // coarser than NEAR draws without the detail only when its distance keeps it from splitting: the
+        // option `finest` can make a coarser level the finest, under the eye. Each pipeline draws near to far,
         // so that a GPU without hidden-surface removal shades few hidden fragments.
         const drawn = nodes.slice(0, MAX_NODES).filter(node => this.pages.covers(node));
         const group = drawn.map(node => (node.level < Math.min(NEAR, rule.finest) ? 2 : this.stamps.known(node)?.portals ? 0 : 1)), near = drawn.map(node => distances(eye, node)[0]);
@@ -454,13 +541,19 @@ export class Terrain {
         // The first view about the eye comes first: until then a road's worker would take its share of the CPU.
         this.roadsFree ||= this.eye || this.pages.idle;
         const roads = this.roads.update({ x: ex, y: ey, unit: anchor.unit }, piece => this.boxVisible(piece, eye, forward, view), this.roadsFree);
-        if (this.pages.shortage > 0) {
-            this.quality++;
-            this.calm = 0;
-        } else if (++this.calm > CALM && this.raisable) {
-            this.quality--;
-            this.calm = 0;
-        }
+        // GP5's plan builds only for its debug draw: the records' workers build every cell for the far look and the meshes.
+        const planned = (this.plan?.debug && this.plan.update({ x: ex, y: ey, unit: anchor.unit, above: view.above }, view.ahead, this.roadsFree)) || false;
+        const records = this.records;
+        // The corners read the drawn and the raw stored heights of the finest level and coarser: the LOD map changes with them.
+        const meshed = !!records && !!this.pieces?.update(rule, eye, node => records.block(node), (box, stored) => this.pages.reads(box, FINEST, stored), work.touched,
+            node => this.visible(node, eye, forward, view), node => records.settled(node), cell => this.pages.fallback(cell, rule.finest) < COARSEST_MESH);
+        // The slots per pool that the pages coarser than the meshes' levels need at a quality, from its own selection.
+        const coarse = (quality: number) => this.pages.demand([...select(this.rule(eye, view.pixels, quality), this.bounds, node => this.visible(node, eye, forward, view)).wanted, ...reads],
+            anchor, COARSEST_MESH);
+        const short = this.pages.left.some((pages, level) => pages > 0 && level < COARSEST_MESH), { capacity } = this.pages;
+        ({ quality: this.quality, calm: this.calm, held: this.held } = stepQuality({ quality: this.quality, calm: this.calm, held: this.held }, short, this.pages.missing === 0, moving,
+            () => this.quality < qualitySteps(view.pixels) && lowers(coarse(this.quality), coarse(this.quality + 1), capacity),
+            () => fits(coarse(this.quality - 1), capacity)));
         const probeReads = this.probeKey(rule, anchor);
         if (probeReads !== this.probeReads) {
             this.probeReads = probeReads;
@@ -468,6 +561,8 @@ export class Terrain {
             this.changedAt = this.frameNumber;
         }
         this.work = work;
+        // The masks and the LOD map change together with every change of a page's heights or mask.
+        this.cliffs = this.records && work.masks ? cliffJobs(this.pages.pages, this.masked, work.touched) : [];
         this.nearDrawn = this.pages.nearMissing === 0 && this.painted(nodes, nearField, anchor);
         this.eyeDrawn = this.pages.eyeMissing === 0 && this.painted(nodes, eyeField, anchor);
         this.jobs = { near: 0, coarse: 0, masks: 0 };
@@ -478,7 +573,27 @@ export class Terrain {
         this.seen = view.z === undefined ? undefined : { viewProj: view.viewProj, z: view.z, forward };
         const level = { anchor, above: 0 }, pages = [...work.uploads, ...work.syntheses, ...work.stamps.filter(({ mode }) => mode & MODE.HEIGHTS)];
         this.reshaped = structures ? 0 : Math.min(this.roads.arrived, ...pages.map(({ page }) => distances(level, page.node)[0]));
-        this.newContent = this.write(r, anchor, rule, forward, work, view.above) || water || structures || roads || !!(work.map || work.masks || work.uploads.length || work.syntheses.length || work.stamps.length);
+        this.newContent = this.write(r, anchor, rule, forward, work, view.above) || water || structures || roads || planned || meshed || !!(work.map || work.masks || work.uploads.length || work.syntheses.length || work.stamps.length);
+        this.sendStamps(resting ? [] : meshes, eye, forward, view);
+    }
+
+    /**
+     * One near-first order for the stamp worker: every wish within EYE_M and the nodes that the meshes in view read, then every
+     * other wish, each by its distance from the eye. The coarse pages over the eye count, as they draw until the eye's own do. A
+     * mesh's nodes are wished for before it comes, so its corners need not wait; those of a mesh out of view wait their turn.
+     */
+    private sendStamps(meshes: { node: Node }[], eye: { anchor: Anchor; above: number }, forward: Float64Array, view: View): void {
+        const shown = new Set(), hidden = new Set(), level = { anchor: eye.anchor, above: 0 };
+        for (const { node: cell } of meshes) {
+            if (this.pieces!.ready(cell)) continue;
+            const nodes = this.visible(cell, eye, forward, view) ? shown : hidden;
+            for (const node of stampNodes(cell)) {
+                this.stamps.get(node);
+                nodes.add(key(node));
+            }
+        }
+        const first = (name: string, node: Node) => shown.has(name) || (!hidden.has(name) && distances(level, node)[0] <= EYE_M);
+        this.stamps.send(node => (first(key(node), node) ? 0 : NO_LIMIT) + distances(eye, node)[0]);
     }
 
     /**
@@ -521,6 +636,19 @@ export class Terrain {
                 { buffer: r.codes, offset: k * texels * 2, bytesPerRow: PAGE * 2 },
                 { texture: r.heights, origin: origin(slot) }, [PAGE, PAGE, 1]));
         }
+        // After the heights and the moves of the frame's pages: the cliff share reads them about each texel.
+        if (this.cliffs.length && r.cliff) {
+            const pass = encoder.beginComputePass({ label: 'cliff', timestampWrites: time('cliff') });
+            pass.setPipeline(r.cliff);
+            pass.setBindGroup(0, r.cliffGroup);
+            pass.setBindGroup(1, r.surfaceGroup);
+            pass.setBindGroup(2, r.emptyGroup);
+            pass.setBindGroup(3, r.cliffFeatures);
+            pass.dispatchWorkgroups(CLIFF_ROW, 1, this.cliffs.length);
+            pass.end();
+        }
+        // After the pages: the meshes' corners read the stored pages and the records.
+        if (this.anchor) this.pieces?.encode(encoder, r.surfaceGroup, { anchor: this.anchor, above: this.above }, () => time('pieces'));
         const state = `${this.anchor?.whole}/${this.anchor?.part}/${this.above}/${this.quality}/${this.changes}`;
         const readback = state === this.probed ? undefined : r.readbacks.pop();
         if (!readback) return () => {};
@@ -574,24 +702,27 @@ export class Terrain {
         pass.end();
     }
 
-    /** Draws the structures into the shadow map (light/shadow.ts) as casters. */
+    /** Draws the structures and the ground plan's storeys into the shadow map (light/shadow.ts) as casters. */
     cast(pass: GPURenderPassEncoder): void {
         const r = this.resources;
         if (!r) return;
         this.structures.cast(pass, r.surfaceGroup, r.featureGroup);
         this.roads.cast(pass, r.surfaceGroup);
+        this.pieces?.cast(pass, r.surfaceGroup, r.emptyGroup, r.featureGroup);
     }
 
-    draw(pass: GPURenderPassEncoder, ground: GPUBindGroup): void {
+    /** With `owned` (the debug view), only the meshes and the terrain draw. */
+    draw(pass: GPURenderPassEncoder, ground: GPUBindGroup, owned = false): void {
         const r = this.resources;
         if (!r || !this.nodes.length) return;
         const { detailed, holed } = this;
         // Before the terrain: the terrain that they hide fails the depth test, also on a GPU without
         // hidden-surface removal, where the draw order decides what early-Z rejects. The ribbons blend
         // over the terrain.
-        this.structures.draw(pass, r.surfaceGroup, ground, r.featureGroup);
-        this.roads.draw(pass, r.surfaceGroup, ground, r.featureGroup);
-        this.water.draw(pass, r.surfaceGroup, ground, r.featureGroup, OPAQUE);
+        if (!owned) this.structures.draw(pass, r.surfaceGroup, ground, r.featureGroup);
+        if (!owned) this.roads.draw(pass, r.surfaceGroup, ground, r.featureGroup);
+        this.pieces?.draw(pass, r.surfaceGroup, ground, r.featureGroup);
+        if (!owned) this.water.draw(pass, r.surfaceGroup, ground, r.featureGroup, OPAQUE);
         pass.setBindGroup(0, r.meshGroup);
         pass.setBindGroup(1, r.surfaceGroup);
         pass.setBindGroup(2, ground);
@@ -603,7 +734,7 @@ export class Terrain {
         if (detailed > holed) pass.drawIndexed(GRID_INDICES.length, detailed - holed, 0, 0, holed);
         pass.setPipeline(r.farMesh);
         if (detailed < this.nodes.length) pass.drawIndexed(GRID_INDICES.length, this.nodes.length - detailed, 0, 0, detailed);
-        this.water.draw(pass, r.surfaceGroup, ground, r.featureGroup, ['ribbons']);
+        if (!owned) this.water.draw(pass, r.surfaceGroup, ground, r.featureGroup, ['ribbons']);
     }
 
     /**
@@ -795,11 +926,9 @@ export class Terrain {
         return clip[2] > 0 && Math.abs(clip[0]) < 0.98 * clip[2] && Math.abs(clip[1]) < 0.98 * clip[2];
     }
 
-    private rule(eye: { anchor: Anchor; above: number }, pixels: number): Rule {
-        // The range at which a level's grid cell spans CELL_PIXELS, a quarter step smaller per quality step.
-        const best = Math.min(RANGE.most, Math.max(RANGE.least, pixels / (2 * Math.tan(VFOV * RAD / 2)) / (GRID * CELL_PIXELS)));
-        const steps = Math.ceil(4 * Math.log2(best / RANGE.least));
-        return cdlod(eye, Math.max(RANGE.least, best * 2 ** (-this.quality / 4)), FINEST - Math.max(0, this.quality - steps));
+    /** The rule at a quality: each step makes the range a quarter step smaller, down to the least. No step lowers the finest level. */
+    private rule(eye: { anchor: Anchor; above: number }, pixels: number, quality = this.quality): Rule {
+        return cdlod(eye, Math.max(RANGE.least, bestRange(pixels) * 2 ** (-quality / 4)), this.finest);
     }
 
     /** Whether a node's box can show: render space corners at its range of heights, against the frustum. */
@@ -829,8 +958,8 @@ export class Terrain {
         return planes.every(plane => points.some(([x, y, z]) => plane[0] * x + plane[1] * y + plane[2] * z + plane[3] >= 0));
     }
 
-    private writeStamps(r: Resources, stamps: Stamp[]): void {
-        const { jobs, data } = stampJobs(stamps);
+    private writeStamps(r: Resources, work: Work): void {
+        const { jobs, data } = stampJobs(work.stamps, new Set(work.syntheses.map(({ page }) => page)));
         r.gpu.device.queue.writeBuffer(r.stampJobs, 0, jobs);
         if (data.length) r.gpu.device.queue.writeBuffer(r.stampData, 0, data);
     }
@@ -859,6 +988,39 @@ export class Terrain {
         return out.join();
     }
 
+    /**
+     * The determinism check: per drawn page in the LOD map a hash of its heights and their scale (`h/`) and of its mask,
+     * paint, move and snaps (`m/`), per records block (`r/`), per piece the corners that the pass made (`p/`)
+     * and its mesh from the worker (`w/`), with the
+     * state of the last frame. Call it after `waitForIdle()`.
+     */
+    async hashes(): Promise> {
+        const r = this.resources;
+        if (!r) throw new Error('The hashes read after the first frame.');
+        const regions: Region[] = [];
+        const layer = (texture: GPUTexture, slot: number, texelBytes: number, name: string, width = PAGE) =>
+            regions.push({ name, texture, origin: [width * (slot & 7), PAGE * ((slot >> 3) & 7), slot >> 6], size: [width, PAGE], texelBytes });
+        for (const [name, page] of this.pages.pages) {
+            if (page.drawn === undefined || !page.ready) continue;
+            layer(r.heights, page.drawn, 2, `h/${name}`);
+            regions.push({ name: `h/${name}`, buffer: r.scales, offset: 8 * page.drawn, bytes: 8 });
+            if (page.mask === undefined) continue;
+            layer(r.mask, page.mask, 4, `m/${name}`);
+            regions.push({ name: `m/${name}`, texture: r.snaps, origin: [0, 0, page.mask], size: [PAGE / 4, PAGE / 4], texelBytes: 4 });
+            if (!this.records) continue;
+            layer(r.paint, page.mask, 4, `m/${name}`);
+            layer(r.moved, page.mask, 4, `m/${name}`, PAGE / 4);
+            layer(r.cliffShare, page.mask, 4, `m/${name}`, PAGE / 4);
+        }
+        for (const { name, first, rows } of this.records?.blocks() ?? []) regions.push({ name: `r/${name}`, texture: r.model, origin: [0, first, 0], size: [MODEL_ROW, rows], texelBytes: 4 });
+        const meshes: Record = {};
+        for (const { name, mesh, buffer, offset, bytes } of this.pieces?.buffers() ?? []) {
+            regions.push({ name: `p/${name}`, buffer, offset, bytes });
+            meshes[`w/${name}`] = hashBytes([mesh.corners, mesh.steps, mesh.triangles, mesh.sunk]);
+        }
+        return { ...(await hashRegions(r.gpu.device, regions)), ...meshes };
+    }
+
     /** Writes the frame's buffers; true when the drawn nodes differ from the last frame's. */
     private write(r: Resources, anchor: Anchor, rule: Rule, forward: Float64Array, work: Work, above: number): boolean {
         const { device } = r.gpu;
@@ -883,37 +1045,81 @@ export class Terrain {
             ...work.syntheses.map(({ page, stored }) => ({ page, stored, slot: page.slot, stamped: heightsOf.has(page) })),
             ...copies(work).map(({ page, target }) => ({ page, stored: 0, slot: target, stamped: true })),
         ]));
-        if (work.stamps.length) this.writeStamps(r, work.stamps);
+        if (work.stamps.length) this.writeStamps(r, work);
+        if (this.cliffs.length) device.queue.writeBuffer(r.cliffJobs, 0, packCliffJobs(this.cliffs));
         device.queue.writeBuffer(r.extent, 0, new Uint32Array(2 * ARRIVALS).map((_, i) => (i % 2 ? 0 : 0xffffffff)));
         const instances = new Int32Array(4 * this.nodes.length);
         this.nodes.forEach(({ level, x, y }, i) => instances.set([x * size(level) - anchor.whole[0], y * size(level) - anchor.whole[1], level, 0], 4 * i));
         device.queue.writeBuffer(r.nodes, 0, instances);
-        device.queue.writeBuffer(r.holes, 0, holes(this.boxes, anchor));
+        // After the structures' upload: a portal opens the ground only where its owner's bore and facade draw in this frame.
+        this.structures.write();
+        device.queue.writeBuffer(r.holes, 0, holes(this.boxes, anchor, (x, y) => this.structures.holds(x, y)));
         const changed = instances.length !== this.instances.length || instances.some((v, i) => v !== this.instances[i]);
         this.instances = instances;
         this.water.write();
-        this.structures.write();
         device.queue.writeBuffer(r.masks, 4, new Float32Array([this.roads.write()]));
+        this.records?.write(device, r.model, [anchor.whole[0] + anchor.part[0], anchor.whole[1] + anchor.part[1]]);
+        this.pieces?.write({ anchor, above });
         return changed;
     }
 }
 
+/** The range at which a level's grid cell spans CELL_PIXELS on a render target `pixels` high, within RANGE. */
+const bestRange = (pixels: number) => Math.min(RANGE.most, Math.max(RANGE.least, pixels / (2 * Math.tan(VFOV * RAD / 2)) / (GRID * CELL_PIXELS)));
+
+/** The quality steps that make the range smaller: 0 on a usual screen, whose best range is the least already. */
+const qualitySteps = (pixels: number) => Math.ceil(4 * Math.log2(bestRange(pixels) / RANGE.least));
+
+/** Whether a demand of slots per pool lowers that of `now` in every pool that `now` overfills. */
+const lowers = (now: Record, next: Record, capacity: Record) =>
+    (['stored', 'synth'] as const).some(kind => now[kind] > capacity[kind]) && (['stored', 'synth'] as const).every(kind => now[kind] <= capacity[kind] || next[kind] < now[kind]);
+
+/** Whether a demand of slots per pool fits in the pools. */
+const fits = (demand: Record, capacity: Record) => demand.stored <= capacity.stored && demand.synth <= capacity.synth;
+
+/** The quality, its calm frames, and whether it holds until the camera moves. */
+export interface QualityState { quality: number; calm: number; held: boolean }
+
+/**
+ * The quality after a frame. The pages of the meshes' levels leave a page at a time (Pages.fit), and those of coarser levels
+ * too; a quality step makes the range of every level smaller (`rule`). It steps down when a page of a coarser level than
+ * the meshes' was left out (`short`) once the pages that fit are in (`settled`: while pages load, their ranges are not known
+ * and the selection is wider), and only where the step lowers the demand of the pool that is short (`lowers`). It steps up
+ * after CALM frames, or at once in a still view whose pages are in, where the demand of the finer quality fits (`fits`);
+ * where it does not, it holds until the camera moves. Down needs a demand that does not fit, up one that fits: for fixed
+ * pages and pools the quality comes to a fixed point, and a still view's frames stop. `lowers` and `fits` select at another
+ * quality, so they run only then.
+ */
+export function stepQuality({ quality, calm, held }: QualityState, short: boolean, settled: boolean, moving: boolean, lowers: () => boolean, fits: () => boolean): QualityState {
+    held &&= !moving;
+    if (short && settled && lowers()) return { quality: quality + 1, calm: 0, held: false };
+    if (!short && quality > 0 && !held && (calm >= CALM || (settled && !moving))) return fits() ? { quality: quality - 1, calm: 0, held: false } : { quality, calm: 0, held: true };
+    return { quality, calm: calm + 1, held };
+}
+
 /** The terrain's own bind group layouts; groups 1 to 3 are those of gpu/layouts.ts. */
 function terrainLayouts({ device }: Gpu) {
     const layout = (entries: [GPUShaderStageFlags, Omit][]) =>
         device.createBindGroupLayout({ entries: entries.map(([visibility, entry], binding) => ({ binding, visibility, ...entry })) });
     const read: GPUBufferBindingLayout = { type: 'read-only-storage' }, write: GPUBufferBindingLayout = { type: 'storage' }, C = GPUShaderStage.COMPUTE;
     return {
-        mesh: layout([[GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, { buffer: { type: 'uniform' } }], [GPUShaderStage.VERTEX, { buffer: read }], [GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, { buffer: read }]]),
+        // The plan cells (binding 3) also in the fragment stage, for the debug view `owned`.
+        mesh: layout([[GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, { buffer: { type: 'uniform' } }], [GPUShaderStage.VERTEX, { buffer: read }], [GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, { buffer: read }], [GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT, { buffer: read }]]),
         job: layout([[C, { buffer: read }], [C, { buffer: write }], [C, { buffer: write }]]),
         quantize: layout([[C, { buffer: read }], [C, { buffer: read }], [C, { buffer: read }], [C, { buffer: write }], [C, { buffer: write }]]),
         probe: layout([[C, { buffer: read }], [C, { buffer: write }]]),
         eye: device.createBindGroupLayout({ entries: [{ binding: 2, visibility: C, buffer: write }] }),
         check: layout([[GPUShaderStage.VERTEX, { buffer: read }]]),
-        stamp: layout([
-            [C, { buffer: read }], [C, { buffer: read }], [C, { buffer: write }], [C, { buffer: write }], [C, { buffer: { type: 'uniform' } }],
-            [C, { storageTexture: { format: 'rgba8unorm', viewDimension: '2d-array' } }],
-        ]),
+        stamp: device.createBindGroupLayout({
+            entries: [
+                ...[read, read, write, write, { type: 'uniform' } as const].map((buffer, binding) => ({ binding, visibility: C, buffer })),
+                ...[5, 9, 10].map(binding => ({ binding, visibility: C, storageTexture: { format: 'rgba8unorm', viewDimension: '2d-array' } as const })),
+                { binding: 8, visibility: C, texture: { sampleType: 'uint' } },
+            ],
+        }),
+        cliff: device.createBindGroupLayout({
+            entries: [{ binding: 0, visibility: C, buffer: read }, { binding: 1, visibility: C, storageTexture: { format: 'rgba8unorm', viewDimension: '2d-array' } }],
+        }),
         snap: device.createBindGroupLayout({
             entries: [
                 { binding: 0, visibility: C, buffer: read }, { binding: 2, visibility: C, buffer: write }, { binding: 4, visibility: C, buffer: { type: 'uniform' } }, { binding: 6, visibility: C, texture: { sampleType: 'float', viewDimension: '2d-array' } },
@@ -930,18 +1136,21 @@ function terrainLayouts({ device }: Gpu) {
 const shader = ({ device }: Gpu, file: string) => device.createShaderModule({ label: file, code: wgsl(`terrain/${file}.wgsl`, device.features.has('clip-distances') ? CLIP_DISTANCES : {}) });
 
 /** A compute pipeline of a terrain shader, whose groups take the layouts `groups`. */
-function compute(gpu: Gpu, file: string, entryPoint: string, groups: GPUBindGroupLayout[]): Promise {
-    return gpu.device.createComputePipelineAsync({ label: entryPoint, layout: gpu.device.createPipelineLayout({ bindGroupLayouts: groups }), compute: { module: shader(gpu, file), entryPoint } });
+function compute(gpu: Gpu, file: string, entryPoint: string, groups: GPUBindGroupLayout[], constants?: Record): Promise {
+    return gpu.device.createComputePipelineAsync({ label: entryPoint, layout: gpu.device.createPipelineLayout({ bindGroupLayouts: groups }), compute: { module: shader(gpu, file), entryPoint, constants } });
 }
 
-/** The draw of the nodes: with the detail of the look (DETAIL of look.wgsl), without it (the far nodes), or with the holes of the tunnels' portals. */
-function meshPipeline(gpu: Gpu, detail: boolean, holes = false): Promise {
+/**
+ * The draw of the nodes: with the detail of the look (DETAIL of look.wgsl), without it (the far nodes), or with the holes of the tunnels' portals;
+ * with `model` the records' look (`ground=plan`).
+ */
+function meshPipeline(gpu: Gpu, detail: boolean, holes = false, model = false): Promise {
     const { device } = gpu, L = gpu.once(terrainLayouts), shared = gpu.once(layouts), module = shader(gpu, 'terrain');
     return device.createRenderPipelineAsync({
         label: holes ? 'terrain with holes' : detail ? 'terrain' : 'far terrain',
         layout: device.createPipelineLayout({ bindGroupLayouts: [L.mesh, shared.surface, shared.ground, shared.features] }),
-        vertex: { module, entryPoint: 'vertex_main', constants: { HOLES: holes ? 1 : 0 } },
-        fragment: { module, entryPoint: 'fragment_main', targets: [{ format: sceneFormat(gpu) }], constants: { DETAIL: detail ? 1 : 0, HOLES: holes ? 1 : 0 } },
+        vertex: { module, entryPoint: 'vertex_main', constants: { HOLES: holes ? 1 : 0, PLAN: model ? 1 : 0 } },
+        fragment: { module, entryPoint: 'fragment_main', targets: [{ format: sceneFormat(gpu) }], constants: { DETAIL: detail ? 1 : 0, HOLES: holes ? 1 : 0, MODEL: model ? 1 : 0 } },
         // The far nodes cull back faces: no snap moves their vertices, so no triangle turns over, and a
         // ray from an eye above them meets a front face first. The other nodes draw both faces:
         // the eye can be under the near mesh for some frames, and its underside then hides what is behind.
@@ -950,25 +1159,31 @@ function meshPipeline(gpu: Gpu, detail: boolean, holes = false): Promise>;
+type Pipelines = Awaited>;
+
+/** What the terrain draws and computes with from its first frame; with `plan`, with the records' heights and look (`ground=plan`). */
+export const terrainPipelines = (plan: boolean) => (plan ? planPipelines : basePipelines);
+const basePipelines = (gpu: Gpu) => pipelines(gpu, false);
+const planPipelines = (gpu: Gpu) => pipelines(gpu, true);
 
-/** What the terrain draws and computes with from its first frame. */
-export async function terrainPipelines(gpu: Gpu) {
+async function pipelines(gpu: Gpu, model: boolean) {
     const L = gpu.once(terrainLayouts), { surface, features } = gpu.once(layouts);
-    const [mesh, farMesh, synthesize, quantize, probe, clampEye, stamp, snap] = await Promise.all([
-        meshPipeline(gpu, true), meshPipeline(gpu, false),
+    const [mesh, farMesh, synthesize, quantize, probe, clampEye, stamp, snap, cliff] = await Promise.all([
+        meshPipeline(gpu, true, false, model), meshPipeline(gpu, false, false, model),
         compute(gpu, 'pages', 'synthesize', [L.job, surface]),
         compute(gpu, 'quantize', 'quantize', [L.quantize]),
         compute(gpu, 'probe', 'probe', [L.probe, surface, L.empty, features]),
         compute(gpu, 'probe', 'clamp_eye', [L.eye, surface, L.empty, features]),
-        compute(gpu, 'stamp', 'stamp', [L.stamp, surface]),
+        compute(gpu, 'stamp', 'stamp', [L.stamp, surface], { MODEL: model ? 1 : 0 }),
         compute(gpu, 'stamp', 'snap', [L.snap, surface]),
+        model ? compute(gpu, 'cliff', 'cliff', [L.cliff, surface, L.empty, features]) : undefined,
     ]);
-    return { mesh, farMesh, synthesize, quantize, probe, clampEye, stamp, snap };
+    return { mesh, farMesh, synthesize, quantize, probe, clampEye, stamp, snap, cliff };
 }
 
 /** The draw of the nodes with a tunnel's portal, with its hole. */
 const holedPipeline = (gpu: Gpu) => meshPipeline(gpu, true, true);
+const planHoledPipeline = (gpu: Gpu) => meshPipeline(gpu, true, true, true);
 
 /** The check's draw and the probe of the share of the sun: only tests check. */
 function checkPipelines(gpu: Gpu): Promise<[GPURenderPipeline, GPUComputePipeline]> {
@@ -996,13 +1211,16 @@ function auditPipelines(gpu: Gpu): Promise {
     return Promise.all(['audit', 'apron'].map(entry => compute(gpu, 'audit', entry, [L.audit, surface, L.empty, features])));
 }
 
-/** The portals' boxes as `holes` of terrain.wgsl reads them, about the anchor; each box once, MAX_HOLES at most. */
-function holes(lists: Float64Array[], anchor: Anchor): Float32Array {
+/**
+ * The portals' boxes as `holes` of terrain.wgsl reads them, about the anchor; each box once, MAX_HOLES at most. A box
+ * whose facade middle is not `drawn` is left out: without its bore and facade the ground stays closed.
+ */
+function holes(lists: Float64Array[], anchor: Anchor, drawn: (x: number, y: number) => boolean): Float32Array {
     const out = new Float32Array(4 * (1 + 3 * MAX_HOLES)), seen = new Set();
     let n = 0;
     for (const list of lists) for (let i = 0; i < list.length && n < MAX_HOLES; i += BOX) {
         const name = `${list[i]},${list[i + 1]}`;
-        if (seen.has(name)) continue;
+        if (seen.has(name) || !drawn(list[i], list[i + 1])) continue;
         seen.add(name);
         out.set([list[i] - anchor.whole[0], list[i + 1] - anchor.whole[1], ...list.subarray(i + 2, i + BOX)], 4 + 12 * n++);
     }
@@ -1020,15 +1238,17 @@ function jobs(list: { page: Page; stored: number; slot: number; stamped: boolean
     return data;
 }
 
-/** Stamp jobs as `StampJob` in stamp.wgsl, with their nodes' data packed after each other from `base`. */
-function stampJobs(stamps: Stamp[], base = 0): { jobs: ArrayBuffer; data: Uint32Array } {
+/** Stamp jobs as `StampJob` in stamp.wgsl, with their nodes' data packed after each other; `synthesized` holds the frame's syntheses. */
+export function stampJobs(stamps: Stamp[], synthesized: Set): { jobs: ArrayBuffer; data: Uint32Array } {
     const jobs = new ArrayBuffer(Math.max(1, stamps.length) * STAMP_JOB_BYTES), words = new Uint32Array(jobs), ints = new Int32Array(jobs);
     const data = new Uint32Array(stamps.reduce((sum, { data }) => sum + (data?.length ?? 0), 0));
     let at = 0;
     stamps.forEach(({ page, out, data: node, mode }, k) => {
         const w = (STAMP_JOB_BYTES / 4) * k;
         ints.set([page.node.x * PAGE, page.node.y * PAGE], w);
-        words.set([page.node.level, node ? base + at : 0xffffffff, out, !(mode & MODE.HEIGHTS) ? page.drawn! : page.kind === 'stored' ? page.slot : SYNTHESIZED, mode, page.mask ?? 0], w + 2);
+        // A page synthesized in the frame has its heights in `out` until the quantize, also for a mask alone.
+        const base = page.kind === 'stored' && mode & MODE.HEIGHTS ? page.slot : mode & MODE.HEIGHTS || synthesized.has(page) ? SYNTHESIZED : page.drawn!;
+        words.set([page.node.level, node ? at : 0xffffffff, out, base, mode, page.mask ?? 0], w + 2);
         if (node) {
             data.set(node, at);
             at += node.length;
diff --git a/builder/web/src/lib/trailview/terrain/terrain.wgsl b/builder/web/src/lib/trailview/terrain/terrain.wgsl
index cb80e46087..cbde217f77 100644
--- a/builder/web/src/lib/trailview/terrain/terrain.wgsl
+++ b/builder/web/src/lib/trailview/terrain/terrain.wgsl
@@ -4,6 +4,7 @@
 // #include drawn-mesh.wgsl
 // #include portal-box.wgsl
 // #include ../ground/look.wgsl
+// #include ../plan/cells.wgsl
 
 struct Frame {
     // Camera-relative world (x east, y north, z up) to clip space; reversed Z, infinite far plane.
@@ -14,7 +15,7 @@ struct Frame {
     eye: f32,
     // Metres of drop per square metre of distance: Earth curvature with refraction.
     curvature: f32,
-    // The index of the debug view: 0 off, 1 normals, 2 LOD, 3 cracks, 4 surface, MASK_VIEW mask; look.wgsl draws the others.
+    // The index of the debug view: 0 off, 1 normals, 2 LOD, 3 cracks, 4 surface, MASK_VIEW mask, OWNED_VIEW owned; look.wgsl draws the others.
     debug: u32,
 }
 
@@ -34,6 +35,9 @@ struct Node {
 // shows through. Only their pipeline discards: a discard turns off the hidden-surface removal of
 // tile-based GPUs such as Apple's.
 override HOLES: bool = false;
+// With the ground plan's meshes (plan/pieces.ts): a level-18 or level-17 vertex takes no snap of its own where a
+// mesh draws whole, and its triangles go inside the mesh's owned region.
+override PLAN: bool = false;
 
 // Metres from a point of the terrain, `u` units about the anchor at height `h`, to the nearest portal
 // box, negative inside; with `footprint`, to the nearest box's footprint, whatever the height.
@@ -57,7 +61,12 @@ const CELLS = 64u;
 fn vertex_main(@builtin(vertex_index) index: u32, @builtin(instance_index) instance: u32) -> Varyings {
     let node = nodes[instance];
     let grid = vec2i(vec2u(index % (CELLS + 1u), index / (CELLS + 1u)));
-    let v = grid_vertex(node.origin + grid * (1 << (24u - node.level)), node.level, true);
+    let u = node.origin + grid * (1 << (24u - node.level));
+    // The meshes lie over the nodes of the finest level, 18 or 17 (pieces.ts).
+    let meshed = PLAN && node.level == min(surface.finest, 18u);
+    let v = grid_vertex_by(u, node.level, !meshed || !plan_near(u), true);
+    // A sunk vertex under a mesh drops each triangle that has one, as an unknown height does: the mesh draws there.
+    let sunk = meshed && plan_sunk(u);
     // A vertex of unknown height stands on the ground under the eye; `mark_known` drops each triangle that has one.
     var p = vec3f(to_render(v.s), select(-surface.above, v.h - frame.eye, known(v.h)));
     p.z -= frame.curvature * dot(p.xy, p.xy);
@@ -65,7 +74,7 @@ fn vertex_main(@builtin(vertex_index) index: u32, @builtin(instance_index) insta
     out.clip = frame.view_proj * vec4f(p, 1.0);
     out.s = v.s;
     out.relative = p;
-    mark_known(&out, known(v.h));
+    mark_known(&out, known(v.h) && !sunk);
     out.near = 1e6;
     if (HOLES) {
         out.near = hole_distance(units_of(v.s), 0.0, true);
@@ -75,8 +84,9 @@ fn vertex_main(@builtin(vertex_index) index: u32, @builtin(instance_index) insta
     return out;
 }
 
-// The debug view of the mask, as `mask` in DEBUG_VIEWS of view.ts.
+// The debug views of the mask and of the ground plan's owned region, as `mask` and `owned` in DEBUG_VIEWS of view.ts.
 const MASK_VIEW: u32 = 10u;
+const OWNED_VIEW: u32 = 11u;
 
 // The road surfaces of the mask, by code: main, road, gravel, dirt, grass, path, oneway, paving, then the
 // tracks in purple: standard and narrow gauge, each without and with a rack.
@@ -118,8 +128,13 @@ fn fragment_main(in: Fragment) -> @location(0) vec4f {
     if (HOLES && in.near < TRIANGLE_CELLS * f32(1u << (24u - in.level)) * surface.unit && hole_distance(units_of(in.s), in.h, false) < 0.0) {
         discard;
     }
+    if (frame.debug == OWNED_VIEW) {
+        // Blue where the mesh draws the point by the strip's rule: the terrain should sink or lie behind the
+        // mesh there, so a blue pixel is a fault from any view. Red elsewhere.
+        return select(vec4f(0.25, 0.0, 0.0, 1.0), vec4f(0.0, 0.0, 0.5, 1.0), MODEL && plan_owns(in.s, in.level));
+    }
     if (frame.debug == 0u || (frame.debug > 4u && frame.debug != MASK_VIEW)) {
-        return vec4f(ground_colour(in.s, in.relative, mat2x3f(dpdx(in.relative), dpdy(in.relative)), in.h, in.level, in.clip.xy, 0.0), 1.0);
+        return vec4f(ground_colour(in.s, in.relative, mat2x3f(dpdx(in.relative), dpdy(in.relative)), in.h, in.level, in.clip.xy, band_road(0.0), drawn_relief(in.s)), 1.0);
     }
     let n = render_normal(drawn_normal(in.s));
     let light = max(dot(n, frame.sun.xyz), 0.0) * frame.sun.w + 0.3;
@@ -132,7 +147,8 @@ fn fragment_main(in: Fragment) -> @location(0) vec4f {
         return vec4f(hue(ceil(lambda)) * (1.0 - 0.6 * (ceil(lambda) - lambda)) * (0.5 + 0.5 * light), 1.0);
     }
     if (frame.debug == 3u) {
-        // Grey only: the red clear colour shows through a crack and nowhere else.
+        // Grey only: the red clear colour shows through a crack, and through a hole in the ground plan's meshes,
+        // and nowhere else.
         return vec4f(vec3f(0.25 + 0.5 * light / 1.3), 1.0);
     }
     if (frame.debug == 4u) {
diff --git a/builder/web/src/lib/trailview/terrain/town.ts b/builder/web/src/lib/trailview/terrain/town.ts
index 4f65cbf437..628f2aa6d3 100644
--- a/builder/web/src/lib/trailview/terrain/town.ts
+++ b/builder/web/src/lib/trailview/terrain/town.ts
@@ -16,24 +16,33 @@ export const KERB = '#c3c0b8';
 /** Cells of 2^SHIFT world units: about 50 m in the Alps. */
 const SHIFT = 11;
 
-/** Boxes of world units (west, north, east, south), the boxes that meet each cell, and a mark per box for a query. */
-export interface Grid { boxes: number[][]; cells: Map; marks: Uint32Array; query: number }
+/** Boxes of world units (west, north, east, south), the boxes that meet each cell of 2^shift units (SHIFT without one), and a mark per box for a query. */
+export interface Grid { boxes: number[][]; cells: Map; marks: Uint32Array; query: number; shift?: number }
 /** The first outer ring of each building in a grid of their boxes. */
 export interface Town extends Grid { rings: number[][] }
 
 const towns = new WeakMap();
 const key = (i: number, j: number) => i * 2 ** 20 + j;
 
-export function gridOf(boxes: number[][]): Grid {
-    const cells = new Map();
-    boxes.forEach(([x0, y0, x1, y1], b) => {
-        for (let i = Math.floor(x0) >> SHIFT; i <= Math.floor(x1) >> SHIFT; i++) for (let j = Math.floor(y0) >> SHIFT; j <= Math.floor(y1) >> SHIFT; j++) {
-            const list = cells.get(key(i, j));
-            if (list) list.push(b);
-            else cells.set(key(i, j), [b]);
-        }
-    });
-    return { boxes, cells, marks: new Uint32Array(boxes.length), query: 0 };
+export function gridOf(boxes: number[][], shift = SHIFT): Grid {
+    const grid: Grid = { boxes: [], cells: new Map(), marks: new Uint32Array(boxes.length), query: 0, shift };
+    for (const box of boxes) add(grid, box);
+    return grid;
+}
+
+/** Adds a box to a grid: a query after it finds the box. */
+export function add(grid: Grid, box: number[]): void {
+    const [x0, y0, x1, y1] = box, b = grid.boxes.push(box) - 1, shift = grid.shift ?? SHIFT;
+    if (b >= grid.marks.length) {
+        const marks = new Uint32Array(2 * b + 16);
+        marks.set(grid.marks);
+        grid.marks = marks;
+    }
+    for (let i = Math.floor(x0) >> shift; i <= Math.floor(x1) >> shift; i++) for (let j = Math.floor(y0) >> shift; j <= Math.floor(y1) >> shift; j++) {
+        const list = grid.cells.get(key(i, j));
+        if (list) list.push(b);
+        else grid.cells.set(key(i, j), [b]);
+    }
 }
 
 export function townOf(buildings: Shapes['buildings']): Town {
@@ -50,8 +59,8 @@ export function townOf(buildings: Shapes['buildings']): Town {
 
 /** Calls `visit` once with each box of a grid that comes within `reach` world units of segment a-b's box. */
 export function near(grid: Grid, ax: number, ay: number, bx: number, by: number, reach: number, visit: (box: number) => void): void {
-    const x0 = Math.min(ax, bx) - reach, y0 = Math.min(ay, by) - reach, x1 = Math.max(ax, bx) + reach, y1 = Math.max(ay, by) + reach, mark = ++grid.query;
-    for (let i = Math.floor(x0) >> SHIFT; i <= Math.floor(x1) >> SHIFT; i++) for (let j = Math.floor(y0) >> SHIFT; j <= Math.floor(y1) >> SHIFT; j++) {
+    const x0 = Math.min(ax, bx) - reach, y0 = Math.min(ay, by) - reach, x1 = Math.max(ax, bx) + reach, y1 = Math.max(ay, by) + reach, mark = ++grid.query, shift = grid.shift ?? SHIFT;
+    for (let i = Math.floor(x0) >> shift; i <= Math.floor(x1) >> shift; i++) for (let j = Math.floor(y0) >> shift; j <= Math.floor(y1) >> shift; j++) {
         for (const b of grid.cells.get(key(i, j)) ?? []) {
             const box = grid.boxes[b];
             if (grid.marks[b] === mark || box[0] > x1 || box[2] < x0 || box[1] > y1 || box[3] < y0) continue;
diff --git a/builder/web/src/lib/trailview/terrain/unknown-clip.wgsl b/builder/web/src/lib/trailview/terrain/unknown-clip.wgsl
index dfb62eac82..a7f86ec971 100644
--- a/builder/web/src/lib/trailview/terrain/unknown-clip.wgsl
+++ b/builder/web/src/lib/trailview/terrain/unknown-clip.wgsl
@@ -5,7 +5,7 @@ enable clip_distances;
 // hidden-surface removal of tile-based GPUs such as Apple's.
 
 struct Varyings {
-    @builtin(position) clip: vec4f,
+    @builtin(position) @invariant clip: vec4f,
     @builtin(clip_distances) known: array,
     @location(0) s: vec2f,
     @location(1) relative: vec3f,
@@ -17,7 +17,7 @@ struct Varyings {
 
 // A fragment shader cannot read a clip distance.
 struct Fragment {
-    @builtin(position) clip: vec4f,
+    @builtin(position) @invariant clip: vec4f,
     @location(0) s: vec2f,
     @location(1) relative: vec3f,
     @location(3) h: f32,
diff --git a/builder/web/src/lib/trailview/terrain/unknown.wgsl b/builder/web/src/lib/trailview/terrain/unknown.wgsl
index 48a1e994e4..2314076c80 100644
--- a/builder/web/src/lib/trailview/terrain/unknown.wgsl
+++ b/builder/web/src/lib/trailview/terrain/unknown.wgsl
@@ -2,7 +2,7 @@
 // engine takes unknown-clip.wgsl when the device has clip distances.
 
 struct Varyings {
-    @builtin(position) clip: vec4f,
+    @builtin(position) @invariant clip: vec4f,
     @location(0) s: vec2f,
     @location(1) relative: vec3f,
     @location(2) known: f32,
diff --git a/builder/web/src/lib/trailview/terrain/water-cut-clip.wgsl b/builder/web/src/lib/trailview/terrain/water-cut-clip.wgsl
index 3708fe2137..80ec9ba3d8 100644
--- a/builder/web/src/lib/trailview/terrain/water-cut-clip.wgsl
+++ b/builder/web/src/lib/trailview/terrain/water-cut-clip.wgsl
@@ -15,6 +15,7 @@ struct WaterOut {
     @location(4) pixels: f32,
     @location(5) fall: f32,
     @location(6) lod: vec2f,
+    @location(7) u: vec2f,
 }
 
 // A fragment shader cannot read a clip distance.
@@ -27,6 +28,7 @@ struct WaterFragment {
     @location(4) pixels: f32,
     @location(5) fall: f32,
     @location(6) lod: vec2f,
+    @location(7) u: vec2f,
 }
 
 fn mark_cut(out: ptr, inside: vec4f, kept: bool) {
diff --git a/builder/web/src/lib/trailview/terrain/water-cut.wgsl b/builder/web/src/lib/trailview/terrain/water-cut.wgsl
index 97bc05bc13..2b2400f2a7 100644
--- a/builder/web/src/lib/trailview/terrain/water-cut.wgsl
+++ b/builder/web/src/lib/trailview/terrain/water-cut.wgsl
@@ -16,8 +16,9 @@ struct WaterOut {
     @location(6) inside: vec4f,
     // 1 where the vertex is kept.
     @location(7) kept: f32,
-    // The point of LOD space.
+    // The point of LOD space, and in units about the anchor.
     @location(8) lod: vec2f,
+    @location(9) u: vec2f,
 }
 
 // The fragment shader reads what the vertex shader writes.
diff --git a/builder/web/src/lib/trailview/terrain/water-look.wgsl b/builder/web/src/lib/trailview/terrain/water-look.wgsl
new file mode 100644
index 0000000000..5f287e1f6f
--- /dev/null
+++ b/builder/web/src/lib/trailview/terrain/water-look.wgsl
@@ -0,0 +1,36 @@
+// The look of the water's surface, which the water meshes (water.wgsl) and the ground plan's water faces
+// (roads/corridor.wgsl) share: a still body, dark from above and a mirror of the sky toward the horizon, with a
+// sun glint, small waves near the eye, and foam where the surface falls steeply along its flow (`fall`, rise per
+// metre). `sea`: the deep colour of the regions about the eye. `pixel` (metres of a pixel per metre of distance)
+// and `curvature` are the frame's. Linear light, before the haze.
+// #include ../ground/look.wgsl
+
+// The body of the water in linear light.
+const BODY: vec3f = vec3f(0.025, 0.098, 0.175);
+// The water turns white where it falls more steeply than FOAM_LOW along its flow, up to FOAM_MOST at FOAM_HIGH.
+const FOAM_LOW: f32 = 0.4;
+const FOAM_HIGH: f32 = 1.0;
+const FOAM_MOST: f32 = 0.35;
+
+fn water_look(relative: vec3f, lod: vec2f, fall: f32, sea: bool, pixel: f32, curvature: f32) -> vec3f {
+    let dir = normalize(relative);
+    let world = relative.xy + look.place.xy;
+    // Small waves tilt the surface by the slope of the noise; far away, where a pixel spans several, it lies calm.
+    let calm = 1.0 - smoothstep(0.5, 4.0, pixel * length(relative));
+    let q = world / 1.7;
+    let tilt = vec2f(noise(q + vec2f(0.35, 0.0)) - noise(q - vec2f(0.35, 0.0)), noise(q + vec2f(0.0, 0.35)) - noise(q - vec2f(0.0, 0.35))) * 0.06 * calm;
+    let up = normalize(vec3f(2.0 * curvature * relative.xy - tilt, 1.0));
+    let mirrored = reflect(dir, up);
+    // The reflection is held to 90 %: the far bank that it would show is darker than the sky.
+    let fresnel = 0.02 + 0.98 * pow(clamp(1.0 - dot(-dir, up), 0.0, 1.0), 5.0);
+    let sun = sun_share(sun_at(lod), relative, vec3f(0.0, 0.0, 1.0), LIFT_GROUND);
+    let lit = look.ambient.rgb + 0.8 * look.sun_colour.rgb * max(look.sun.z, 0.0) * sun;
+    let body = select(BODY, look.sea.rgb, sea) * lit;
+    var c = mix(body * 0.55, sky(mirrored), min(0.96 * fresnel, 0.9));
+    // The sun's path glints in sparks rather than a sheen.
+    let glint = max(dot(mirrored, look.sun.xyz), 0.0);
+    let sparks = smoothstep(0.8, 0.86, noise(q + 17.0)) * calm;
+    c += look.sun_colour.rgb * (4.0 * pow(glint, 400.0) + 2.5 * sparks * pow(glint, 80.0)) * sun;
+    let foam = FOAM_MOST * smoothstep(FOAM_LOW, FOAM_HIGH, fall) * (0.6 + 0.4 * noise(world / 0.8));
+    return mix(c, vec3f(0.85) * lit, foam);
+}
diff --git a/builder/web/src/lib/trailview/terrain/water-mesh.ts b/builder/web/src/lib/trailview/terrain/water-mesh.ts
index 148a31965a..3abd032d98 100644
--- a/builder/web/src/lib/trailview/terrain/water-mesh.ts
+++ b/builder/web/src/lib/trailview/terrain/water-mesh.ts
@@ -7,7 +7,7 @@ import earcut from 'earcut';
 import { CURVATURE } from '../frame/frame';
 import type { Feature } from '../stream/features';
 import { PAGE } from '../stream/heights';
-import { features, metresPerUnit, mitre, RIVER, RULES, STREAM, type Line, type Node } from './bins';
+import { features, metresPerUnit, mitre, nearBoxes, RIVER, RULES, STREAM, tileIndex, type Line, type Node } from './bins';
 import { waysOf } from './culverts';
 
 /** Words of a vertex, as `WaterIn` of water.wgsl: x, y (int32 world units), level, across x and y, signed half-width. */
@@ -33,7 +33,7 @@ export interface WaterMesh {
 
 /** The water mesh of a node from the features of its feature tile, null without water. */
 export function waterMesh(list: Feature[], tile: Node, node: Node): WaterMesh | null {
-    const { lines, lakes, seas, areas } = features(list, tile);
+    const shapes = features(list, tile), { lines, lakes, seas, areas } = shapes, index = tileIndex(shapes);
     const words: number[] = [], ribbons: number[] = [], surfaces: number[] = [], sea: number[] = [], drapes: number[] = [];
     const vertex = (x: number, y: number, z: number, ax = 0, ay = 0, half = 0) => words.push(Math.round(x), Math.round(y), z, ax, ay, half) / WATER_VERTEX - 1;
     const shift = 22 - node.level, side = PAGE * 2 ** shift, x0 = node.x * side, y0 = node.y * side, margin = 2 ** shift;
@@ -58,9 +58,10 @@ export function waterMesh(list: Feature[], tile: Node, node: Node): WaterMesh |
         }
         for (let i = 0; i + 1 < pairs; i++) ribbons.push(first + 2 * i, first + 2 * i + 1, first + 2 * i + 2, first + 2 * i + 2, first + 2 * i + 1, first + 2 * i + 3);
     };
-    for (const line of lines) {
+    // Each run of segments that comes near the square is a ribbon: only a line whose box comes near has one.
+    for (const id of nearBoxes(index.lines, box, 2 * cell + index.waterHalf / metresPerUnit(y0 + side / 2) + 1)) {
+        const line = lines[id];
         if (line.kind !== RIVER && line.kind !== STREAM) continue;
-        // Each run of segments that comes near the square is a ribbon.
         const reach = 2 * cell + line.h / metresPerUnit(y0 + side / 2);
         let run: number[] = [];
         for (let v = 0; v + 1 < line.z.length; v++) {
@@ -96,9 +97,13 @@ export function waterMesh(list: Feature[], tile: Node, node: Node): WaterMesh |
             for (const i of triangles) into.push(first + i);
         }
     };
-    for (const { level, rings, outer } of lakes) surface(rings, outer, level, longest, surfaces);
-    for (const { level, rings, outer } of seas) surface(rings, outer, level, longest, sea);
-    for (const { rings, outer } of areas) surface(rings, outer, DRAPED, Math.min(longest, AREA_CELLS * cell), drapes);
+    // An outline whose box misses the square has no ring in it.
+    const { outlines } = index;
+    for (const k of nearBoxes(outlines, box, 0)) {
+        if (k < outlines.seasFrom) surface(lakes[k].rings, lakes[k].outer, lakes[k].level, longest, surfaces);
+        else if (k < outlines.padsFrom) surface(seas[k - outlines.seasFrom].rings, seas[k - outlines.seasFrom].outer, seas[k - outlines.seasFrom].level, longest, sea);
+        else if (k >= outlines.areasFrom && k < outlines.buildingsFrom) surface(areas[k - outlines.areasFrom].rings, areas[k - outlines.areasFrom].outer, DRAPED, Math.min(longest, AREA_CELLS * cell), drapes);
+    }
     if (!ribbons.length && !surfaces.length && !sea.length && !drapes.length) return null;
     const vertices = new ArrayBuffer(words.length * 4), floats = new Float32Array(vertices), ints = new Int32Array(vertices);
     words.forEach((word, i) => (i % WATER_VERTEX < 2 ? (ints[i] = word) : (floats[i] = word)));
diff --git a/builder/web/src/lib/trailview/terrain/water.ts b/builder/web/src/lib/trailview/terrain/water.ts
index 76fec71377..1977d0875c 100644
--- a/builder/web/src/lib/trailview/terrain/water.ts
+++ b/builder/web/src/lib/trailview/terrain/water.ts
@@ -60,7 +60,8 @@ export class Water {
 
     constructor(private readonly stamps: Stamps) {}
 
-    async attach(gpu: Gpu, frame: GPUBuffer, nodes: GPUBuffer): Promise {
+    /** `cells`: the cells whose ground plan meshes draw (plan/cells.wgsl), where a ribbon draws nothing. */
+    async attach(gpu: Gpu, frame: GPUBuffer, nodes: GPUBuffer, cells: GPUBuffer): Promise {
         this.resources = undefined;
         const { device } = gpu, { pipelines, layout } = await gpu.once(waterPipelines);
         // A node index and a level per instance, at most one instance per node.
@@ -69,7 +70,7 @@ export class Water {
         this.vertexEnd = this.indexEnd = 0;
         this.resources = {
             device, pipelines, instances,
-            group: device.createBindGroup({ layout, entries: [{ binding: 0, resource: { buffer: frame } }, { binding: 2, resource: { buffer: nodes } }, { binding: 3, resource: { buffer: instances } }] }),
+            group: device.createBindGroup({ layout, entries: [{ binding: 0, resource: { buffer: frame } }, { binding: 2, resource: { buffer: nodes } }, { binding: 3, resource: { buffer: cells } }, { binding: 4, resource: { buffer: instances } }] }),
             vertices: gpu.buffer('water', VERTEX_BYTES, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST),
             indices: gpu.buffer('water', INDEX_BYTES, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST),
         };
@@ -163,7 +164,8 @@ async function waterPipelines(gpu: Gpu): Promise<{ pipelines: Record frame: Frame;
 @group(0) @binding(2) var nodes: array;
 // Per instance, the index of its node in `nodes` and the level of the node that the mesh belongs to.
-@group(0) @binding(3) var water_nodes: array;
+@group(0) @binding(4) var water_nodes: array;
 
 struct WaterIn {
     @location(0) at: vec2i,
@@ -43,18 +46,14 @@ struct WaterIn {
     @location(3) half: f32,
 }
 
-// The body of the water in linear light.
-const BODY: vec3f = vec3f(0.025, 0.098, 0.175);
 // The draw of the sea.
 override SEA_DRAW: bool = false;
 // The sea lies at this share of the lift of water over the terrain: under a lake at sea level. A river
 // area or a ribbon in the sea lies on its bed, under it, on the levels that cut the sea.
 const SEA_LIFT: f32 = 0.5;
-// A ribbon turns white where its bed falls more steeply than FOAM_LOW along its flow, up to FOAM_MOST at FOAM_HIGH.
-const FOAM_LOW: f32 = 0.4;
-const FOAM_HIGH: f32 = 1.0;
-const FOAM_MOST: f32 = 0.7;
 const RIBBON_PIXELS: f32 = 1.5;
+// Over a ground plan mesh, a ribbon draws for a stream narrower on screen than this, whole at a pixel less.
+const THIN_PIXELS: f32 = 2.0 * RIBBON_PIXELS;
 // A ribbon stops this far past a way's edge or its sidewalk, as GIVE_WAY_M of culverts.ts: past a guard rail's posts, 0.67 m (roads/details.ts).
 // Where a stream crosses the way, its ribbon has ended before this at a mouth's wall (standMouths of culverts.ts).
 const GIVE_WAY_M: f32 = 0.8;
@@ -99,8 +98,11 @@ fn water_vertex(v: WaterIn, @builtin(instance_index) instance: u32) -> WaterOut
     let drawn = water_nodes[instance];
     let node = nodes[drawn.x];
     let metres = unit_metres(v.at.y);
-    let lift = water_lift(metres * f32(1 << (22u - drawn.y)));
     var u = vec2f(v.at - surface.anchor);
+    // The lift of the texel at the point's own LOD, which runs on across a node's edge: one of the mesh's level would
+    // step there, and the far side's water, a level coarser and higher, shows the bed through a line. Never less than
+    // the mesh's own, where the node draws a coarser page's mesh.
+    let lift = max(water_lift(metres * exp2(22.0 - lod(lod_space(u)))), water_lift(metres * f32(1 << (22u - drawn.y))));
     var out: WaterOut;
     out.share = 1.0;
     out.pixels = 1e6;
@@ -130,6 +132,7 @@ fn water_vertex(v: WaterIn, @builtin(instance_index) instance: u32) -> WaterOut
     mark_cut(&out, vec4f(u - low, high - u), known(z) && frame.debug != 3u && frame.debug != 4u);
     z = select(frame.eye - surface.above, z, known(z)) + lift * select(1.0, SEA_LIFT, SEA_DRAW);
     out.lod = lod_space(u);
+    out.u = u;
     var p = vec3f(to_render(out.lod), z - frame.eye);
     p.z -= frame.curvature * dot(p.xy, p.xy);
     let d = length(p);
@@ -156,6 +159,8 @@ fn water_fragment(in: WaterFragment) -> @location(0) vec4f {
 
 @fragment
 fn ribbon_fragment(in: WaterFragment) -> @location(0) vec4f {
+    // The ribbon's width on screen, across it: `side` runs from -1 to 1 over it.
+    let across = 2.0 / max(fwidth(in.side), 1e-6);
     drop_cut(in);
     let edge = clamp((1.0 - abs(in.side)) * in.pixels + 0.5, 0.0, 1.0);
     let m = mask_at(in.lod, u32(ceil(lod(in.lod))), true);
@@ -163,28 +168,13 @@ fn ribbon_fragment(in: WaterFragment) -> @location(0) vec4f {
     if (m.level != 0u && m.kind.x != 0u && (m.kind.y & FORDED) == 0u) {
         open = clamp((m.edge - m.walk - select(GIVE_WAY_M, 0.0, m.half < FOOT_HALF_M)) / (frame.pixel * length(in.relative)) + 0.5, 0.0, 1.0);
     }
-    return vec4f(atmosphere(water_colour(in), in.relative, in.altitude), in.share * edge * open);
+    // Over a ground plan mesh, a stream narrower on screen than THIN_PIXELS keeps its ribbon on top: at a
+    // grazing view its own bank hides its face. The ribbon fades in as the stream narrows.
+    let thin = 1.0 - smoothstep(THIN_PIXELS - 1.0, THIN_PIXELS, across);
+    let drawn = select(1.0, thin, plan_near(vec2i(floor(in.u))));
+    return vec4f(atmosphere(water_colour(in), in.relative, in.altitude), in.share * edge * open * drawn);
 }
 
 fn water_colour(in: WaterFragment) -> vec3f {
-    let dir = normalize(in.relative);
-    let world = in.relative.xy + look.place.xy;
-    // Small waves tilt the surface by the slope of the noise; far away, where a pixel spans several, it lies calm.
-    let calm = 1.0 - smoothstep(0.5, 4.0, frame.pixel * length(in.relative));
-    let q = world / 1.7;
-    let tilt = vec2f(noise(q + vec2f(0.35, 0.0)) - noise(q - vec2f(0.35, 0.0)), noise(q + vec2f(0.0, 0.35)) - noise(q - vec2f(0.0, 0.35))) * 0.06 * calm;
-    let up = normalize(vec3f(2.0 * frame.curvature * in.relative.xy - tilt, 1.0));
-    let mirrored = reflect(dir, up);
-    // The reflection is held to 90 %: the far bank that it would show is darker than the sky.
-    let fresnel = 0.02 + 0.98 * pow(clamp(1.0 - dot(-dir, up), 0.0, 1.0), 5.0);
-    let sun = sun_share(sun_at(in.lod), in.relative, vec3f(0.0, 0.0, 1.0), LIFT_GROUND);
-    let lit = look.ambient.rgb + 0.8 * look.sun_colour.rgb * max(look.sun.z, 0.0) * sun;
-    let body = select(BODY, look.sea.rgb, SEA_DRAW) * lit;
-    var c = mix(body * 0.55, sky(mirrored), min(0.96 * fresnel, 0.9));
-    // The sun's path glints in sparks rather than a sheen.
-    let glint = max(dot(mirrored, look.sun.xyz), 0.0);
-    let sparks = smoothstep(0.8, 0.86, noise(q + 17.0)) * calm;
-    c += look.sun_colour.rgb * (4.0 * pow(glint, 400.0) + 2.5 * sparks * pow(glint, 80.0)) * sun;
-    let foam = FOAM_MOST * smoothstep(FOAM_LOW, FOAM_HIGH, in.fall) * (0.6 + 0.4 * noise(world / 0.8));
-    return mix(c, vec3f(0.85) * lit, foam);
+    return water_look(in.relative, in.lod, in.fall, SEA_DRAW, frame.pixel, frame.curvature);
 }
diff --git a/builder/web/src/lib/trailview/vegetation/forest.ts b/builder/web/src/lib/trailview/vegetation/forest.ts
index 2fa6bc32fd..44ac43fe4c 100644
--- a/builder/web/src/lib/trailview/vegetation/forest.ts
+++ b/builder/web/src/lib/trailview/vegetation/forest.ts
@@ -65,8 +65,8 @@ export class Forest implements Producer {
         this.most = windowSide(Math.max(Math.abs(config.bounds[1]), Math.abs(config.bounds[3])));
         this.planted = bits(rules.vocabulary.materials.flatMap((material, code) => (material.rows ? [code] : [])));
         // tools/trailview/rules.py checks that a region has SPECIES tree species at most, each with its model.
-        this.species = speciesTable(rules.regions.map(region => region.trees.filter(rule => rule.cover === 'tree').slice(0, SPECIES).flatMap(rule => {
-            const model = trees.index(rule.model, rule.evergreen);
+        this.species = speciesTable(rules.regions.map((region, r) => region.trees.filter(rule => rule.cover === 'tree').slice(0, SPECIES).flatMap(rule => {
+            const model = trees.index(r, rule.model, rule.evergreen);
             return model === undefined ? [] : [{ model, leaf: rule.leaf === 'broadleaved' ? 1 : 2, band: rule.elevation, weight: rule.weight }];
         })));
     }
diff --git a/builder/web/src/lib/trailview/vegetation/model-entry.ts b/builder/web/src/lib/trailview/vegetation/model-entry.ts
new file mode 100644
index 0000000000..db2a185aad
--- /dev/null
+++ b/builder/web/src/lib/trailview/vegetation/model-entry.ts
@@ -0,0 +1,28 @@
+// A built tree model as an entry of the device cache. The tree version hashes this module with the model worker, so a
+// change of the layout makes another cache.
+import { SEASONS } from '../rules/regions';
+import type { BuiltLeafy, BuiltModel } from './model-worker';
+
+/** Numbers in the head per phase of a summer crown: whether the phase draws a crown of its own, whether it has a colour matrix, and the matrix. */
+const PHASE_WORDS = 11;
+
+/** A built model as the parts of an entry: a float64 head (the crown's lowest point, the tiers' trunks and, for a summer crown, its phases), then the arrays of each tier. */
+export function partsOf(model: BuiltModel | BuiltLeafy): Uint32Array[] {
+    const { tiers, crown } = model, leafy = 'tones' in model ? model : undefined;
+    const head = [crown, tiers.length, ...tiers.map(({ trunk }) => trunk), leafy ? 1 : 0];
+    if (leafy) SEASONS.forEach((_, phase) => head.push(+!!leafy.own[phase], leafy.tones[phase] ? 1 : 0, ...(leafy.tones[phase] ?? Array(9).fill(0))));
+    return [new Uint32Array(Float64Array.from(head).buffer), ...tiers.flatMap(({ position, normal, color, index }) => [position, normal, color, index].map(array => new Uint32Array(array.buffer, array.byteOffset, array.length)))];
+}
+
+/** The model of an entry; it throws where the entry does not hold one. */
+export function modelOf([words, ...arrays]: Uint32Array[]): BuiltModel | BuiltLeafy {
+    const head = new Float64Array(words.buffer), count = head[1], at = 2 + count;
+    if (!Number.isInteger(count) || arrays.length !== 4 * count || head.length !== at + 1 + (head[at] ? PHASE_WORDS * SEASONS.length : 0)) throw new Error('not a tree model');
+    const tiers = [...head.subarray(2, at)].map((trunk, t) => {
+        const [position, normal, color] = arrays.slice(4 * t, 4 * t + 3).map(array => new Float32Array(array.buffer));
+        return { position, normal, color, index: arrays[4 * t + 3], trunk };
+    });
+    if (!head[at]) return { tiers, crown: head[0] };
+    const phases = SEASONS.map((_, phase) => head.subarray(at + 1 + PHASE_WORDS * phase, at + 1 + PHASE_WORDS * (phase + 1)));
+    return { tiers, crown: head[0], own: phases.map(words => words[0] === 1), tones: phases.map(words => (words[1] ? [...words.subarray(2)] : undefined)) };
+}
diff --git a/builder/web/src/lib/trailview/vegetation/model-worker.ts b/builder/web/src/lib/trailview/vegetation/model-worker.ts
index 4aad213c9c..f6bb91e8d4 100644
--- a/builder/web/src/lib/trailview/vegetation/model-worker.ts
+++ b/builder/web/src/lib/trailview/vegetation/model-worker.ts
@@ -14,8 +14,11 @@ const TRIANGLES = [600, 200];
 /** A phase draws the summer crown through a colour matrix where that turns every crown vertex within this many sRGB steps of 255. */
 const FIT = 8;
 
-/** A job: species to build in summer, kept green all year or not, and crowns of a species in a phase. */
-export interface ModelJob { id: number; leafy: { model: string; evergreen: boolean }[]; crowns: { model: string; phase: number }[] }
+/**
+ * A job: species to build in summer, with the colour matrices and crowns of their phases, and crowns of a species in
+ * a phase. A species that a pack keeps green all year takes the same build and leaves its phases out.
+ */
+export interface ModelJob { id: number; leafy: { model: string }[]; crowns: { model: string; phase: number }[] }
 export interface BuiltTier { position: Float32Array; normal: Float32Array; color: Float32Array; index: Uint32Array }
 /** A model's tiers, each with its trunk's vertices first, and its crown's lowest point in model units at every tier. */
 export interface BuiltModel { tiers: (BuiltTier & { trunk: number })[]; crown: number }
@@ -31,11 +34,11 @@ export interface BuiltLeafy extends BuiltModel { tones: (number[] | undefined)[]
 self.onmessage = async ({ data: { id, leafy, crowns } }: MessageEvent) => {
     try {
         await simplifierReady;
-        const species = leafy.map(({ model, evergreen }): BuiltLeafy => {
+        const species = leafy.map(({ model }): BuiltLeafy => {
             const summer = ([0, 1, 2] as Lod[]).map(lod => tree(model, 'summer', lod));
             const tones: (number[] | undefined)[] = [], own: boolean[] = [];
             SEASONS.forEach((season, phase) => {
-                if (evergreen || phase === SUMMER) return;
+                if (phase === SUMMER) return;
                 const near = bareIn(model, season) ? undefined : tree(model, season, 0), matrix = near && tone(summer[0], near);
                 tones[phase] = matrix;
                 own[phase] = !matrix || !fits(matrix, summer[0], near!, FIT);
diff --git a/builder/web/src/lib/trailview/vegetation/plants.test.ts b/builder/web/src/lib/trailview/vegetation/plants.test.ts
index e50a1f78aa..6eddd6a0ac 100644
--- a/builder/web/src/lib/trailview/vegetation/plants.test.ts
+++ b/builder/web/src/lib/trailview/vegetation/plants.test.ts
@@ -55,9 +55,9 @@ describe('the plant models', () => {
         const rules = { vocabulary, regions: [{ ground: [], trees: [shrub] }], styles: [] } as unknown as Rules;
         const plants = new Plants(rules, {} as TreeModels, instances as unknown as Instances, () => {}, new AbortController().signal);
         expect(specs).toHaveLength(1);
-        const first = plants.rowModel('grapevine');
+        const first = plants.rowModel(0, 'grapevine');
         expect(first).toBe(1);
-        expect(plants.rowModel('grapevine')).toBe(first);
+        expect(plants.rowModel(0, 'grapevine')).toBe(first);
         expect(specs).toHaveLength(1 + SEEDS);
     });
 });
diff --git a/builder/web/src/lib/trailview/vegetation/plants.ts b/builder/web/src/lib/trailview/vegetation/plants.ts
index 16a79c9607..60bbb40ade 100644
--- a/builder/web/src/lib/trailview/vegetation/plants.ts
+++ b/builder/web/src/lib/trailview/vegetation/plants.ts
@@ -10,7 +10,7 @@ import { TREES } from '../models/library';
 import { PLANTS } from '../models/plant-library';
 import { bits, named, seasonOf, type Region, type Rules, type Season, type Vocabulary } from '../rules/regions';
 import type { BuiltMesh, PlantJob } from './plant-worker';
-import type { TreeModels } from './tree-models';
+import { meets, type Reach, type TreeModels } from './tree-models';
 
 /** As plants.wgsl: the units of a cell of each grid, the reaches in metres, the list slots per region, vec4 per region and shapes per ground plant. */
 const GROUND_UNITS = 32, SHRUB_UNITS = 256, GROUND_M = 60, SHRUB_M = 500;
@@ -57,17 +57,23 @@ export function groundList(plants: T[]): T[] {
 
 /**
  * The ground plants and the shrubs about the eye (plants.wgsl): a producer of instances whose models
- * come from the packs of the regions, built for the date's season. A tree that stands as a shrub is
+ * come from the packs of the regions, built for the date's season once their region is in reach. A tree that stands as a shrub is
  * a model of the forest's (tree-models.ts).
  */
 export class Plants implements Producer {
     private resources?: Resources;
     private readonly list: Model[] = [];
     private readonly indexes: number[] = [];
+    /** Per model of the list: the regions that plant it, and the seasons that its mesh was asked for and that it holds. */
+    private readonly users: Set[] = [];
+    private readonly asked: (Season | undefined)[] = [];
+    private readonly built: (Season | undefined)[] = [];
     private readonly data: Uint32Array;
     private readonly worker = new Worker(new URL('./plant-worker.ts', import.meta.url), { type: 'module' });
+    /** The jobs in the worker by id: their season and their models of the list. */
+    private readonly jobs = new Map();
     private season?: Season;
-    private building = 0;
+    private reach: Reach = { reach: new Set(), near: new Set() };
     private next = 0;
     private surface?: GPUBindGroup;
     private features?: GPUBindGroup;
@@ -86,7 +92,7 @@ export class Plants implements Producer {
             const at = 64 + r * REGION_WORDS * 4;
             const ground = groundRules(region, rules.vocabulary).flatMap(rule => {
                 const tie = rule.own ? OWN_TIE : TIE;
-                const first = this.models(Array.from({ length: SEEDS }, (_, k) => ({ model: rule.model, seed: k + 1, evergreen: false, shrub: false, tie })));
+                const first = this.models(r, Array.from({ length: SEEDS }, (_, k) => ({ model: rule.model, seed: k + 1, evergreen: false, shrub: false, tie })));
                 return first === undefined ? [] : [{ ...rule, first }];
             });
             ground.forEach((rule, k) => {
@@ -97,7 +103,7 @@ export class Plants implements Producer {
             });
             const shrubs = region.trees.filter(rule => rule.cover === 'shrub' && (rule.model in PLANTS || rule.model in TREES)).sort((a, b) => b.weight - a.weight).slice(0, SLOTS).flatMap(rule => {
                 const plant = rule.model in PLANTS;
-                const model = plant ? this.models([{ model: rule.model, seed: 1, evergreen: !!rule.evergreen, shrub: true, tie: OWN_TIE }]) : trees.index(rule.model, rule.evergreen, OWN_TIE);
+                const model = plant ? this.models(r, [{ model: rule.model, seed: 1, evergreen: !!rule.evergreen, shrub: true, tie: OWN_TIE }]) : trees.index(r, rule.model, rule.evergreen, OWN_TIE);
                 return model === undefined ? [] : [{ ...rule, index: model, height: plant ? PLANTS[rule.model].ground.height : SHRUB_HEIGHT_M }];
             });
             shrubs.forEach((rule, k) => {
@@ -108,33 +114,50 @@ export class Plants implements Producer {
         });
         this.data = data;
         this.worker.onmessage = ({ data: message }: MessageEvent<{ id: number; built?: BuiltMesh[]; error?: string }>) => {
-            this.building--;
+            const job = this.jobs.get(message.id)!;
+            this.jobs.delete(message.id);
             if (message.error || !message.built) return void console.warn(`Plant models: ${message.error}`);
-            if (message.id !== this.next - 1) return;
-            this.list.forEach((entry, i) => this.instances.replace(this.indexes[i], spec(entry, message.built![i])));
+            if (job.season !== this.season) return;
+            job.models.forEach((i, k) => {
+                this.instances.replace(this.indexes[i], spec(this.list[i], message.built![k]));
+                this.built[i] = job.season;
+            });
             this.newContent = true;
             this.wake();
         };
     }
 
     get idle(): boolean {
-        return this.building === 0;
+        return this.jobs.size === 0 && this.list.every((_, i) => this.asked[i] === this.season || !this.plants(i, this.reach.reach));
+    }
+
+    /** Whether the models of the near regions hold their meshes of the season. */
+    get nearIdle(): boolean {
+        return this.list.every((_, i) => this.built[i] === this.season || !this.plants(i, this.reach.near));
     }
 
-    /** The first of SEEDS models of a plant that stands in rows (rows.ts), in its own colour; ask before the first update. */
-    rowModel(model: string): number | undefined {
-        return this.models(Array.from({ length: SEEDS }, (_, k) => ({ model, seed: k + 1, evergreen: false, shrub: true, tie: OWN_TIE })));
+    /** The first of SEEDS models of a plant that stands in rows (rows.ts) of region `region`, in its own colour; ask before the first update. */
+    rowModel(region: number, model: string): number | undefined {
+        return this.models(region, Array.from({ length: SEEDS }, (_, k) => ({ model, seed: k + 1, evergreen: false, shrub: true, tie: OWN_TIE })));
     }
 
-    /** The first of a run of models, one per entry: a run that the list already holds whole, else a new one. */
-    private models(entries: Model[]): number | undefined {
+    /** Whether one of these regions plants model `i` of the list. */
+    private plants(i: number, regions: Set): boolean {
+        return meets(this.users[i], regions);
+    }
+
+    /** The first of a run of models of region `region`, one per entry: a run that the list already holds whole, else a new one. */
+    private models(region: number, entries: Model[]): number | undefined {
         const same = (m: Model | undefined, e: Model) => m?.model === e.model && m.seed === e.seed && m.shrub === e.shrub && m.evergreen === e.evergreen && m.tie === e.tie;
-        const at = this.list.findIndex((_, i) => entries.every((entry, k) => same(this.list[i + k], entry) && this.indexes[i + k] === this.indexes[i] + k));
-        if (at >= 0) return this.indexes[at];
-        const first = this.instances.add(...entries.map(() => ({ tiers: [] })));
-        if (first === undefined) return undefined;
-        entries.forEach((entry, k) => (this.list.push(entry), this.indexes.push(first + k)));
-        return first;
+        let at = this.list.findIndex((_, i) => entries.every((entry, k) => same(this.list[i + k], entry) && this.indexes[i + k] === this.indexes[i] + k));
+        if (at < 0) {
+            const first = this.instances.add(...entries.map(() => ({ tiers: [] })));
+            if (first === undefined) return undefined;
+            at = this.list.length;
+            entries.forEach((entry, k) => (this.list.push(entry), this.indexes.push(first + k), this.users.push(new Set())));
+        }
+        entries.forEach((_, k) => this.users[at + k].add(region));
+        return this.indexes[at];
     }
 
     async attach(gpu: Gpu, { surface, features }: Surfaces): Promise {
@@ -152,16 +175,25 @@ export class Plants implements Producer {
         this.features = features;
     }
 
-    /** The models of the date's season, and the windows of the grids about the eye at (lon, lat), `above` metres over the ground. */
-    update(lonLat: [number, number], date: string, above: number): void {
+    /**
+     * The models of the date's season for the regions in reach, and the windows of the grids about the eye at (lon, lat), `above`
+     * metres over the ground.
+     */
+    update(lonLat: [number, number], date: string, above: number, reach: Reach): void {
         this.newContent = false;
         const r = this.resources;
         if (!r) return;
-        const season = seasonOf(date);
-        if (season !== this.season && this.list.length) {
-            this.season = season;
-            this.building++;
-            this.worker.postMessage({ id: this.next++, models: this.list.map(({ model, seed, evergreen }) => ({ model, seed, season: evergreen ? 'summer' : season })) } satisfies PlantJob);
+        const season = seasonOf(date), asking = season !== this.season || reach !== this.reach;
+        this.season = season;
+        this.reach = reach;
+        // A job for the near regions' models first, then one for the others in reach, each in the season.
+        for (const regions of asking ? [reach.near, reach.reach] : []) {
+            const models = this.list.flatMap((_, i) => (this.asked[i] !== season && this.plants(i, regions) ? [i] : []));
+            if (!models.length) continue;
+            models.forEach(i => (this.asked[i] = season));
+            const id = this.next++;
+            this.jobs.set(id, { season, models });
+            this.worker.postMessage({ id, models: models.map(i => ({ model: this.list[i].model, seed: this.list[i].seed, season: this.list[i].evergreen ? 'summer' : season })) } satisfies PlantJob);
         }
         const [ux, uy] = worldPixel(lonLat, UNITS), unit = anchorAt(...lonLat).unit;
         // An eye higher over the ground than a grid's reach dispatches none of it.
diff --git a/builder/web/src/lib/trailview/vegetation/rows.ts b/builder/web/src/lib/trailview/vegetation/rows.ts
index f04aeecfcf..b1499c5ff0 100644
--- a/builder/web/src/lib/trailview/vegetation/rows.ts
+++ b/builder/web/src/lib/trailview/vegetation/rows.ts
@@ -40,16 +40,16 @@ export class Rows implements Producer {
             floats.set([rows.reach_m, ...rows.height_m], 64 + 4 * c + 1);
         });
         const evergreen = (region: Region, model: string) => (region.trees.find(rule => rule.model === model) ?? rules.regions.flatMap(r => r.trees).find(rule => rule.model === model))?.evergreen;
-        const word = (region: Region, model: string | undefined) => {
+        const word = (region: Region, r: number, model: string | undefined) => {
             if (model && model in PLANTS) {
-                const first = plants.rowModel(model);
+                const first = plants.rowModel(r, model);
                 return first === undefined ? NO_MODEL : first | ALONG | (SEEDS << SHAPES);
             }
-            const index = model && model in TREES ? trees.index(model, evergreen(region, model)) : undefined;
+            const index = model && model in TREES ? trees.index(r, model, evergreen(region, model)) : undefined;
             return index === undefined ? NO_MODEL : index | (TREES[model!].keepsHeading ? WINDWARD : 0);
         };
         rules.regions.forEach((region, r) => crops.forEach(({ code, rows }, c) => {
-            data[MODELS_AT + 4 * r + c] = word(region, region.rows[rules.vocabulary.materials[code].id] ?? rows.model);
+            data[MODELS_AT + 4 * r + c] = word(region, r, region.rows[rules.vocabulary.materials[code].id] ?? rows.model);
         }));
         this.data = data;
         this.reach = Math.max(0, ...crops.map(({ rows }) => rows.reach_m));
diff --git a/builder/web/src/lib/trailview/vegetation/tree-models.test.ts b/builder/web/src/lib/trailview/vegetation/tree-models.test.ts
index 1c116f3af2..e447bbbc5b 100644
--- a/builder/web/src/lib/trailview/vegetation/tree-models.test.ts
+++ b/builder/web/src/lib/trailview/vegetation/tree-models.test.ts
@@ -1,7 +1,8 @@
 import { afterEach, describe, expect, it, vi } from 'vitest';
+import { FakeCaches } from '../../../../test-support/fake-caches';
 import type { Instances, ModelSpec } from '../instances/instances';
 import type { ModelAnswer, ModelJob } from './model-worker';
-import { TreeModels } from './tree-models';
+import { TreeModels, type Reach } from './tree-models';
 
 // Workers that keep their jobs, which the test answers.
 const jobs: { job: ModelJob; answer: (data: Omit) => void }[] = [];
@@ -13,46 +14,101 @@ class FakeWorker {
 }
 const built = (crown: number) => ({ tiers: [], crown });
 
-function trees(near = new Map()) {
+function trees(near = new Map(), version?: string, reach: Reach = { reach: new Set([0]), near: new Set([0]) }) {
     vi.stubGlobal('Worker', FakeWorker);
     jobs.length = 0;
     const specs: ModelSpec[] = [];
     const instances = { add: (spec: ModelSpec) => specs.push(spec) - 1, replace: (m: number, spec: ModelSpec) => (specs[m] = spec), day: 0 };
-    const models = new TreeModels(instances as unknown as Instances, () => {}, () => near, new AbortController().signal);
-    return { models, specs, beech: models.index('beech')! };
+    const models = new TreeModels(instances as unknown as Instances, () => {}, () => near, new AbortController().signal, version);
+    return { models, specs, reach, beech: models.index(0, 'beech')! };
 }
 
 describe('the tree models', () => {
     afterEach(() => (vi.unstubAllGlobals(), vi.restoreAllMocks()));
 
     it('draws a winter start bare from the summer builds', () => {
-        const { models, specs, beech } = trees();
-        models.update('2026-01-20');
-        expect(jobs.map(({ job }) => job)).toEqual([{ id: 0, leafy: [{ model: 'beech', evergreen: false }], crowns: [] }]);
+        const { models, specs, reach, beech } = trees();
+        models.update('2026-01-20', reach);
+        expect(jobs.map(({ job }) => job)).toEqual([{ id: 0, leafy: [{ model: 'beech' }], crowns: [] }]);
         // The summer build of beech and its winter crown both are `beech|0`.
         jobs[0].answer({ leafy: [{ ...built(0.1), tones: [], own: [true] }], crowns: [] });
         expect(jobs[1].job).toEqual({ id: 1, leafy: [], crowns: [{ model: 'beech', phase: 0 }] });
         jobs[1].answer({ leafy: [], crowns: [built(0.2)] });
-        models.update('2026-01-20');
+        models.update('2026-01-20', reach);
         const winter = specs[beech].phases![0].model;
         expect([specs[beech].crown, winter === beech ? undefined : specs[winter].crown, jobs.length]).toEqual([0.1, 0.2, 2]);
     });
 
     it('gives the free workers the species with the most trees about the eye first', () => {
-        const { models } = trees(new Map([['larch', 0.2], ['spruce', 0.7]]));
-        for (const model of ['beech', 'oak', 'larch', 'spruce']) models.index(model);
-        models.update('2026-07-01');
+        const { models, reach } = trees(new Map([['larch', 0.2], ['spruce', 0.7]]));
+        for (const model of ['beech', 'oak', 'larch', 'spruce']) models.index(0, model);
+        models.update('2026-07-01', reach);
         expect(jobs.map(({ job }) => job.leafy[0].model)).toEqual(['spruce', 'larch', 'beech']);
         jobs[1].answer({ leafy: [{ ...built(0.1), tones: [], own: [] }], crowns: [] });
         expect(jobs.map(({ job }) => job.leafy[0].model)).toEqual(['spruce', 'larch', 'beech', 'oak']);
     });
 
+    it('builds only the species of the regions in reach, those of the near regions first, and is near idle once these are in', () => {
+        const reach = { reach: new Set([0, 1]), near: new Set([1]) }, { models } = trees(new Map([['beech', 0.9]]), undefined, reach);
+        models.index(1, 'larch');
+        models.index(1, 'spruce');
+        models.index(2, 'oak');
+        models.update('2026-07-01', reach);
+        expect(jobs.map(({ job }) => job.leafy[0].model)).toEqual(['larch', 'spruce', 'beech']);
+        jobs[0].answer({ leafy: [{ ...built(0.1), tones: [], own: [] }], crowns: [] });
+        jobs[1].answer({ leafy: [{ ...built(0.1), tones: [], own: [] }], crowns: [] });
+        models.update('2026-07-01', reach);
+        expect([models.nearIdle, models.idle, jobs.length]).toEqual([true, false, 3]);
+        models.update('2026-07-01', { ...reach, reach: new Set([0, 1, 2]) });
+        expect(jobs.map(({ job }) => job.leafy[0].model)).toEqual(['larch', 'spruce', 'beech', 'oak']);
+    });
+
+    it('is near idle in winter only once the near trees draw their own bare crowns', () => {
+        const reach = { reach: new Set([0, 1]), near: new Set([0]) }, { models, specs, beech } = trees(new Map(), undefined, reach);
+        models.index(1, 'oak');
+        models.update('2026-01-20', reach);
+        expect(jobs.map(({ job }) => job.leafy[0].model)).toEqual(['beech', 'oak']);
+        jobs[0].answer({ leafy: [{ ...built(0.1), tones: [], own: [true] }], crowns: [] });
+        jobs[2].answer({ leafy: [], crowns: [built(0.2)] });
+        models.update('2026-01-20', reach);
+        // Built, but the far species' summer crown still runs: the bare crown has no instance model yet.
+        expect([models.nearIdle, specs[beech].phases![0].model === beech]).toEqual([false, true]);
+        jobs[1].answer({ leafy: [{ ...built(0.3), tones: [], own: [] }], crowns: [] });
+        models.update('2026-01-20', reach);
+        expect([models.nearIdle, specs[specs[beech].phases![0].model].crown]).toEqual([true, 0.2]);
+    });
+
     it('asks again for the models of a job that failed', () => {
         vi.spyOn(console, 'warn').mockImplementation(() => {});
-        const { models } = trees();
-        models.update('2026-01-20');
+        const { models, reach } = trees();
+        models.update('2026-01-20', reach);
         jobs[0].answer({ error: 'lost' });
-        models.update('2026-07-01');
-        expect(jobs.map(({ job }) => job.leafy)).toEqual([[{ model: 'beech', evergreen: false }], [{ model: 'beech', evergreen: false }]]);
+        // Not in the next frame: when the next job lands or the date's phases change.
+        models.update('2026-01-20', reach);
+        expect([jobs.length, models.idle]).toEqual([1, true]);
+        models.update('2026-07-01', reach);
+        expect(jobs.map(({ job }) => job.leafy)).toEqual([[{ model: 'beech' }], [{ model: 'beech' }]]);
+    });
+
+    it('takes a build from the device cache as the worker made it, and builds again for another version', async () => {
+        vi.stubGlobal('caches', new FakeCaches());
+        const tier = (k: number) => ({ position: Float32Array.of(k, 0.5, 1 / 3), normal: Float32Array.of(0, 0, 1), color: Float32Array.of(0.1, 0.2, k), index: Uint32Array.of(0, 0, 0), trunk: k });
+        // A summer crown with gaps in its tones and in its phases of their own, as a worker makes it.
+        const leafy = { tiers: [tier(1), tier(2), tier(3)], crown: 0.125, tones: [[1, 0, 0, 0, 1, 0, 0, 0, 1.5], undefined, undefined, [0.5, 0, 0, 0, 1, 0, 0, 0, 1]], own: [true, false, undefined, false] as boolean[] };
+        const load = async (version: string) => {
+            const { models, specs, reach, beech } = trees(undefined, version);
+            models.update('2026-08-15', reach);
+            for (let i = 0; i < 50 && !jobs.length && !models.idle; i++) await new Promise(resolve => setTimeout(resolve, 2));
+            jobs[0]?.answer({ leafy: [leafy], crowns: [] });
+            // The engine saves what the workers built once the view is idle.
+            models.save();
+            await new Promise(resolve => setTimeout(resolve, 20));
+            models.update('2026-08-15', reach);
+            return { asked: jobs.length, spec: specs[beech] };
+        };
+        const made = await load('a'), again = await load('a'), other = await load('b');
+        expect([made.asked, again.asked, other.asked, made.spec.tiers.length]).toEqual([1, 0, 1, 3]);
+        // toStrictEqual compares the classes of the typed arrays too.
+        expect(again.spec).toStrictEqual(made.spec);
     });
 });
diff --git a/builder/web/src/lib/trailview/vegetation/tree-models.ts b/builder/web/src/lib/trailview/vegetation/tree-models.ts
index 1c49e166e4..9368f5f1f3 100644
--- a/builder/web/src/lib/trailview/vegetation/tree-models.ts
+++ b/builder/web/src/lib/trailview/vegetation/tree-models.ts
@@ -1,6 +1,8 @@
 import { dayOfYear } from '../ground/rules';
 import type { Instances, ModelSpec } from '../instances/instances';
 import { SEASONS } from '../rules/regions';
+import { CAPS, DeviceCache } from '../terrain/device-cache';
+import { modelOf, partsOf } from './model-entry';
 import type { BuiltLeafy, BuiltModel, ModelAnswer, ModelJob } from './model-worker';
 import { phasesOn } from './phenology';
 
@@ -14,18 +16,29 @@ const TIERS_M = [60, 300, 700], TREE_SIZE_M = 25;
 /** Workers that build the models side by side, a species or a crown per job: the trees show as each job lands. */
 const WORKERS = 3;
 
-/** An instance model of a species, and the models of its phases that draw a crown of their own. */
-interface Entry { index: number; own: (number | undefined)[] }
+/** An instance model of a species, the models of its phases that draw a crown of their own, and the regions whose trees take it. */
+interface Entry { index: number; own: (number | undefined)[]; regions: Set }
+/** The regions whose trees and plants the view can show (`reach`), and those of the near field (`near`). */
+export interface Reach { reach: Set; near: Set }
+/** Whether two sets of regions share one. */
+export function meets(a: Set, b: Set): boolean {
+    for (const region of a) if (b.has(region)) return true;
+    return false;
+}
+/** A build: a species' summer crown, kept green all year or not, or a crown of a species in a phase. */
+interface Build { leafy: { model: string; evergreen: boolean }[]; crowns: { model: string; phase: number }[] }
 
 /**
  * The tree models (model-worker.ts), one build per species for the forest, the shrubs and the
- * plantings. A tree draws the summer crown, which its phase on the date (phenology.ts) colours, or a
+ * plantings, of the species of the regions in reach. A tree draws the summer crown, which its phase on the date (phenology.ts) colours, or a
  * crown of the phase's own, such as a bare one, once the workers have built it for a phase that the
  * date has; until then the summer crown in the phase's colours. A free worker takes the next build:
- * summer crowns before crowns of their own, each with the models about the eye first. Built models
+ * summer crowns before crowns of their own, each with the models of the near regions and then about the eye first. Built models
  * stay, so a change of date builds only what it has not seen. A species that a pack keeps green all
  * year stays in summer. A model with a tie to the ground's hue (draw.wgsl), such as a tree that stands
- * as a shrub, is an instance model of its own on the same meshes.
+ * as a shrub, is an instance model of its own on the same meshes. With the version of the model worker's code,
+ * a build comes from the device cache where it holds it; what the workers built goes there once the view is idle
+ * (`save`), so a load does not wait for the writes.
  */
 export class TreeModels {
     /** Instance models by `model|evergreen|tie`. */
@@ -33,12 +46,14 @@ export class TreeModels {
     private readonly workers = Array.from({ length: WORKERS }, () => new Worker(new URL('./model-worker.ts', import.meta.url), { type: 'module' }));
     private readonly free = [...this.workers];
     /** The jobs that run, by id. */
-    private readonly jobs = new Map>();
+    private readonly jobs = new Map();
     /** The built summer crowns by `model|evergreen`, the built crowns of a phase by `model|phase`, what is asked for (`leafy:` or `crown:` and the key), and the builds that wait for a worker. */
     private readonly leafy = new Map();
     private readonly crowns = new Map();
     private readonly asked = new Set();
-    private waiting: Omit[] = [];
+    /** What a failed job asked for: `ask` asks for it again, when the next job lands or the date's phases change. */
+    private readonly failed = new Set();
+    private waiting: Build[] = [];
     /** The phases that the date has. */
     private phases = new Set();
     private day?: number;
@@ -47,30 +62,59 @@ export class TreeModels {
     private stale = false;
     /** Whether models or the date changed in the last update. */
     newContent = false;
+    /** The regions in reach at the last update, and the builds of a set of regions (`builds`). */
+    private wanted: Reach = { reach: new Set(), near: new Set() };
+    private buildsOf = new WeakMap, string[]>();
+    private readonly cache?: Promise;
+    /** Builds whose device cache entry is being read, and the entries that the workers built and the cache lacks. */
+    private reading = 0;
+    private readonly built: [string, Uint32Array[]][] = [];
 
     /** `near` gives the models about the eye, each with its share of the trees there. An abort of `stop` ends the workers. */
-    constructor(private readonly instances: Instances, private readonly wake: () => void, private readonly near: () => Map, stop: AbortSignal) {
+    constructor(private readonly instances: Instances, private readonly wake: () => void, private readonly near: () => Map, private readonly stop: AbortSignal, version?: string) {
         stop.addEventListener('abort', () => this.workers.forEach(worker => worker.terminate()));
         for (const worker of this.workers) worker.onmessage = ({ data }: MessageEvent) => this.land(worker, data);
+        if (version) this.cache = DeviceCache.open('trees', '', version, CAPS.trees).catch(() => undefined);
     }
 
     get idle(): boolean {
-        return this.jobs.size === 0 && this.waiting.length === 0 && !this.stale;
+        return this.jobs.size === 0 && this.waiting.length === 0 && this.reading === 0 && !this.stale && this.builds().every(build => this.asked.has(`leafy:${build}`) || this.failed.has(`leafy:${build}`));
+    }
+
+    /**
+     * Whether the trees of the near regions draw their final models: each has its summer crown, and the crown of its own of
+     * each of the date's phases that needs one is built and installed.
+     */
+    get nearIdle(): boolean {
+        if (this.stale) return false;
+        for (const [key, entry] of this.entries) {
+            if (!meets(entry.regions, this.wanted.near)) continue;
+            const [model, evergreen] = key.split('|'), leafy = this.leafy.get(`${model}|${evergreen}`);
+            if (!leafy) return false;
+            for (const phase of this.phases) if (leafy.own[phase] && (!this.crowns.has(`${model}|${phase}`) || entry.own[phase] === undefined)) return false;
+        }
+        return true;
     }
 
-    /** The instance model of a tree species with a tie to the ground's hue; undefined where the instances hold no more models. */
-    index(model: string, evergreen = false, tie = 0): number | undefined {
+    /**
+     * The instance model of a tree species with a tie to the ground's hue, for the trees of region `region`; undefined where
+     * the instances hold no more models.
+     */
+    index(region: number, model: string, evergreen = false, tie = 0): number | undefined {
         const key = `${model}|${evergreen ? 1 : 0}|${tie}`;
         if (!this.entries.has(key)) {
             const index = this.instances.add({ tiers: [] });
             if (index === undefined) return undefined;
-            this.entries.set(key, { index, own: [] });
+            this.entries.set(key, { index, own: [], regions: new Set() });
         }
-        return this.entries.get(key)!.index;
+        const entry = this.entries.get(key)!;
+        entry.regions.add(region);
+        this.buildsOf = new WeakMap();
+        return entry.index;
     }
 
-    /** Takes the date: the trees change phase at once, and the workers build what its phases lack. */
-    update(date: string): void {
+    /** Takes the date and the regions in reach: the trees change phase at once, and the workers build what they lack. */
+    update(date: string, reach: Reach): void {
         this.newContent = false;
         const day = dayOfYear(date);
         if (day !== this.day && this.entries.size) {
@@ -83,6 +127,10 @@ export class TreeModels {
                 this.ask();
             }
         }
+        if (reach !== this.wanted) {
+            this.wanted = reach;
+            if (this.builds().some(build => !this.asked.has(`leafy:${build}`) && !this.failed.has(`leafy:${build}`))) this.ask();
+        }
         if (!this.stale) return;
         this.stale = false;
         this.newContent = true;
@@ -95,12 +143,31 @@ export class TreeModels {
         this.jobs.delete(id);
         this.free.push(worker);
         if (error || !leafy || !crowns) {
-            job.leafy.forEach(({ model, evergreen }) => this.asked.delete(`leafy:${model}|${evergreen ? 1 : 0}`));
-            job.crowns.forEach(({ model, phase }) => this.asked.delete(`crown:${model}|${phase}`));
+            for (const key of [...job.leafy.map(({ model, evergreen }) => `leafy:${model}|${evergreen ? 1 : 0}`), ...job.crowns.map(({ model, phase }) => `crown:${model}|${phase}`)]) {
+                this.asked.delete(key);
+                this.failed.add(key);
+            }
             this.post();
             return void console.warn(`Tree models: ${error}`);
         }
-        job.leafy.forEach(({ model, evergreen }, i) => this.leafy.set(`${model}|${evergreen ? 1 : 0}`, leafy[i]));
+        if (this.cache) this.built.push([keyOf(job), partsOf(leafy[0] ?? crowns[0])]);
+        this.take(job, leafy, crowns);
+    }
+
+    /** Whether the workers built models that the device cache lacks. */
+    get unsaved(): boolean {
+        return this.built.length > 0;
+    }
+
+    /** Writes the models that the workers built to the device cache. */
+    save(): void {
+        for (const [key, parts] of this.built.splice(0)) void this.cache?.then(cache => cache?.write(key, parts)).catch(() => {});
+    }
+
+    /** Keeps the models of a job, from a worker or from the device cache. */
+    private take(job: Build, leafy: BuiltLeafy[], crowns: BuiltModel[]): void {
+        // A species kept green all year draws the summer crown in every phase.
+        job.leafy.forEach(({ model, evergreen }, i) => this.leafy.set(`${model}|${evergreen ? 1 : 0}`, evergreen ? { ...leafy[i], tones: [], own: [] } : leafy[i]));
         job.crowns.forEach(({ model, phase }, i) => this.crowns.set(`${model}|${phase}`, crowns[i]));
         this.stale = true;
         this.ask();
@@ -109,6 +176,7 @@ export class TreeModels {
 
     /** Queues the summer crowns not yet asked for, and the crowns of their own that the date's phases need. */
     private ask(): void {
+        this.failed.clear();
         const leafy = this.builds().filter(build => !this.asked.has(`leafy:${build}`)).map(build => {
             this.asked.add(`leafy:${build}`);
             const [model, evergreen] = build.split('|');
@@ -120,22 +188,50 @@ export class TreeModels {
                 const [model, phase] = crown.split('|');
                 return { model, phase: Number(phase) };
             });
-        this.waiting.push(...leafy.map(build => ({ leafy: [build], crowns: [] })), ...crowns.map(crown => ({ leafy: [], crowns: [crown] })));
+        const jobs = [...leafy.map(build => ({ leafy: [build], crowns: [] })), ...crowns.map(crown => ({ leafy: [], crowns: [crown] }))];
+        // Each build reads the device cache at once, so a warm device takes all its models in a frame or two; a miss waits for a worker.
+        for (const job of jobs) {
+            if (!this.cache) {
+                this.waiting.push(job);
+                continue;
+            }
+            this.reading++;
+            void this.cache.then(cache => cache?.read(keyOf(job))).catch(() => undefined).then(parts => {
+                this.reading--;
+                if (this.stop.aborted) return;
+                let model: BuiltModel | BuiltLeafy | undefined;
+                try {
+                    model = parts && modelOf(parts);
+                } catch {
+                    model = undefined;
+                }
+                // A miss, or an entry that holds no model, goes to a worker.
+                if (!model) {
+                    this.waiting.push(job);
+                    return this.post();
+                }
+                this.take(job, job.leafy.length ? [model as BuiltLeafy] : [], job.leafy.length ? [] : [model]);
+            });
+        }
         this.post();
     }
 
-    /** Gives the free workers the waiting builds: summer crowns first, each with the models that have the most trees about the eye first. */
+    /**
+     * Gives the free workers the waiting builds: summer crowns first, each with the models of the near regions first, then
+     * those that have the most trees about the eye.
+     */
     private post(): void {
         if (!this.free.length || !this.waiting.length) return;
         // Crowns of phases that the date lost: `ask()` queues them again if the date comes back.
         for (const { model, phase } of this.waiting.flatMap(job => job.crowns)) if (!this.phases.has(phase)) this.asked.delete(`crown:${model}|${phase}`);
         this.waiting = this.waiting.filter(job => job.crowns.every(({ phase }) => this.phases.has(phase)));
-        const near = this.near(), share = (job: Omit) => near.get((job.leafy[0] ?? job.crowns[0]).model) ?? 0;
-        this.waiting.sort((a, b) => b.leafy.length - a.leafy.length || share(b) - share(a));
+        const near = this.near(), close = new Set(this.builds(this.wanted.near).map(build => build.split('|')[0]));
+        const share = (job: Build) => near.get((job.leafy[0] ?? job.crowns[0]).model) ?? 0, first = (job: Build) => +close.has((job.leafy[0] ?? job.crowns[0]).model);
+        this.waiting.sort((a, b) => b.leafy.length - a.leafy.length || first(b) - first(a) || share(b) - share(a));
         for (const job of this.waiting.splice(0, this.free.length)) {
             const id = this.next++;
             this.jobs.set(id, job);
-            this.free.pop()!.postMessage({ id, ...job } satisfies ModelJob);
+            this.free.pop()!.postMessage({ id, leafy: job.leafy.map(({ model }) => ({ model })), crowns: job.crowns } satisfies ModelJob);
         }
     }
 
@@ -145,7 +241,7 @@ export class TreeModels {
      * only in colour draws the summer crown's impostor. Crowns of phases that the date lacks leave the pools.
      */
     private install(): void {
-        // Crowns of their own take their instance models in entry and phase order once every species
+        // Crowns of their own take their instance models in entry and phase order once every species in reach
         // has its summer crown, so the indexes never hang on which worker answers first.
         const settled = this.builds().every(build => this.leafy.has(build));
         for (const [key, entry] of this.entries) {
@@ -169,8 +265,13 @@ export class TreeModels {
         }
     }
 
-    /** The builds, by `model|evergreen`. */
-    private builds(): string[] {
-        return [...new Set([...this.entries.keys()].map(key => key.split('|').slice(0, 2).join('|')))];
+    /** The builds of the entries of these regions, by `model|evergreen`. */
+    private builds(regions = this.wanted.reach): string[] {
+        let builds = this.buildsOf.get(regions);
+        if (!builds) this.buildsOf.set(regions, (builds = [...new Set([...this.entries].filter(([, entry]) => meets(entry.regions, regions)).map(([key]) => key.split('|').slice(0, 2).join('|')))]));
+        return builds;
     }
 }
+
+/** A build's key in the device cache: each build makes one model, and both kinds of a species' summer crown are one. */
+const keyOf = ({ leafy, crowns }: Build) => (leafy.length ? `leafy/${leafy[0].model}` : `crown/${crowns[0].model}/${crowns[0].phase}`);
diff --git a/builder/web/src/lib/trailview/view.test.ts b/builder/web/src/lib/trailview/view.test.ts
index 0e1ef046ef..74a06ce8f5 100644
--- a/builder/web/src/lib/trailview/view.test.ts
+++ b/builder/web/src/lib/trailview/view.test.ts
@@ -1,5 +1,5 @@
 import { describe, expect, it } from 'vitest';
-import { defaultView, formatView, parseView, type View } from './view';
+import { defaultView, formatView, groundPlanOf, parseView, type View } from './view';
 
 const fallback = defaultView([8.37, 46.765, 8.46, 46.83], new Date(2026, 7, 15));
 
@@ -9,8 +9,15 @@ describe('the view in the address', () => {
         const search = formatView(walk, '?scale=2&lat=1');
         expect(search).toBe('?scale=2&lat=46.820500&lon=8.403000&heading=160.0&pitch=5.0&eye=1.6&date=2026-08-15&time=15:00&weather=sunny&debug=lod');
         expect(parseView(search, fallback)).toEqual(walk);
-        const fly: View = { ...walk, mode: 'fly', height: 60000, debug: 'off' };
-        expect(parseView(formatView(fly), fallback)).toEqual(fly);
+        const fly: View = { ...walk, mode: 'fly', height: 60000, debug: 'off', plan: 'faces' };
+        expect(formatView(fly, '?ground=plan')).toContain('&plan=faces');
+        expect(parseView(formatView(fly, '?ground=plan'), fallback)).toEqual(fly);
+    });
+
+    it('builds the ground plan only with ground=plan', () => {
+        expect(groundPlanOf('?ground=plan&plan=faces')).toBe(true);
+        expect(groundPlanOf('?plan=faces')).toBe(false);
+        expect(groundPlanOf('?ground=planned')).toBe(false);
     });
 });
 
diff --git a/builder/web/src/lib/trailview/view.ts b/builder/web/src/lib/trailview/view.ts
index ebfa29f929..49cf9d324f 100644
--- a/builder/web/src/lib/trailview/view.ts
+++ b/builder/web/src/lib/trailview/view.ts
@@ -1,17 +1,23 @@
 import { MAX_ALTITUDE, WALK_EYE, type Mode } from './frame/camera';
+import { FINEST } from './terrain/lod';
 
 export const WEATHERS = ['sunny', 'cloudy', 'rainy'] as const;
 /**
  * The false-colour views of the terrain shader, in the order of its `debug` switch. `cracks` clears to
  * red; `surface` paints red where drawnHeight leaves the mesh. The ground views key the material,
  * lithology and region codes, and show the snow on the date; `mask` draws the features of the mask flat.
+ * `owned` (with `ground=plan`) draws the meshes green and the terrain red, blue where the mesh owns the point: a fault.
  */
-export const DEBUG_VIEWS = ['off', 'normals', 'lod', 'cracks', 'surface', 'material', 'lithology', 'region', 'snow', 'albedo', 'mask'] as const;
+export const DEBUG_VIEWS = ['off', 'normals', 'lod', 'cracks', 'surface', 'material', 'lithology', 'region', 'snow', 'albedo', 'mask', 'owned'] as const;
 /** The clock of a view is the wall clock of the Alps, the only region that TrailView covers. */
 export const TIME_ZONE = 'Europe/Zurich';
 
+/** The views of the ground plan's debug draw: `faces` draws the plan over the view. Only with `ground=plan`. */
+export const PLAN_VIEWS = ['off', 'faces'] as const;
+
 export type Weather = (typeof WEATHERS)[number];
 export type DebugView = (typeof DEBUG_VIEWS)[number];
+export type PlanView = (typeof PLAN_VIEWS)[number];
 
 /** What the address holds. `height` is `eye` (metres above the ground) when walking, `alt` (metres above sea level) when flying. */
 export interface View {
@@ -27,6 +33,7 @@ export interface View {
     time: string;
     weather: Weather;
     debug: DebugView;
+    plan: PlanView;
 }
 
 /** The date of today in the Alps, YYYY-MM-DD: en-CA formats a date so. */
@@ -34,7 +41,7 @@ export const today = (now = new Date()) => new Intl.DateTimeFormat('en-CA', { ti
 
 /** A walk at the centre of the bounds, at noon of today in the Alps. */
 export function defaultView([west, south, east, north]: [number, number, number, number], now = new Date()): View {
-    return { lat: (south + north) / 2, lon: (west + east) / 2, heading: 0, pitch: 0, mode: 'walk', height: WALK_EYE, date: today(now), time: '12:00', weather: 'sunny', debug: 'off' };
+    return { lat: (south + north) / 2, lon: (west + east) / 2, heading: 0, pitch: 0, mode: 'walk', height: WALK_EYE, date: today(now), time: '12:00', weather: 'sunny', debug: 'off', plan: 'off' };
 }
 
 const number = (text: string | null, min: number, max: number) => {
@@ -60,13 +67,26 @@ export function parseView(search: string, fallback: View): View {
         time: /^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/.test(time) ? time : fallback.time,
         weather: choice(q.get('weather'), WEATHERS) ?? fallback.weather,
         debug: choice(q.get('debug'), DEBUG_VIEWS) ?? fallback.debug,
+        plan: choice(q.get('plan'), PLAN_VIEWS) ?? fallback.plan,
     };
 }
 
+/**
+ * Whether the page builds the ground plan: `ground=plan`. A page option, as the render scale is, read
+ * once: it decides which workers exist.
+ */
+export const groundPlanOf = (search: string) => new URLSearchParams(search).get('ground') === 'plan';
+
+/** The finest terrain level of the page, `finest=16` to `18`: a debug option that caps it as a lower quality does. Read once. */
+export const finestOf = (search: string) => number(new URLSearchParams(search).get('finest'), 16, FINEST) ?? FINEST;
+
+/** The share of the terrain's page pools that the page holds, `pool=0.5`: a debug option for the pools of a small device. Read once. */
+export const poolOf = (search: string) => number(new URLSearchParams(search).get('pool'), 0.05, 1) ?? 1;
+
 /** The query string of a view. Parameters that are not part of a view stay as they are in `search`. */
 export function formatView(view: View, search = ''): string {
     const q = new URLSearchParams(search);
-    for (const key of ['lat', 'lon', 'heading', 'pitch', 'eye', 'alt', 'date', 'time', 'weather', 'debug']) q.delete(key);
+    for (const key of ['lat', 'lon', 'heading', 'pitch', 'eye', 'alt', 'date', 'time', 'weather', 'debug', 'plan']) q.delete(key);
     q.set('lat', view.lat.toFixed(6));
     q.set('lon', view.lon.toFixed(6));
     q.set('heading', view.heading.toFixed(1));
@@ -76,6 +96,7 @@ export function formatView(view: View, search = ''): string {
     q.set('time', view.time);
     q.set('weather', view.weather);
     if (view.debug !== 'off') q.set('debug', view.debug);
+    if (view.plan !== 'off') q.set('plan', view.plan);
     // A copied address stays readable: `time=15:00`, not `time=15%3A00`.
     return `?${q}`.replace(/%3A/g, ':');
 }
diff --git a/builder/web/src/plan-timing.ts b/builder/web/src/plan-timing.ts
new file mode 100644
index 0000000000..d05d4c1c86
--- /dev/null
+++ b/builder/web/src/plan-timing.ts
@@ -0,0 +1,115 @@
+// The timing page of the ground plan: builds the prepared requests of a `requests` folder in the plan
+// worker, in any browser, and compares the times and digests with the native ones. The dev server
+// serves it; no build ships it.
+//
+//   plan-timing.html?requests=/@fs//.artifacts/ground-plan/requests/&runs=5&cells=34296-23098
+import init, { wanted } from './lib/trailview/plan/pkg/obc_ground_plan_bridge.js';
+import type { Built, Failed, PlanRequest, Timed } from './lib/trailview/plan/plan-worker';
+
+/** Absolute paths of the fixture files of a cell's inputs, as `requests` writes them. */
+interface Sources { tiles: [number, number, string][]; terrain: [number, number, number, string][] }
+interface Entry { cell: [number, number]; file: string; places: string[]; request: string; digest: string; native: Record; sources?: Sources }
+interface Row {
+    cell: string; places: string[]; faces?: number; edges?: number; junctions: number; first: number; mean: number; prepare?: number;
+    median: Record; p95: Record; native: number; ratio: number; heap: number; same: boolean; error?: string;
+}
+
+const WASM = new URL('./lib/trailview/plan/pkg/obc_ground_plan_bridge_bg.wasm', import.meta.url);
+const q = new URLSearchParams(location.search);
+const folder = q.get('requests'), runs = Math.min(50, Math.max(1, Number(q.get('runs') ?? 5) || 5)), only = q.get('cells')?.split(',');
+const about = document.querySelector('#about')!, table = document.querySelector('#cells')!, summary = document.querySelector('#summary')!;
+const copy = document.querySelector('#copy')!, output = document.querySelector('#json')!;
+
+const quantile = (values: number[], at: number) => {
+    const sorted = [...values].sort((a, b) => a - b);
+    return sorted[Math.min(sorted.length - 1, Math.floor(at * sorted.length))] ?? NaN;
+};
+const ms = (value: number | undefined) => (value !== undefined && Number.isFinite(value) ? value.toFixed(1) : '–');
+const body = async (path: string) => (await fetch(`/@fs${path}`)).arrayBuffer();
+
+async function main(): Promise {
+    if (!folder) throw new Error('Give the folder of a `requests` run: ?requests=/@fs//.artifacts/ground-plan/requests/');
+    const base = new URL(folder.endsWith('/') ? folder : `${folder}/`, location.href);
+    const index: Entry[] = await (await fetch(new URL('index.json', base))).json();
+    const entries = index.filter(({ cell }) => !only || only.includes(cell.join('-')));
+    const module = await WebAssembly.compile(await (await fetch(WASM)).arrayBuffer());
+    // The page's own instance names the pages of a cell, as the viewer's main thread does.
+    await init({ module_or_path: module });
+    const timing = performance.getEntriesByName(WASM.href)[0] as PerformanceResourceTiming | undefined;
+    const worker = new Worker(new URL('./lib/trailview/plan/plan-worker.ts', import.meta.url), { type: 'module' });
+    const next = () => new Promise(resolve => (worker.onmessage = ({ data }) => resolve(data)));
+    worker.postMessage({ type: 'start', module } satisfies PlanRequest);
+    const started = await next<{ type: 'ready'; error?: string }>();
+    if (started.error) throw new Error(`The plan worker did not start: ${started.error}`);
+    const head = {
+        userAgent: navigator.userAgent, cores: navigator.hardwareConcurrency, runs,
+        wasm: { bytes: timing?.decodedBodySize || undefined, transferred: timing?.encodedBodySize || undefined },
+    };
+    about.textContent = `${head.userAgent}\ncores ${head.cores} · runs ${runs} · WASM ${head.wasm.bytes ? `${(head.wasm.bytes / 1024).toFixed(0)} KiB` : 'size unknown'}${head.wasm.transferred ? ` (${(head.wasm.transferred / 1024).toFixed(0)} KiB sent)` : ''} · ${entries.length} cells`
+        + '\n"first": the first run of a cell; only the first row runs on a cold instance. "mean": all runs after the first over their count, which holds where the clock is coarse (Safari: 1 ms).'
+        + '\n"prepare": gunzip and WebP decode of the cell\'s fixture files in the worker, with its cache of 16 terrain tiles, as in the viewer.';
+    let stages: string[] = [];
+    const rows: Row[] = [];
+    for (const [id, entry] of entries.entries()) {
+        const request = await (await fetch(new URL(entry.file, base))).arrayBuffer();
+        worker.postMessage({ type: 'time', id, request, runs } satisfies PlanRequest, [request]);
+        const result = await next(), cell = entry.cell.join('-');
+        if (!result.ok) {
+            rows.push({ cell, places: entry.places, junctions: 0, first: NaN, mean: NaN, median: {}, p95: {}, native: entry.native.total, ratio: NaN, heap: 0, same: false, error: result.error });
+        } else {
+            stages = [...Object.keys(entry.native).filter(stage => stage !== 'total'), 'total'];
+            const per = (i: number) => result.runs.map(times => times[i]);
+            const median = Object.fromEntries(stages.map((stage, i) => [stage, quantile(per(i), 0.5)]));
+            const p95 = Object.fromEntries(stages.map((stage, i) => [stage, quantile(per(i), 0.95)]));
+            const stats = JSON.parse(result.stats) as { graph: { junctions: number }; faces?: { faces: number; edges: number } };
+            rows.push({
+                cell, places: entry.places, faces: stats.faces?.faces, edges: stats.faces?.edges, junctions: stats.graph.junctions, first: result.first.at(-1)!, mean: result.mean,
+                prepare: entry.sources && await prepare(worker, next, id, entry),
+                median, p95, native: entry.native.total, ratio: result.mean / entry.native.total, heap: result.heap, same: result.digest === entry.digest,
+            });
+        }
+        draw(rows, stages);
+    }
+    worker.terminate();
+    const ok = rows.filter(row => !row.error), means = ok.map(row => row.mean);
+    const result = {
+        ...head, cells: rows,
+        summary: {
+            median: quantile(means, 0.5), p95: quantile(means, 0.95), prepare: quantile(ok.flatMap(row => (row.prepare === undefined ? [] : [row.prepare])), 0.5),
+            heap: Math.max(0, ...ok.map(row => row.heap)), same: rows.filter(row => row.same).length, of: rows.length,
+        },
+        done: true,
+    };
+    summary.textContent = `over ${ok.length} cells: median ${ms(result.summary.median)} ms · p95 ${ms(result.summary.p95)} ms of the per-cell means · prepare median ${ms(result.summary.prepare)} ms · largest heap ${(result.summary.heap / 2 ** 20).toFixed(0)} MiB · ${result.summary.same} of ${result.summary.of} digests equal the native ones`;
+    Object.assign(window, { planTiming: result });
+    // The Clipboard API needs a secure context: plain HTTP on a LAN address is none, so the text area holds the JSON too.
+    output.value = JSON.stringify(result, null, 1);
+    output.hidden = false;
+    copy.disabled = !isSecureContext;
+    copy.onclick = () => void navigator.clipboard.writeText(output.value);
+}
+
+/** The worker's `prepare` of a cell from its fixture files: one build with the inputs as the viewer sends them. */
+async function prepare(worker: Worker, next: () => Promise, id: number, { cell: [x, y], sources }: Entry): Promise {
+    const tiles = await Promise.all(sources!.tiles.map(async ([column, row, path]) => ({ column, row, body: await body(path) })));
+    const terrain = await Promise.all(sources!.terrain.map(async ([z, tx, ty, path]) => ({ z, x: tx, y: ty, body: await body(path) })));
+    const message: PlanRequest = { type: 'build', id, cell: { x, y }, tiles, terrain, pages: wanted(x, y), debug: false };
+    worker.postMessage(message, tiles.map(tile => tile.body));
+    const built = await next();
+    return built.ok ? built.prepare : undefined;
+}
+
+function draw(rows: Row[], stages: string[]): void {
+    const cells = (values: string[], tag = 'td') => values.map(value => `<${tag}>${value}`).join('');
+    table.innerHTML = `${cells(['cell', 'places', 'faces', 'edges', 'junctions', 'first', 'mean', 'prepare', ...stages.flatMap(s => [`${s} median`, `${s} p95`]), 'native', 'ratio (mean)', 'heap MiB', 'digest'], 'th')}`
+        + rows.map(row => `${cells([
+            row.cell, row.places.join(' '), String(row.faces ?? '–'), String(row.edges ?? '–'), String(row.junctions), ms(row.first), ms(row.mean), ms(row.prepare),
+            ...stages.flatMap(s => [ms(row.median[s]), ms(row.p95[s])]), ms(row.native), Number.isFinite(row.ratio) ? row.ratio.toFixed(2) : '–', (row.heap / 2 ** 20).toFixed(0),
+            row.error ? `${row.error}` : row.same ? 'equal' : 'differs',
+        ])}`).join('');
+}
+
+main().catch((error: unknown) => {
+    about.textContent = error instanceof Error ? error.message : String(error);
+    Object.assign(window, { planTiming: { error: about.textContent, done: true } });
+});
diff --git a/builder/web/src/trailview.ts b/builder/web/src/trailview.ts
index 6e80f3c04c..c0b77c3ebd 100644
--- a/builder/web/src/trailview.ts
+++ b/builder/web/src/trailview.ts
@@ -3,13 +3,16 @@ import { activeRelease, pageRelease } from './lib/planner/release';
 import { TrailView } from './lib/trailview/engine';
 import { Gpu } from './lib/trailview/gpu/device';
 import { hud } from './lib/trailview/hud';
+import { preload } from './lib/trailview/plan/bridge';
+import { WORKERS } from './lib/trailview/terrain/model';
 import { scaleOf } from './lib/trailview/resolve/targets';
 import { canRenderStills, credits, still, type StillJob } from './lib/trailview/still';
 import { coverView } from './lib/trailview/still-view';
-import { defaultView, formatView, parseView } from './lib/trailview/view';
+import { defaultView, finestOf, formatView, groundPlanOf, parseView, poolOf } from './lib/trailview/view';
 
 /** The address follows the view at most this often. */
 const ADDRESS_MS = 200;
+const NO_WEBGPU = 'TrailView needs WebGPU. Open this page in a current version of Chrome, Edge or Safari.';
 
 function notice(text: string): void {
     const message = document.createElement('p');
@@ -19,15 +22,23 @@ function notice(text: string): void {
     document.body.replaceChildren(message);
 }
 
-/** The device and the release; undefined after the notice that the browser has no WebGPU. */
-async function open(): Promise<{ gpu: Gpu; release: PlannerConfig } | undefined> {
+/**
+ * The release and the device, and with `plan` the plan's bridge and its workers, which load side by side; undefined
+ * after the notice that the browser has no WebGPU. The device rejects when the browser has no adapter.
+ */
+async function open(plan = false): Promise<{ gpu: Promise; release: PlannerConfig } | undefined> {
+    if (!navigator.gpu) return void notice(NO_WEBGPU);
     const preview: string | undefined = import.meta.env.VITE_PLANNER_CONFIG;
     const config = (async () => plannerConfig(preview ? JSON.parse(preview) : await activeRelease()))();
     config.catch(() => {});
-    const gpu = await Gpu.request();
-    if (!gpu) return void notice('TrailView needs WebGPU. Open this page in a current version of Chrome, Edge or Safari.');
-    // `start` reports a failed compile.
-    TrailView.prepare(gpu).catch(() => {});
+    // `start` reports a failed load. The pipelines compile at the attach: a compile from the device on would hold the
+    // start of the ground's workers, whose WebGL waits for the same GPU process.
+    if (plan) preload(WORKERS);
+    const gpu = Gpu.request().then(gpu => {
+        if (!gpu) throw new Error(NO_WEBGPU);
+        return gpu;
+    });
+    gpu.catch(() => {});
     const release = await config;
     pageRelease(release.id);
     return { gpu, release };
@@ -37,7 +48,9 @@ async function open(): Promise<{ gpu: Gpu; release: PlannerConfig } | undefined>
 async function stills(): Promise {
     const opened = await open();
     if (!opened) return;
-    const { gpu, release } = opened;
+    const { release } = opened, gpu = await opened.gpu;
+    // No engine runs before the first still, so no worker waits for this compile.
+    TrailView.prepare(gpu).catch(() => {});
     Object.assign(window, {
         trailviewStill: {
             release: release.id,
@@ -50,11 +63,11 @@ async function stills(): Promise {
 }
 
 async function main(): Promise {
-    const opened = await open();
+    const plan = groundPlanOf(location.search), opened = await open(plan);
     if (!opened) return;
     const { gpu, release } = opened;
     const view = parseView(location.search, defaultView(release.bounds));
-    const engine = await TrailView.start(document.querySelector('canvas')!, gpu, release, view, scaleOf(location.search));
+    const engine = await TrailView.start(document.querySelector('canvas')!, gpu, release, view, scaleOf(location.search), { plan, finest: finestOf(location.search), pool: poolOf(location.search) });
 
     const address = () => `${location.origin}${location.pathname}${formatView(engine.view, location.search)}`;
     let writing: ReturnType | undefined;
diff --git a/builder/web/test-support/fake-caches.ts b/builder/web/test-support/fake-caches.ts
new file mode 100644
index 0000000000..3adeed4822
--- /dev/null
+++ b/builder/web/test-support/fake-caches.ts
@@ -0,0 +1,26 @@
+// Cache Storage in memory for the device cache's tests: what a put keeps survives an engine, as on a device.
+export class FakeCaches {
+    caches = new Map>();
+
+    async open(name: string) {
+        const entries = this.caches.get(name) ?? new Map();
+        this.caches.set(name, entries);
+        return {
+            match: async (url: string) => {
+                const entry = entries.get(url);
+                return entry && new Response(entry.body.slice(0), { headers: entry.headers });
+            },
+            put: async (url: string, response: Response) => void entries.set(url, { body: await response.arrayBuffer(), headers: response.headers }),
+            delete: async (url: string) => entries.delete(url),
+            keys: async () => [...entries.keys()].map(url => ({ url })),
+        };
+    }
+
+    async keys() {
+        return [...this.caches.keys()];
+    }
+
+    async delete(name: string) {
+        return this.caches.delete(name);
+    }
+}
diff --git a/builder/web/test-support/trailview/census-baseline.json b/builder/web/test-support/trailview/census-baseline.json
index 94cdb2ea9c..6a8225ffb5 100644
--- a/builder/web/test-support/trailview/census-baseline.json
+++ b/builder/web/test-support/trailview/census-baseline.json
@@ -1 +1 @@
-{ "folds": 266, "slivers": 261, "twists": 713 }
+{ "folds": 281, "slivers": 295, "twists": 772 }
diff --git a/builder/web/test-support/trailview/census.ts b/builder/web/test-support/trailview/census.ts
index 4d5a4e095b..bac6cdb5f3 100644
--- a/builder/web/test-support/trailview/census.ts
+++ b/builder/web/test-support/trailview/census.ts
@@ -17,7 +17,7 @@ import { between } from '../../src/lib/trailview/roads/stations';
 import { decodeFeatures, DEEPEST, type Feature } from '../../src/lib/trailview/stream/features';
 import { AnchoredBuilder } from '../../src/lib/trailview/structures/anchored';
 import { MeshBuilder } from '../../src/lib/trailview/structures/mesh';
-import { features, insideRings, metresPerUnit, PATH, RIVER, ROAD, STREAM, walkOf, type Line } from '../../src/lib/trailview/terrain/bins';
+import { features, insideRings, metresPerUnit, RIVER, STREAM, walkOf, type Line } from '../../src/lib/trailview/terrain/bins';
 import { cornerAt } from '../../src/lib/trailview/terrain/corners';
 import { CHILD, OWNER, size, type Node } from '../../src/lib/trailview/terrain/lod';
 import { LEFT, RIGHT } from '../../src/lib/trailview/terrain/town';
@@ -303,9 +303,9 @@ const nothing = () => ({ mesh: new MeshBuilder(), anchored: new AnchoredBuilder(
 export function objectsOnWays(tiles: FixtureTile[]): number[] {
     const out: number[] = [];
     for (const { tile, list } of tiles) {
-        const shapes = features(list, tile), { lines, buildings } = shapes, cores = coresOf(shapes), cornered = (x: number, y: number) => !!cornerAt(lines, x, y);
+        const shapes = features(list, tile), { lines } = shapes, cores = coresOf(shapes), cornered = (x: number, y: number) => !!cornerAt(lines, x, y);
         const build: Build = {
-            far: nothing(), near: nothing(), owns: (x, y) => inSquare(tile, x, y), ways: lines.filter(line => line.kind === ROAD || line.kind === PATH), cores, taken: [], buildings, cornered,
+            far: nothing(), near: nothing(), owns: (x, y) => inSquare(tile, x, y), shapes, cores, taken: [], cornered,
             place: ({ x, y }) => {
                 if (coreAt(cores, x, y) || cornered(x, y)) out.push(x, y);
             },
diff --git a/builder/web/tests/browser/playwright.trailview.config.js b/builder/web/tests/browser/playwright.trailview.config.js
index 01c0943d59..919300f3cc 100644
--- a/builder/web/tests/browser/playwright.trailview.config.js
+++ b/builder/web/tests/browser/playwright.trailview.config.js
@@ -1,6 +1,6 @@
 import { defineConfig } from '@playwright/test';
 import { loopbackPort } from '../../../../tools/loopback_port.mjs';
-import { EXECUTABLE, SWIFTSHADER } from './trailview/harness.js';
+import { EXECUTABLE, GPU, SWIFTSHADER } from './trailview/harness.js';
 
 // The shipped TrailView build, served from loopback. `pretest:trailview` points it at the fixture
 // config, and the test answers its tile host in the page, so nothing leaves the machine.
@@ -23,7 +23,8 @@ export default defineConfig({
     browserName: 'chromium',
     baseURL: `http://127.0.0.1:${PORT}`,
     viewport: { width: 960, height: 600 },
-    launchOptions: { executablePath: EXECUTABLE, args: SWIFTSHADER },
+    // OBC_TRAILVIEW_GPU=1 draws on the machine's GPU.
+    launchOptions: { executablePath: EXECUTABLE, args: process.env.OBC_TRAILVIEW_GPU ? GPU : SWIFTSHADER },
     actionTimeout: 15_000,
     navigationTimeout: 15_000,
     screenshot: 'only-on-failure',
diff --git a/builder/web/tests/browser/trailview/determinism.mjs b/builder/web/tests/browser/trailview/determinism.mjs
new file mode 100644
index 0000000000..c930d2e218
--- /dev/null
+++ b/builder/web/tests/browser/trailview/determinism.mjs
@@ -0,0 +1,157 @@
+// Draws each view several times and compares the runs: the hashes of the drawn terrain (engine.hashes:
+// each drawn page's heights `h/` and mask `m/`, each records block `r/`, each piece's corners `p/`) and the
+// pixels of the shots. A deterministic view gives one hash per region and equal shots. A debug tool, not a test.
+//
+//   npm run pretest:trailview --prefix builder/web/tests/browser     # build against the fixture
+//   node builder/web/tests/browser/trailview/determinism.mjs --views FILE --out DIR [--runs N] [--pages N] [--query Q] [--gpu]
+//
+// --runs is the runs of each view (default 8), --pages the runs that draw at once, each on its own page
+// (default 1); the runs of the views interleave. A run waits for the idle view, then until the records and
+// the pieces stop changing, and reads the hashes twice, a second apart: a region that changes between the
+// reads counts as unsettled. Writes DIR//.png, DIR/hashes.json and DIR/report.md, and prints the report.
+
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { parseArgs } from 'node:util';
+import { errorsOf, launch, routeFixture, serve } from './harness.js';
+
+const { values } = parseArgs({
+    options: {
+        views: { type: 'string' },
+        out: { type: 'string' },
+        runs: { type: 'string', default: '8' },
+        pages: { type: 'string', default: '1' },
+        query: { type: 'string' },
+        gpu: { type: 'boolean' },
+    },
+});
+const TIMEOUT_MS = 120_000;
+const runs = Number(values.runs), pages = Number(values.pages);
+const views = JSON.parse(readFileSync(values.views, 'utf8'));
+mkdirSync(values.out, { recursive: true });
+const { origin, close } = await serve();
+const browser = await launch(values.gpu);
+const idle = page => page.evaluate(ms => Promise.race([
+    window.trailView.waitForIdle(),
+    new Promise((_, reject) => setTimeout(() => reject(new Error(`not idle after ${ms} ms`)), ms)),
+]), TIMEOUT_MS);
+const snap = page => page.evaluate(() => {
+    const s = window.trailView.stats(), p = s.terrain?.pieces, r = s.terrain?.records;
+    return { key: JSON.stringify([p?.cells, p?.drawn, p?.triangles, r?.cells, r?.building]), building: r?.building ?? 0, records: r && { cells: r.cells, restarts: r.restarts, error: r.error } };
+});
+
+async function run({ name, view }, k) {
+    const page = await browser.newPage({ viewport: { width: 1920, height: 960 }, deviceScaleFactor: 1 });
+    const errors = errorsOf(page);
+    await routeFixture(page);
+    await page.goto(`${origin}/trailview.html${view}${values.query ? `&${values.query}` : ''}`);
+    await page.waitForFunction(() => window.trailView, null, { timeout: TIMEOUT_MS });
+    await idle(page);
+    await page.evaluate(() => window.trailView.showMarker(null));
+    await page.addStyleTag({ content: '#hud { display: none; }' });
+    await idle(page);
+    let prev = await snap(page);
+    for (let round = 0; round < 8; round++) {
+        await page.waitForTimeout(1000);
+        await idle(page);
+        const now = await snap(page);
+        if (now.key === prev.key && now.building === 0) break;
+        prev = now;
+    }
+    const first = await page.evaluate(() => window.trailView.hashes());
+    await page.waitForTimeout(1000);
+    await idle(page);
+    const hashes = await page.evaluate(() => window.trailView.hashes());
+    const unsettled = Object.keys(hashes).filter(region => first[region] !== undefined && first[region] !== hashes[region]);
+    mkdirSync(join(values.out, name), { recursive: true });
+    const file = join(values.out, name, `${k}.png`);
+    await page.screenshot({ path: file });
+    await page.close();
+    console.log(JSON.stringify({ name, run: k, regions: Object.keys(hashes).length, unsettled: unsettled.length, records: prev.records, errors }));
+    return { name, run: k, file, hashes, unsettled, records: prev.records, errors };
+}
+
+/** Per later run, the pixels that differ from the first run's and those by more than 8 in a channel; `diff` gets a PNG of the run that differs most: the first run dimmed, magenta where it differs by more than 8. */
+async function pixelDiffs(files, diff) {
+    const page = await browser.newPage();
+    const out = await page.evaluate(async datas => {
+        const load = async data => {
+            const img = new Image();
+            img.src = `data:image/png;base64,${data}`;
+            await img.decode();
+            const c = new OffscreenCanvas(img.width, img.height), g = c.getContext('2d');
+            g.drawImage(img, 0, 0);
+            return [g.getImageData(0, 0, img.width, img.height).data, img.width, img.height];
+        };
+        const [base, width, height] = await load(datas[0]), counts = [];
+        let worst = { big: 0 }, picture;
+        for (const data of datas.slice(1)) {
+            const [other] = await load(data);
+            let any = 0, big = 0;
+            const marks = new Uint8ClampedArray(base.length);
+            for (let i = 0; i < base.length; i += 4) {
+                const d = Math.max(Math.abs(base[i] - other[i]), Math.abs(base[i + 1] - other[i + 1]), Math.abs(base[i + 2] - other[i + 2]));
+                if (d > 0) any++;
+                if (d > 8) big++;
+                marks.set(d > 8 ? [255, 0, 255, 255] : [base[i] / 3, base[i + 1] / 3, base[i + 2] / 3, 255], i);
+            }
+            counts.push([any, big]);
+            if (big > worst.big) worst = { big, marks };
+        }
+        if (worst.marks) {
+            const c = new OffscreenCanvas(width, height);
+            c.getContext('2d').putImageData(new ImageData(worst.marks, width, height), 0, 0);
+            const bytes = new Uint8Array(await (await c.convertToBlob({ type: 'image/png' })).arrayBuffer());
+            picture = btoa(Array.from(bytes, b => String.fromCharCode(b)).join(''));
+        }
+        return { counts, picture };
+    }, files.map(file => readFileSync(file).toString('base64')));
+    await page.close();
+    if (out.picture) writeFileSync(diff, Buffer.from(out.picture, 'base64'));
+    return out.counts;
+}
+
+const results = [];
+try {
+    const queue = Array.from({ length: runs }, (_, k) => views.map(view => [view, k])).flat();
+    let next = 0;
+    await Promise.all(Array.from({ length: pages }, async () => {
+        while (next < queue.length) {
+            const [view, k] = queue[next++];
+            results.push(await run(view, k).catch(error => ({ name: view.name, run: k, error: error.message })));
+        }
+    }));
+    writeFileSync(join(values.out, 'hashes.json'), JSON.stringify(results, null, 1));
+    const lines = [`Runs per view: ${runs}, pages at once: ${pages}, query: ${values.query ?? '(none)'}`, '',
+        '| View | Runs | Regions in every run | Differ (h/m/r/p/w) | In some runs | Unsettled | Pixels ≠ run 0 (max, >8 max) |', '| --- | --- | --- | --- | --- | --- | --- |'];
+    const details = [];
+    for (const { name } of views) {
+        const done = results.filter(r => r.name === name && r.hashes).sort((a, b) => a.run - b.run);
+        const failed = results.filter(r => r.name === name && r.error);
+        if (!done.length) {
+            lines.push(`| ${name} | 0 | | | | | ${failed.map(f => f.error).join('; ')} |`);
+            continue;
+        }
+        const regions = new Set(done.flatMap(r => Object.keys(r.hashes)));
+        const every = [...regions].filter(region => done.every(r => region in r.hashes));
+        const differ = every.filter(region => new Set(done.map(r => r.hashes[region])).size > 1);
+        const kinds = ['h', 'm', 'r', 'p', 'w'].map(kind => differ.filter(region => region.startsWith(`${kind}/`)).length).join('/');
+        const unsettled = new Set(done.flatMap(r => r.unsettled));
+        const pixels = done.length > 1 ? await pixelDiffs(done.map(r => r.file), join(values.out, name, 'diff.png')) : [];
+        const max = pixels.reduce((m, [any, big]) => [Math.max(m[0], any), Math.max(m[1], big)], [0, 0]);
+        lines.push(`| ${name} | ${done.length}${failed.length ? ` (+${failed.length} failed)` : ''} | ${every.length} | ${differ.length} (${kinds}) | ${regions.size - every.length} | ${unsettled.size} | ${max[0]}, ${max[1]} |`);
+        for (const region of differ) {
+            const groups = new Map();
+            done.forEach(r => groups.set(r.hashes[region], [...(groups.get(r.hashes[region]) ?? []), r.run]));
+            details.push(`- ${name} ${region}: ${[...groups.values()].map(g => `runs ${g.join(',')}`).join(' | ')}`);
+        }
+        if (unsettled.size) details.push(`- ${name} unsettled: ${[...unsettled].slice(0, 20).join(', ')}`);
+        if (pixels.length) details.push(`- ${name} pixels vs run 0: ${pixels.map(([any, big]) => `${any}/${big}`).join(' ')}`);
+    }
+    const report = [...lines, '', ...details].join('\n');
+    writeFileSync(join(values.out, 'report.md'), `${report}\n`);
+    console.log(report);
+} finally {
+    await browser.close();
+    close();
+}
diff --git a/builder/web/tests/browser/trailview/fixture/features/10/535/360.bin b/builder/web/tests/browser/trailview/fixture/features/10/535/360.bin
index 3fd783fb7d..0da71d84fc 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/10/535/360.bin and b/builder/web/tests/browser/trailview/fixture/features/10/535/360.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/10/535/361.bin b/builder/web/tests/browser/trailview/fixture/features/10/535/361.bin
index fe7a96ca36..4e6a2e3669 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/10/535/361.bin and b/builder/web/tests/browser/trailview/fixture/features/10/535/361.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/10/536/360.bin b/builder/web/tests/browser/trailview/fixture/features/10/536/360.bin
index b71883c858..31e501ae7f 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/10/536/360.bin and b/builder/web/tests/browser/trailview/fixture/features/10/536/360.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/10/536/361.bin b/builder/web/tests/browser/trailview/fixture/features/10/536/361.bin
index 0b21c103f3..58a423a973 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/10/536/361.bin and b/builder/web/tests/browser/trailview/fixture/features/10/536/361.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/11/1071/721.bin b/builder/web/tests/browser/trailview/fixture/features/11/1071/721.bin
index 9c38dbf63a..296841fca1 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/11/1071/721.bin and b/builder/web/tests/browser/trailview/fixture/features/11/1071/721.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/11/1071/722.bin b/builder/web/tests/browser/trailview/fixture/features/11/1071/722.bin
index 1d4c76407a..ff0f40ccaa 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/11/1071/722.bin and b/builder/web/tests/browser/trailview/fixture/features/11/1071/722.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/11/1072/721.bin b/builder/web/tests/browser/trailview/fixture/features/11/1072/721.bin
index 85dc41a477..28317a8470 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/11/1072/721.bin and b/builder/web/tests/browser/trailview/fixture/features/11/1072/721.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/11/1072/722.bin b/builder/web/tests/browser/trailview/fixture/features/11/1072/722.bin
index 33cc4d1648..c8a4369998 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/11/1072/722.bin and b/builder/web/tests/browser/trailview/fixture/features/11/1072/722.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/12/2143/1443.bin b/builder/web/tests/browser/trailview/fixture/features/12/2143/1443.bin
index 7cf5cd1046..10c41a7172 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/12/2143/1443.bin and b/builder/web/tests/browser/trailview/fixture/features/12/2143/1443.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/12/2143/1444.bin b/builder/web/tests/browser/trailview/fixture/features/12/2143/1444.bin
index b6209ac09c..02a498598d 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/12/2143/1444.bin and b/builder/web/tests/browser/trailview/fixture/features/12/2143/1444.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/12/2144/1443.bin b/builder/web/tests/browser/trailview/fixture/features/12/2144/1443.bin
index 81b82db67a..32214b7aa4 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/12/2144/1443.bin and b/builder/web/tests/browser/trailview/fixture/features/12/2144/1443.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/12/2144/1444.bin b/builder/web/tests/browser/trailview/fixture/features/12/2144/1444.bin
index 8e684429ca..6418475372 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/12/2144/1444.bin and b/builder/web/tests/browser/trailview/fixture/features/12/2144/1444.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4286/2887.bin b/builder/web/tests/browser/trailview/fixture/features/13/4286/2887.bin
index ba05195cb7..96f51ddfd7 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4286/2887.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4286/2887.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4286/2888.bin b/builder/web/tests/browser/trailview/fixture/features/13/4286/2888.bin
index cdc25a2fc6..226de4c5da 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4286/2888.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4286/2888.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4286/2889.bin b/builder/web/tests/browser/trailview/fixture/features/13/4286/2889.bin
index 88b5a34e03..698c616289 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4286/2889.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4286/2889.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4287/2887.bin b/builder/web/tests/browser/trailview/fixture/features/13/4287/2887.bin
index 1be7e41b4c..bb61b2fb8e 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4287/2887.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4287/2887.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4287/2888.bin b/builder/web/tests/browser/trailview/fixture/features/13/4287/2888.bin
index 49d75886e0..ddefbe8642 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4287/2888.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4287/2888.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4287/2889.bin b/builder/web/tests/browser/trailview/fixture/features/13/4287/2889.bin
index 146939b53e..b07a7d5f64 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4287/2889.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4287/2889.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4288/2887.bin b/builder/web/tests/browser/trailview/fixture/features/13/4288/2887.bin
index 1310f4e0b5..84107a7e39 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4288/2887.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4288/2887.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4288/2888.bin b/builder/web/tests/browser/trailview/fixture/features/13/4288/2888.bin
index ac0263b65b..8590c8d89d 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4288/2888.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4288/2888.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/13/4288/2889.bin b/builder/web/tests/browser/trailview/fixture/features/13/4288/2889.bin
index e1881de964..ac1efc214c 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/13/4288/2889.bin and b/builder/web/tests/browser/trailview/fixture/features/13/4288/2889.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/8/133/90.bin b/builder/web/tests/browser/trailview/fixture/features/8/133/90.bin
index 8ee554e76c..f39494b67f 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/8/133/90.bin and b/builder/web/tests/browser/trailview/fixture/features/8/133/90.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/8/134/90.bin b/builder/web/tests/browser/trailview/fixture/features/8/134/90.bin
index d442835d7c..78eb7381b5 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/8/134/90.bin and b/builder/web/tests/browser/trailview/fixture/features/8/134/90.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/9/267/180.bin b/builder/web/tests/browser/trailview/fixture/features/9/267/180.bin
index e7b93d1982..9d3483674f 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/9/267/180.bin and b/builder/web/tests/browser/trailview/fixture/features/9/267/180.bin differ
diff --git a/builder/web/tests/browser/trailview/fixture/features/9/268/180.bin b/builder/web/tests/browser/trailview/fixture/features/9/268/180.bin
index 6b5b35d08a..88018a4788 100644
Binary files a/builder/web/tests/browser/trailview/fixture/features/9/268/180.bin and b/builder/web/tests/browser/trailview/fixture/features/9/268/180.bin differ
diff --git a/builder/web/tests/browser/trailview/flight.mjs b/builder/web/tests/browser/trailview/flight.mjs
index 6e22f371c7..31b90bbb5d 100644
--- a/builder/web/tests/browser/trailview/flight.mjs
+++ b/builder/web/tests/browser/trailview/flight.mjs
@@ -3,7 +3,7 @@
 // corridors, and the requests.
 //
 //   npm run pretest:trailview --prefix builder/web/tests/browser     # build against the fixture
-//   node builder/web/tests/browser/trailview/flight.mjs --gpu [--flights FILE] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--cracks N] [--audit N] [--resolve MS]
+//   node builder/web/tests/browser/trailview/flight.mjs --gpu [--flights FILE] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--cracks N] [--audit N] [--resolve MS] [--query Q]
 //
 // A pass prints its median, p95 and max over the frames that ran it, their number, and `amortized`,
 // its time summed over the flight per frame: the `ground` compute runs only on frames with arriving pages.
@@ -21,7 +21,9 @@
 // idle and adds up its invariant audit (`trailView.audit()`). --resolve names the expected median of the
 // `resolve` pass, a fixed load per pixel: a flight past RESOLVE_DRIFT_MS prints `valid: false`. --gpu
 // draws 2560 × 1600 pixels on the machine's GPU, headless on Linux and in a window on macOS, with exact
-// timestamps. Without it SwiftShader draws on the CPU, and its times say nothing about a GPU.
+// timestamps. Without it SwiftShader draws on the CPU, and its times say nothing about a GPU. With the
+// ground plan's meshes a line holds the cells that draw, their triangles and slots in view, and their bytes.
+// --query Q appends `&Q` to the start view of each flight, such as `ground=plan`.
 
 import { readFileSync } from 'node:fs';
 import { parseArgs } from 'node:util';
@@ -38,6 +40,7 @@ const { values } = parseArgs({
         audit: { type: 'string' },
         resolve: { type: 'string' },
         gpu: { type: 'boolean' },
+        query: { type: 'string' },
     },
 });
 /** The owner's limit: past it, the GPU clock moved or another job ran, and the flight does not count. */
@@ -96,7 +99,7 @@ try {
         const [width, height] = flight.viewport ?? [1280, 800];
         const page = await browser.newPage({ viewport: { width, height }, deviceScaleFactor: 2 });
         await routeFixture(page, values.tiles, values.ground, values.colour, values.features);
-        await page.goto(`${origin}/trailview.html${values.cracks ? `${flight.from}&debug=cracks` : flight.from}`);
+        await page.goto(`${origin}/trailview.html${flight.from}${values.cracks ? '&debug=cracks' : ''}${values.query ? `&${values.query}` : ''}`);
         await page.waitForFunction(() => window.trailView, null, { timeout: 60_000 });
         await page.evaluate(() => window.trailView.waitForIdle());
         if (values.cracks) await page.addStyleTag({ content: '#hud { display: none; }' });
@@ -152,6 +155,7 @@ try {
             nodes: summary(of('nodes')), triangles: summary(of('triangles')), quality: summary(of('quality')),
             pages: { stored: Math.max(...of('resident').map(r => r.stored)), synth: Math.max(...of('resident').map(r => r.synth)), capacity: last.terrain.capacity },
             ...(last.terrain.roads ? { roads: { first: frames[0].terrain.roads, vertices: summary(of('roads').map(r => r.vertices)), triangles: summary(of('roads').map(r => r.triangles)), dropped: Math.max(...of('roads').map(r => r.dropped)) } } : {}),
+            ...(last.terrain.pieces ? { pieces: { drawn: summary(of('pieces').map(p => p.drawn)), triangles: summary(of('pieces').map(p => p.triangles)), steps: summary(of('pieces').map(p => p.steps)), megabytes: +(last.terrain.pieces.bytes / 2 ** 20).toFixed(1) } } : {}),
             ground: { wanted: summary(frames.map(frame => frame.ground.wanted)), short: summary(frames.map(frame => frame.ground.shortage)), capacity: last.ground.capacity, colour: last.ground.colour },
             poolMegabytes: Object.fromEntries(stats.pools.map(([pool, bytes]) => [pool, +(bytes / 2 ** 20).toFixed(1)])),
             requests: last.requests, megabytes: +(last.bytes / 2 ** 20).toFixed(2),
diff --git a/builder/web/tests/browser/trailview/harness.js b/builder/web/tests/browser/trailview/harness.js
index 1b6fdc97c5..83fcb1774b 100644
--- a/builder/web/tests/browser/trailview/harness.js
+++ b/builder/web/tests/browser/trailview/harness.js
@@ -9,7 +9,7 @@ export const SWIFTSHADER = ['--enable-unsafe-webgpu', '--enable-features=Vulkan'
 /** A Chromium other than the one Playwright installed, such as /opt/pw-browsers/chromium. */
 export const EXECUTABLE = process.env.OBC_CHROMIUM || undefined;
 /** WebGPU on the machine's GPU. Chromium on Linux gives no adapter without Vulkan. */
-const GPU = ['--enable-webgpu-developer-features', ...(process.platform === 'linux' ? ['--enable-unsafe-webgpu', '--enable-features=Vulkan', '--use-angle=vulkan', '--ignore-gpu-blocklist'] : [])];
+export const GPU = ['--enable-webgpu-developer-features', ...(process.platform === 'linux' ? ['--enable-unsafe-webgpu', '--enable-features=Vulkan', '--use-angle=vulkan', '--ignore-gpu-blocklist'] : [])];
 /**
  * The browser of a script: with `gpu` the machine's GPU, else SwiftShader. Only a GPU `window` is not
  * headless, and macOS keeps one by default: its GPU is proven in a window only. With OBC_BROWSER_WS set,
diff --git a/builder/web/tests/browser/trailview/label-probe.mjs b/builder/web/tests/browser/trailview/label-probe.mjs
new file mode 100644
index 0000000000..bfebafffbf
--- /dev/null
+++ b/builder/web/tests/browser/trailview/label-probe.mjs
@@ -0,0 +1,71 @@
+// The viewer's model.wgsl against the crate's `find` at the whole-unit points that the debug tool's
+// `heights --gpu-check --out DIR` writes to labels.json: the label of each point, on and beside the
+// candidates' edges too. Prints the points whose labels differ. One GPU user at a time:
+//   flock /tmp/trailview-gpu.lock node tests/browser/trailview/label-probe.mjs DIR
+import { copyFileSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { include } from '../../../src/lib/trailview/gpu/include.ts';
+import { launch, serve } from './harness.js';
+
+const ROOT = new URL('../../../src/lib/trailview/', import.meta.url).pathname;
+const [dir] = process.argv.slice(2);
+if (!dir) throw new Error('label-probe.mjs DIR (of debug heights --gpu-check)');
+const points = JSON.parse(readFileSync(join(dir, 'labels.json'), 'utf8'));
+const code = include('terrain/model.wgsl', path => readFileSync(ROOT + path, 'utf8')) + `
+@group(0) @binding(1) var probe_in: array;
+@group(0) @binding(3) var probe_out: array;
+@compute @workgroup_size(64) fn probe(@builtin(global_invocation_id) id: vec3u) {
+    if (id.x >= arrayLength(&probe_out)) { return; }
+    let v = probe_in[id.x];
+    probe_out[id.x] = model_point(v.x, bitcast(v.yz), 0.0).label;
+}`;
+
+const root = mkdtempSync(join(tmpdir(), 'label-probe-'));
+writeFileSync(join(root, 'probe.html'), 'probe');
+copyFileSync(join(dir, 'blocks.bin'), join(root, 'blocks.bin'));
+const { origin, close } = await serve(root);
+const browser = await launch(true);
+const page = await browser.newPage();
+await page.goto(`${origin}/probe.html`);
+const result = await page.evaluate(async ({ code, points }) => {
+    const device = await (await navigator.gpu.requestAdapter()).requestDevice();
+    const module = device.createShaderModule({ code });
+    const errors = (await module.getCompilationInfo()).messages.filter(m => m.type === 'error');
+    if (errors.length) return { errors: errors.map(m => `${m.lineNum}: ${m.message}`) };
+    const all = new Uint32Array(await (await fetch('/blocks.bin')).arrayBuffer());
+    const rows = Math.ceil(all.length / 4096), padded = new Uint32Array(rows * 4096);
+    padded.set(all);
+    const texture = device.createTexture({ size: [4096, rows], format: 'r32uint', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });
+    device.queue.writeTexture({ texture }, padded, { bytesPerRow: 4096 * 4, rowsPerImage: rows }, [4096, rows]);
+    const input = new Int32Array(points.length * 4);
+    points.forEach(([block, x, y], k) => input.set([block, x, y, 0], 4 * k));
+    const inBuffer = device.createBuffer({ size: input.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
+    device.queue.writeBuffer(inBuffer, 0, input);
+    const size = points.length * 4;
+    const output = device.createBuffer({ size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });
+    const read = device.createBuffer({ size, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
+    const pipeline = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'probe' } });
+    const group = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [
+        { binding: 8, resource: texture.createView() }, { binding: 1, resource: { buffer: inBuffer } }, { binding: 3, resource: { buffer: output } },
+    ] });
+    const encoder = device.createCommandEncoder(), pass = encoder.beginComputePass();
+    pass.setPipeline(pipeline);
+    pass.setBindGroup(0, group);
+    pass.dispatchWorkgroups(Math.ceil(points.length / 64));
+    pass.end();
+    encoder.copyBufferToBuffer(output, 0, read, 0, size);
+    device.queue.submit([encoder.finish()]);
+    await read.mapAsync(GPUMapMode.READ);
+    return { out: Array.from(new Uint32Array(read.getMappedRange().slice(0))) };
+}, { code, points });
+await browser.close();
+close();
+if (result.errors) {
+    console.log(result.errors.slice(0, 10).join('\n'));
+    process.exit(1);
+}
+const differ = points.flatMap(([block, x, y, label], k) => (result.out[k] === label ? [] : [{ block, q: [x, y], rust: label, gpu: result.out[k] }]));
+for (const row of differ.slice(0, 20)) console.log(JSON.stringify(row));
+console.log(`${points.length} points: ${differ.length} labels differ`);
+process.exit(differ.length ? 1 : 0);
diff --git a/builder/web/tests/browser/trailview/model-probe.mjs b/builder/web/tests/browser/trailview/model-probe.mjs
new file mode 100644
index 0000000000..65774e9912
--- /dev/null
+++ b/builder/web/tests/browser/trailview/model-probe.mjs
@@ -0,0 +1,111 @@
+// The viewer's heights.wgsl against the crate's height_at at the points that the debug tool's
+// `heights --gpu-check --out DIR` writes: the GPU's height and kind at each point, with Rust's label
+// and terrain, and the largest difference. One GPU user at a time:
+//   flock /tmp/trailview-gpu.lock node tests/browser/trailview/model-probe.mjs DIR
+import { copyFileSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { include } from '../../../src/lib/trailview/gpu/include.ts';
+import { launch, serve } from './harness.js';
+
+/** Over this many metres a height differs. */
+const TOLERANCE_M = 0.002;
+const ROOT = new URL('../../../src/lib/trailview/', import.meta.url).pathname;
+
+const [dir] = process.argv.slice(2);
+if (!dir) throw new Error('model-probe.mjs DIR (of debug heights --gpu-check)');
+const points = JSON.parse(readFileSync(join(dir, 'points.json'), 'utf8'));
+const code = include('terrain/heights.wgsl', path => readFileSync(ROOT + path, 'utf8')) + `
+@group(0) @binding(1) var probe_in: array;
+@group(0) @binding(2) var probe_terrain: array;
+@group(0) @binding(3) var probe_out: array;
+@compute @workgroup_size(64) fn probe(@builtin(global_invocation_id) id: vec3u) {
+    if (id.x >= arrayLength(&probe_out)) { return; }
+    let v = probe_in[id.x];
+    probe_out[id.x] = height_at(v.x, bitcast(v.yz), v.w, probe_terrain[id.x], 0u);
+}`;
+
+const root = mkdtempSync(join(tmpdir(), 'model-probe-'));
+writeFileSync(join(root, 'probe.html'), 'probe');
+copyFileSync(join(dir, 'blocks.bin'), join(root, 'blocks.bin'));
+const { origin, close } = await serve(root);
+const browser = await launch(true);
+const page = await browser.newPage();
+await page.goto(`${origin}/probe.html`);
+const result = await page.evaluate(async ({ code, points }) => {
+    const adapter = await navigator.gpu.requestAdapter();
+    const device = await adapter.requestDevice();
+    device.pushErrorScope('validation');
+    const module = device.createShaderModule({ code });
+    const errors = (await module.getCompilationInfo()).messages.filter(m => m.type === 'error');
+    if (errors.length) return { errors: errors.map(m => `${m.lineNum}: ${m.message}`) };
+    const all = new Uint32Array(await (await fetch('/blocks.bin')).arrayBuffer());
+    const rows = Math.ceil(all.length / 4096);
+    const padded = new Uint32Array(rows * 4096);
+    padded.set(all);
+    const texture = device.createTexture({ size: [4096, rows], format: 'r32uint', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST });
+    device.queue.writeTexture({ texture }, padded, { bytesPerRow: 4096 * 4, rowsPerImage: rows }, [4096, rows]);
+    const input = new Uint32Array(points.length * 4);
+    const floats = new Float32Array(input.buffer);
+    const terrain = new Float32Array(points.length);
+    points.forEach(([block, x, y, label, t], k) => {
+        input[4 * k] = block;
+        floats[4 * k + 1] = x;
+        floats[4 * k + 2] = y;
+        input[4 * k + 3] = label;
+        terrain[k] = t;
+    });
+    const buffer = data => {
+        const b = device.createBuffer({ size: data.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST });
+        device.queue.writeBuffer(b, 0, data);
+        return b;
+    };
+    const size = points.length * 8;
+    const output = device.createBuffer({ size, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });
+    const read = device.createBuffer({ size, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST });
+    const pipeline = await device.createComputePipelineAsync({ layout: 'auto', compute: { module, entryPoint: 'probe' } });
+    const group = device.createBindGroup({
+        layout: pipeline.getBindGroupLayout(0),
+        entries: [
+            { binding: 8, resource: texture.createView() },
+            { binding: 1, resource: { buffer: buffer(input) } },
+            { binding: 2, resource: { buffer: buffer(terrain) } },
+            { binding: 3, resource: { buffer: output } },
+        ],
+    });
+    const encoder = device.createCommandEncoder();
+    const pass = encoder.beginComputePass();
+    pass.setPipeline(pipeline);
+    pass.setBindGroup(0, group);
+    pass.dispatchWorkgroups(Math.ceil(points.length / 64));
+    pass.end();
+    encoder.copyBufferToBuffer(output, 0, read, 0, size);
+    device.queue.submit([encoder.finish()]);
+    await read.mapAsync(GPUMapMode.READ);
+    const out = new Float32Array(read.getMappedRange().slice(0));
+    const error = await device.popErrorScope();
+    return { error: error?.message, out: Array.from(out) };
+}, { code, points });
+await browser.close();
+close();
+if (result.errors) {
+    console.log(result.errors.slice(0, 10).join('\n'));
+    process.exit(1);
+}
+if (result.error) throw new Error(result.error);
+const places = {};
+const rows = points.map(([block, x, y, label, t, h, kind, name], k) => {
+    const gh = result.out[2 * k], gk = result.out[2 * k + 1];
+    const p = (places[name] ??= { points: 0, max_mm: 0, kinds_differ: 0 });
+    const d = Math.abs(gh - h);
+    p.points++;
+    p.max_mm = Math.max(p.max_mm, d * 1000);
+    p.kinds_differ += gk !== kind;
+    return { block, q: [x, y], label, t, rust: [h, kind], gpu: [gh, gk] };
+});
+writeFileSync(join(dir, 'probe.json'), JSON.stringify(rows));
+const max = Math.max(...Object.values(places).map(p => p.max_mm));
+const differ = Object.values(places).reduce((n, p) => n + p.kinds_differ, 0);
+for (const [name, p] of Object.entries(places)) console.log(`${name}: ${p.points} points, max ${p.max_mm.toFixed(3)} mm, kinds differ ${p.kinds_differ}`);
+console.log(`${rows.length} points: max ${max.toFixed(3)} mm, kinds differ ${differ}`);
+process.exit(max <= TOLERANCE_M * 1000 && differ === 0 ? 0 : 1);
diff --git a/builder/web/tests/browser/trailview/road-views-far.json b/builder/web/tests/browser/trailview/road-views-far.json
new file mode 100644
index 0000000000..d022f095f4
--- /dev/null
+++ b/builder/web/tests/browser/trailview/road-views-far.json
@@ -0,0 +1,20 @@
+[
+  { "name": "junction0-far-300", "view": "?lat=46.822298&lon=8.395658&heading=315.5&pitch=-12&eye=64&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "junction0-far-700", "view": "?lat=46.819735&lon=8.399338&heading=315.5&pitch=-12&eye=149&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "junction0-far-1400", "view": "?lat=46.815250&lon=8.405780&heading=315.5&pitch=-12&eye=298&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "j-tt-a-far-300", "view": "?lat=46.814945&lon=8.378698&heading=72.2&pitch=-12&eye=64&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "j-tt-a-far-700", "view": "?lat=46.813847&lon=8.373698&heading=72.2&pitch=-12&eye=149&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "j-tt-a-far-1400", "view": "?lat=46.811924&lon=8.364950&heading=72.2&pitch=-12&eye=298&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "t-tertiary-far-300", "view": "?lat=46.822406&lon=8.409129&heading=201&pitch=-12&eye=64&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "t-tertiary-far-700", "view": "?lat=46.825761&lon=8.411011&heading=201&pitch=-12&eye=149&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "t-tertiary-far-1400", "view": "?lat=46.831631&lon=8.414304&heading=201&pitch=-12&eye=298&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "x-tertiary-far-300", "view": "?lat=46.818757&lon=8.412226&heading=290&pitch=-12&eye=64&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "x-tertiary-far-700", "view": "?lat=46.817528&lon=8.417160&heading=290&pitch=-12&eye=149&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "x-tertiary-far-1400", "view": "?lat=46.815378&lon=8.425795&heading=290&pitch=-12&eye=298&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "i07-hairpin-far-300", "view": "?lat=46.819116&lon=8.404286&heading=10&pitch=-12&eye=64&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "i07-hairpin-far-700", "view": "?lat=46.815577&lon=8.403374&heading=10&pitch=-12&eye=149&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "i07-hairpin-far-1400", "view": "?lat=46.809385&lon=8.401778&heading=10&pitch=-12&eye=298&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "b45-bridge-junction-far-300", "view": "?lat=46.820826&lon=8.413832&heading=45&pitch=-12&eye=64&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "b45-bridge-junction-far-700", "view": "?lat=46.818286&lon=8.410119&heading=45&pitch=-12&eye=149&date=2026-08-15&time=10:30&weather=sunny" },
+  { "name": "b45-bridge-junction-far-1400", "view": "?lat=46.813839&lon=8.403621&heading=45&pitch=-12&eye=298&date=2026-08-15&time=10:30&weather=sunny" }
+]
diff --git a/builder/web/tests/browser/trailview/road-views-top.json b/builder/web/tests/browser/trailview/road-views-top.json
new file mode 100644
index 0000000000..5bea6d3793
--- /dev/null
+++ b/builder/web/tests/browser/trailview/road-views-top.json
@@ -0,0 +1,52 @@
+[
+    { "name": "v01-stairs-top", "view": "?lat=46.824710&lon=8.412039&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v02-stream-path-shrubs-top", "view": "?lat=46.824960&lon=8.411504&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v03-good-path-top", "view": "?lat=46.825128&lon=8.409916&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v04-wall-road-junction-top", "view": "?lat=46.827343&lon=8.404113&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v05-slope-artifact-top", "view": "?lat=46.827675&lon=8.403631&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v06-road-path-broken-top", "view": "?lat=46.822091&lon=8.379351&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v07-good-junction-top", "view": "?lat=46.821747&lon=8.376233&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v08-rough-connection-top", "view": "?lat=46.813795&lon=8.381561&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v09-sidewalk-patches-top", "view": "?lat=46.810470&lon=8.378928&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v10-signpost-bench-top", "view": "?lat=46.809459&lon=8.377482&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v11-two-bad-junctions-top", "view": "?lat=46.810632&lon=8.373293&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v12-good-town-junctions-top", "view": "?lat=46.818323&lon=8.398182&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v13-culverts-top", "view": "?lat=46.819326&lon=8.406537&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v14-paths-not-joined-top", "view": "?lat=46.820878&lon=8.409111&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v15-stuff-on-road-top", "view": "?lat=46.821258&lon=8.406819&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v16-road-rail-top", "view": "?lat=46.819838&lon=8.399169&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "v17-sharp-corners-top", "view": "?lat=46.821753&lon=8.404913&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "i07-hairpin-top", "view": "?lat=46.821770&lon=8.404970&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "d-hairpin-top", "view": "?lat=46.827088&lon=8.391039&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "hp-top", "view": "?lat=46.814828&lon=8.384674&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "t-tertiary-top", "view": "?lat=46.819890&lon=8.407718&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "x-tertiary-top", "view": "?lat=46.819679&lon=8.408525&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "junction0-top", "view": "?lat=46.824220&lon=8.392897&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "j-tt-a-top", "view": "?lat=46.815769&lon=8.382447&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "b45-bridge-junction-top", "view": "?lat=46.822732&lon=8.416617&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "b315-bridge-junction-top", "view": "?lat=46.822705&lon=8.416670&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "d-bridge-top", "view": "?lat=46.818435&lon=8.397207&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "zebra-tagged-top", "view": "?lat=46.819676&lon=8.408600&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "crossing-close-top", "view": "?lat=46.821887&lon=8.402731&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "stream-culvert-main-road-top", "view": "?lat=46.819322&lon=8.406504&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "stream-culvert-track-top", "view": "?lat=46.795257&lon=8.377083&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "mouth-stream-top", "view": "?lat=46.822759&lon=8.410184&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "stream-parallel-road-top", "view": "?lat=46.818451&lon=8.409863&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "lake-shore-top", "view": "?lat=46.797151&lon=8.387200&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "rail-close-top", "view": "?lat=46.819807&lon=8.399818&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "steps-town-top", "view": "?lat=46.821875&lon=8.409691&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-own-a-top", "view": "?lat=46.823456&lon=8.408935&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-own-b-top", "view": "?lat=46.823722&lon=8.405972&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-own-c-top", "view": "?lat=46.823857&lon=8.405212&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-path-off-road-top", "view": "?lat=46.823764&lon=8.403463&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-track-off-road-top", "view": "?lat=46.823738&lon=8.387114&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-path-off-walk-top", "view": "?lat=46.822974&lon=8.396994&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-road-into-path-top", "view": "?lat=46.823835&lon=8.388108&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-walk-into-path-top", "view": "?lat=46.823834&lon=8.405159&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-road-into-track-top", "view": "?lat=46.806463&lon=8.398374&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-walk-into-track-top", "view": "?lat=46.828968&lon=8.417102&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-path-off-track-top", "view": "?lat=46.813305&lon=8.408688&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-footway-hump-top", "view": "?lat=46.822773&lon=8.421102&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-steep-ramp-top", "view": "?lat=46.823307&lon=8.417528&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" },
+    { "name": "conn-parallel-way-top", "view": "?lat=46.820463&lon=8.419475&heading=0&pitch=-89&eye=60&date=2026-08-15&time=10:30&weather=sunny" }
+]
diff --git a/builder/web/tests/browser/trailview/road-views.json b/builder/web/tests/browser/trailview/road-views.json
index 0b9430d899..8ad2b1344f 100644
--- a/builder/web/tests/browser/trailview/road-views.json
+++ b/builder/web/tests/browser/trailview/road-views.json
@@ -98,7 +98,6 @@
     { "name": "conn-parallel-way-above", "view": "?lat=46.820273&lon=8.419475&heading=0&pitch=-42&eye=20&date=2026-08-15&time=10:30&weather=sunny" },
     { "name": "conn-parallel-way-eye", "view": "?lat=46.820291&lon=8.419475&heading=0&pitch=-12&eye=1.6&date=2026-08-15&time=10:30&weather=sunny" },
     { "name": "i07-hairpin-eye", "view": "?lat=46.82175&lon=8.40488&heading=10&pitch=-5&eye=1.6&date=2026-08-15&time=10:30&weather=sunny" },
-    { "name": "i07-hairpin-top", "view": "?lat=46.82177&lon=8.40497&heading=0&pitch=-89&alt=1035&date=2026-08-15&time=10:30&weather=sunny" },
     { "name": "worst3", "view": "?lat=46.82455&lon=8.40435&heading=0&pitch=-45&alt=1140&date=2026-08-15&time=10:30&weather=sunny" },
     { "name": "flat-bend-top", "view": "?lat=46.824357&lon=8.393655&heading=0&pitch=-89&eye=18&date=2026-08-15&time=10:30&weather=sunny" },
     { "name": "v01-stairs", "view": "?lat=46.824484&lon=8.412129&heading=344.7&pitch=-16.0&alt=1166.1&date=2026-08-15&time=10:30&weather=sunny" },
diff --git a/builder/web/tests/browser/trailview/shoot.mjs b/builder/web/tests/browser/trailview/shoot.mjs
index fbc99e758e..63717b440b 100644
--- a/builder/web/tests/browser/trailview/shoot.mjs
+++ b/builder/web/tests/browser/trailview/shoot.mjs
@@ -1,7 +1,7 @@
 // Draws a list of views of the built TrailView page in headless Chromium and writes one PNG per view.
 //
 //   npm run pretest:trailview --prefix builder/web/tests/browser     # build against the fixture
-//   node builder/web/tests/browser/trailview/shoot.mjs [--views FILE] [--out DIR] [--width PX] [--height PX] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--hud] [--gpu] [--audit] [--pages N]
+//   node builder/web/tests/browser/trailview/shoot.mjs [--views FILE] [--out DIR] [--width PX] [--height PX] [--tiles FILE] [--ground DIR] [--colour V] [--features DIR] [--hud] [--gpu] [--audit] [--pages N] [--query Q]
 //
 // --views is a JSON list of {name, view}, where view is a query string (default: views.json).
 // --width and --height are the size of the page (default 1280 × 800).
@@ -12,7 +12,10 @@
 // draws on the CPU. Prints one JSON line per view: the file, the adapter, the nodes drawn, the
 // requests, the red pixels of a `debug=cracks` view and page errors.
 // --pages is the number of views that draw at once, each on its own page (default 3 with --gpu, else
-// 1). The JSON lines come in the order in which the views finish.
+// 1). The JSON lines come in the order in which the views finish. --query Q appends `&Q` to each view,
+// such as `ground=plan&plan=faces`; with the ground plan, a line holds its cells, failures, ready time and heap,
+// the records, and the meshes: the cells that draw, their triangles and slots in view, their bytes and the
+// milliseconds to the first frame in which every cell of level 18 draws its mesh.
 
 import { mkdirSync, readFileSync } from 'node:fs';
 import { join } from 'node:path';
@@ -33,6 +36,7 @@ const { values } = parseArgs({
         audit: { type: 'boolean' },
         gpu: { type: 'boolean' },
         pages: { type: 'string' },
+        query: { type: 'string' },
     },
 });
 /** The longest wait for the page and for an idle view. */
@@ -52,7 +56,7 @@ async function shoot({ name, view }) {
     const page = await browser.newPage({ viewport: { width: Number(values.width), height: Number(values.height) }, deviceScaleFactor: 1 });
     const errors = errorsOf(page);
     await routeFixture(page, values.tiles, values.ground, values.colour, values.features);
-    await page.goto(`${origin}/trailview.html${view}`);
+    await page.goto(`${origin}/trailview.html${view}${values.query ? `&${values.query}` : ''}`);
     await page.waitForFunction(() => window.trailView, null, { timeout: TIMEOUT_MS });
     await idle(page);
     await page.evaluate(() => window.trailView.showMarker(null));
@@ -64,7 +68,10 @@ async function shoot({ name, view }) {
     const stats = await page.evaluate(() => window.trailView.stats());
     const red = view.includes('debug=cracks') ? { redPixels: await redPixels(page) } : {};
     const audit = values.audit ? { audit: await page.evaluate(() => window.trailView.audit()) } : {};
-    console.log(JSON.stringify({ name, file, adapter: stats.adapter, drawn: stats.drawn, requests: stats.requests, ...red, ...audit, errors }));
+    const plan = stats.plan ? { plan: { cells: stats.plan.cells, failed: stats.plan.failed, ready: stats.plan.ready, heap: stats.plan.heap, debugVertices: stats.plan.debugVertices, build: stats.plan.build, error: stats.plan.error } } : {};
+    const records = stats.terrain?.records ? { records: stats.terrain.records } : {};
+    const pieces = stats.terrain?.pieces ? { pieces: stats.terrain.pieces } : {};
+    console.log(JSON.stringify({ name, file, adapter: stats.adapter, drawn: stats.drawn, requests: stats.requests, ...red, ...audit, ...plan, ...records, ...pieces, errors }));
     await page.close();
 }
 try {
diff --git a/builder/web/tests/browser/trailview/smoke.test.js b/builder/web/tests/browser/trailview/smoke.test.js
index 9d241bbd87..98c07113af 100644
--- a/builder/web/tests/browser/trailview/smoke.test.js
+++ b/builder/web/tests/browser/trailview/smoke.test.js
@@ -24,10 +24,7 @@ async function debug(page, view) {
     }, view);
 }
 
-test('the page draws the fixture with no WebGPU error, and the probe gives the height that an instance shader evaluates, to 1 mm', async ({ page }) => {
-    // SwiftShader on the Linux runners spends its frames shading pixels: a quarter of them draws the same nodes.
-    test.slow();
-    await page.setViewportSize({ width: 480, height: 300 });
+test('the page draws the fixture with no WebGPU error, and the probe gives the height that an instance shader evaluates, to 1 mm', { tag: '@gpu' }, async ({ page }) => {
     const errors = errorsOf(page);
     await open(page, DOWN);
     const { drawn, failed, terrain } = await page.evaluate(() => window.trailView.stats());
diff --git a/builder/web/vite.config.ts b/builder/web/vite.config.ts
index fd010b87c9..9c31f2c3b7 100644
--- a/builder/web/vite.config.ts
+++ b/builder/web/vite.config.ts
@@ -1,6 +1,8 @@
 import { availableParallelism, loadavg } from "node:os";
 import { svelte } from "@sveltejs/vite-plugin-svelte";
 import { defineConfig, loadEnv } from "vite";
+import { bundleVersions } from "./vite/bundle-version";
+import { stampVersion } from "./vite/stamp-bundle";
 import { thirdPartyLicenses } from "./vite/third-party-licenses";
 import { plannerConfig } from "./src/lib/planner/config";
 import { testConfig } from "./test-support/planner/config";
@@ -57,8 +59,8 @@ export default defineConfig(({ mode }) => {
         // "/" (local FastAPI) or under a sub-path (a future single-server deployment
         // serving landing + docs + builder behind one reverse proxy).
         base: "./",
-            // The licence notices ride along with the bundle, which is a distribution.
-        plugins: [svelte(), thirdPartyLicenses()],
+        // The licence notices ride along with the bundle, which is a distribution.
+        plugins: [svelte(), thirdPartyLicenses(), stampVersion(), bundleVersions()],
         // Always a string, so a build without it drops the pretend device of `planner.ts` with its wasm.
         define: { "import.meta.env.VITE_FAKE_DEVICE": JSON.stringify(process.env.VITE_FAKE_DEVICE ?? "") },
         resolve: {
@@ -85,6 +87,8 @@ export default defineConfig(({ mode }) => {
                 // in-browser assembly, not the site: the worker only spawns from the
                 // download step.
             format: "es",
+            // Workers bundle their imports with plugins of their own.
+            plugins: () => [stampVersion()],
         },
         server: {
             // The product skin editor imports the bakery's canonical Teningen
diff --git a/builder/web/vite/bundle-version.ts b/builder/web/vite/bundle-version.ts
new file mode 100644
index 0000000000..6513b673cd
--- /dev/null
+++ b/builder/web/vite/bundle-version.ts
@@ -0,0 +1,62 @@
+// `virtual:NAME-version`: the version of the JavaScript that a worker runs to make what the device cache keeps, the
+// start of the SHA-256 of its entries bundled with every import inlined. `plan`: the plan worker's input preparation,
+// with the page decode that it imports, and the input walk; the cells also key by the hash of the bridge's wasm, which
+// the bundle only names by URL. `tree`: the tree models and their entry layout. `house`: the house records. The stamp
+// version stays in stamp-bundle.ts: the data pipeline digests that file as the stamp bake's own (`stamp_sources`).
+
+import { createHash } from "node:crypto";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { build, type Plugin } from "vite";
+
+const ROOT = fileURLToPath(new URL("..", import.meta.url));
+const ENTRIES: Record = {
+    plan: ["src/lib/trailview/plan/plan-worker.ts", "src/lib/trailview/plan/inputs.ts"],
+    tree: ["src/lib/trailview/vegetation/model-worker.ts", "src/lib/trailview/vegetation/model-entry.ts"],
+    house: ["src/lib/trailview/structures/house-worker.ts"],
+};
+
+/** The start of the SHA-256 of the entries bundled with every import inlined, and the files of the modules in them. */
+async function bundle(entries: string[]): Promise<{ version: string; modules: string[] }> {
+    const hash = createHash("sha256"), modules: string[] = [];
+    for (const entry of entries) {
+        const out = await build({
+            configFile: false, root: ROOT, logLevel: "silent", ssr: { noExternal: true },
+            build: { ssr: entry, write: false, minify: false, rollupOptions: { output: { inlineDynamicImports: true } } },
+        });
+        const [chunk] = (Array.isArray(out) ? out[0] : out as { output: { code: string; moduleIds: string[] }[] }).output;
+        hash.update(chunk.code);
+        modules.push(...chunk.moduleIds);
+    }
+    return { version: hash.digest("hex").slice(0, 16), modules };
+}
+
+/** The versions of ENTRIES. The dev server reloads the page when a module of a bundle changes. */
+export function bundleVersions(): Plugin {
+    const bundles = new Map>();
+    const nameOf = (source: string) => {
+        const name = /^\0?virtual:(\w+)-version$/.exec(source)?.[1];
+        return name && Object.hasOwn(ENTRIES, name) ? name : undefined;
+    };
+    return {
+        name: "bundle-versions",
+        resolveId: source => (nameOf(source) && !source.startsWith("\0") ? `\0${source}` : undefined),
+        async load(id) {
+            const name = id.startsWith("\0") ? nameOf(id) : undefined;
+            if (!name) return undefined;
+            if (!bundles.has(name)) bundles.set(name, bundle(ENTRIES[name]));
+            return `export default ${JSON.stringify((await bundles.get(name)!).version)};`;
+        },
+        configureServer(server) {
+            server.watcher.on("change", async file => {
+                for (const [name, made] of bundles) {
+                    const module = server.moduleGraph.getModuleById(`\0virtual:${name}-version`);
+                    if (!module || !(await made).modules.includes(path.resolve(file))) continue;
+                    bundles.delete(name);
+                    server.moduleGraph.invalidateModule(module);
+                    server.ws.send({ type: "full-reload" });
+                }
+            });
+        },
+    };
+}
diff --git a/builder/web/vite/stamp-bundle.ts b/builder/web/vite/stamp-bundle.ts
new file mode 100644
index 0000000000..52d54cf0d9
--- /dev/null
+++ b/builder/web/vite/stamp-bundle.ts
@@ -0,0 +1,52 @@
+// The stamp bake as one ES module for Node, and its version: the bake of `planner/trailview-stamps` runs the
+// module, and the viewer reads a baked node only when the layer's `stamp_version` is the version of its build.
+//
+// This module imports nothing local: scripts/trailview-stamps.mjs loads it in plain Node.
+
+import { createHash } from "node:crypto";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { build, type Plugin } from "vite";
+
+const ROOT = fileURLToPath(new URL("..", import.meta.url));
+/** The bake entry: the stamp worker, the node bytes and the baked nodes of a feature tile. */
+const ENTRY = "src/lib/trailview/terrain/stamp-bake.ts";
+
+/**
+ * The module of the bake with every import inlined, its version (the start of the SHA-256 of the module, so of
+ * the stamp code and the tables that it reads) and the files of the modules in it.
+ */
+export async function stampBundle(): Promise<{ code: string; version: string; modules: string[] }> {
+    const out = await build({
+        configFile: false, root: ROOT, logLevel: "silent", ssr: { noExternal: true },
+        build: { ssr: ENTRY, write: false, minify: false, rollupOptions: { output: { inlineDynamicImports: true } } },
+    });
+    const [chunk] = (Array.isArray(out) ? out[0] : out as { output: { code: string; moduleIds: string[] }[] }).output;
+    return { code: chunk.code, version: createHash("sha256").update(chunk.code).digest("hex").slice(0, 16), modules: chunk.moduleIds };
+}
+
+/** The bundle of the build: the page and each worker read one version. The dev server drops it when a module of the bake changes. */
+let bundle: ReturnType | undefined;
+
+/** `virtual:stamp-version`: the version of stampBundle. The dev server reloads the page when a module of the bake changes. */
+export function stampVersion(): Plugin {
+    const id = "virtual:stamp-version", resolved = `\0${id}`;
+    return {
+        name: "stamp-version",
+        resolveId: source => (source === id ? resolved : undefined),
+        async load(source) {
+            if (source !== resolved) return undefined;
+            bundle ??= stampBundle();
+            return `export default ${JSON.stringify((await bundle).version)};`;
+        },
+        configureServer(server) {
+            server.watcher.on("change", async file => {
+                const module = server.moduleGraph.getModuleById(resolved);
+                if (!module || !bundle || !(await bundle).modules.includes(path.resolve(file))) return;
+                bundle = undefined;
+                server.moduleGraph.invalidateModule(module);
+                server.ws.send({ type: "full-reload" });
+            });
+        },
+    };
+}
diff --git a/builder/web/vite/stamp-version.d.ts b/builder/web/vite/stamp-version.d.ts
new file mode 100644
index 0000000000..2ea2e0acee
--- /dev/null
+++ b/builder/web/vite/stamp-version.d.ts
@@ -0,0 +1,5 @@
+// The version of the stamp bake, from stampVersion of stamp-bundle.ts.
+declare module "virtual:stamp-version" {
+    const version: string;
+    export default version;
+}
diff --git a/builder/web/vite/versions.d.ts b/builder/web/vite/versions.d.ts
new file mode 100644
index 0000000000..763595411d
--- /dev/null
+++ b/builder/web/vite/versions.d.ts
@@ -0,0 +1,13 @@
+// The versions of the code that the device cache keys by, from bundleVersions of bundle-version.ts.
+declare module "virtual:plan-version" {
+    const version: string;
+    export default version;
+}
+declare module "virtual:tree-version" {
+    const version: string;
+    export default version;
+}
+declare module "virtual:house-version" {
+    const version: string;
+    export default version;
+}
diff --git a/data/trailview/README.md b/data/trailview/README.md
index fbc87dc10d..117cae6b7e 100644
--- a/data/trailview/README.md
+++ b/data/trailview/README.md
@@ -12,8 +12,9 @@ The rules that the TrailView ground layers index and that the engine reads. The
 | `countries.json` | Natural Earth countries and first-level subdivisions: the places of a value by place |
 | `kinds.json` | The feature kinds of `planner/trailview-features`: [specs/trailview-features.md](../../specs/trailview-features.md) |
 | `ground.json` | The ground sources of the material and the lithology, in the order they apply: [specs/trailview-tiles.md](../../specs/trailview-tiles.md#ground-sources) |
-| `roads.json` | The rules per class of road and track, from the most important down: the grade and smoothing of the road solver, the alignment and the sidewalks of the bake, the stamp profile of the engine |
-| `waterways.json` | The rules per `waterway` value of the river and stream kinds: the width without a `width` tag, the longest culvert, the cover of a road over a culvert and the most that it lifts the road, and the stamp profile of the engine |
+| `roads.json` | The rules per class of road and track, from the most important down: the grade and smoothing of the road solver, the alignment and the sidewalks of the bake, the stamp profile of the engine, the cross-section of the ground plan (`half_m`, `shoulder_m`, `kerb_m`, `kerb_top_m`). The feature step's options: `half_m`, `shoulder_m` and the fields of the road solver |
+| `finishes.json` | The caps of the half-width and the shoulder per finish of a way's top, in the order of the mask's surface code; null keeps the class's value. All of it is an option of the feature step |
+| `waterways.json` | The rules per `waterway` value of the river and stream kinds: the width without a `width` tag, the longest culvert, the cover of a road over a culvert and the most that it lifts the road, the widest water that an untagged way crosses on a culvert (`culvert_width_m`), the bank top that the level keeps under (`freeboard_m`, `bank_m`), the curve that the ground plan draws through a waterway's vertices (`curve_turn_max_deg`, `curve_off_max_m`), the ground plan's bed depth and bank (`depth_m`, `bank_slope`, `bank_reach_m`, `bank_steepest`), the depth under the terrain past which the ground plan draws no water (`underground_m`), and the stamp profile of the engine. All but the bed depth, the bank, `underground_m` and the stamp profile are options of the feature step |
 
 ## Test
 
diff --git a/data/trailview/finishes.json b/data/trailview/finishes.json
new file mode 100644
index 0000000000..898799606c
--- /dev/null
+++ b/data/trailview/finishes.json
@@ -0,0 +1,14 @@
+{
+  "main": {"half_m": null, "shoulder_m": null},
+  "road": {"half_m": 3, "shoulder_m": 0.4},
+  "gravel": {"half_m": 1.75, "shoulder_m": 0.3},
+  "dirt": {"half_m": 1.5, "shoulder_m": 0.25},
+  "grass": {"half_m": 1.25, "shoulder_m": 0.2},
+  "path": {"half_m": 0.6, "shoulder_m": 0},
+  "oneway": {"half_m": null, "shoulder_m": null},
+  "paving": {"half_m": 1.25, "shoulder_m": 0},
+  "rail": {"half_m": 1.9, "shoulder_m": 0.35},
+  "narrow": {"half_m": 1.5, "shoulder_m": 0.35},
+  "rack": {"half_m": 1.9, "shoulder_m": 0.35},
+  "narrow-rack": {"half_m": 1.5, "shoulder_m": 0.35}
+}
diff --git a/data/trailview/kinds.json b/data/trailview/kinds.json
index 9b2c516a9d..6a07a7aed0 100644
--- a/data/trailview/kinds.json
+++ b/data/trailview/kinds.json
@@ -6,7 +6,7 @@
                            "secondary", "secondary_link", "tertiary", "tertiary_link", "unclassified",
                            "residential", "living_street", "service", "road", "track", "path", "footway",
                            "cycleway", "bridleway", "steps", "pedestrian", "via_ferrata"],
-               "tunnel": ["yes", "building_passage"]},
+               "tunnel": ["yes"]},
               {"railway": ["rail", "narrow_gauge", "light_rail", "funicular"], "tunnel": ["yes"]}],
     "keep": ["highway", "tunnel", "width", "lanes", "layer", "railway", "gauge", "rack", "electrified"],
     "height": "profile"
@@ -29,7 +29,7 @@
     "match": [{"highway": ["motorway", "motorway_link", "trunk", "trunk_link", "primary", "primary_link",
                            "secondary", "secondary_link"]}],
     "keep": ["highway", "surface", "width", "lanes", "oneway", "junction", "bridge", "bridge:structure", "layer", "ford",
-             "sidewalk", "sidewalk:both", "sidewalk:left", "sidewalk:right"],
+             "lit", "sidewalk", "sidewalk:both", "sidewalk:left", "sidewalk:right"],
     "height": "profile",
     "min_zoom": 8
   },
@@ -38,8 +38,8 @@
     "geometry": "line",
     "match": [{"highway": ["tertiary", "tertiary_link", "unclassified", "residential", "living_street", "service",
                            "road", "track"]}],
-    "keep": ["highway", "surface", "tracktype", "width", "lanes", "oneway", "junction", "bridge", "bridge:structure",
-             "layer", "ford", "sidewalk", "sidewalk:both", "sidewalk:left", "sidewalk:right"],
+    "keep": ["highway", "service", "surface", "tracktype", "width", "lanes", "oneway", "junction", "bridge",
+             "bridge:structure", "layer", "ford", "lit", "sidewalk", "sidewalk:both", "sidewalk:left", "sidewalk:right"],
     "height": "profile"
   },
   {
@@ -47,7 +47,7 @@
     "geometry": "line",
     "match": [{"highway": ["path", "footway", "cycleway", "bridleway", "steps", "pedestrian", "via_ferrata"]}],
     "keep": ["highway", "footway", "crossing", "crossing:markings", "surface", "width", "bridge", "bridge:structure",
-             "layer", "ford", "sac_scale"],
+             "layer", "ford", "lit", "sac_scale"],
     "height": "profile"
   },
   {
@@ -75,7 +75,7 @@
     "kind": "river",
     "geometry": "line",
     "match": [{"waterway": ["river", "canal"]}],
-    "keep": ["waterway", "width", "tunnel", "intermittent", "seasonal"],
+    "keep": ["waterway", "width", "tunnel", "bridge", "intermittent", "seasonal"],
     "height": "profile",
     "min_zoom": 8
   },
@@ -83,7 +83,7 @@
     "kind": "stream",
     "geometry": "line",
     "match": [{"waterway": ["stream"]}],
-    "keep": ["waterway", "width", "tunnel", "intermittent", "seasonal"],
+    "keep": ["waterway", "width", "tunnel", "bridge", "intermittent", "seasonal"],
     "height": "profile"
   },
   {
@@ -237,7 +237,14 @@
     "kind": "crossing",
     "geometry": "point",
     "match": [{"highway": ["crossing"]}],
-    "keep": ["crossing", "crossing:markings"],
+    "keep": ["crossing", "crossing:markings", "railway", "crossing:barrier", "crossing:light", "crossing:saltire"],
+    "height": "surface"
+  },
+  {
+    "kind": "level-crossing",
+    "geometry": "point",
+    "match": [{"railway": ["level_crossing", "crossing"]}],
+    "keep": ["railway", "crossing:barrier", "crossing:light", "crossing:saltire"],
     "height": "surface"
   },
   {
@@ -295,5 +302,12 @@
     "match": [{"amenity": ["bicycle_repair_station"]}],
     "keep": [],
     "height": "surface"
+  },
+  {
+    "kind": "street-lamp",
+    "geometry": "point",
+    "match": [{"highway": ["street_lamp"]}],
+    "keep": [],
+    "height": "surface"
   }
 ]
diff --git a/data/trailview/plan.json b/data/trailview/plan.json
new file mode 100644
index 0000000000..c7754adcd3
--- /dev/null
+++ b/data/trailview/plan.json
@@ -0,0 +1,35 @@
+{
+  "extent_m": 20,
+  "seam_m": 0.5,
+  "taper_rate": 0.15,
+  "platform_half_m": 1.5,
+  "platform_reach_m": 0,
+  "tread_finishes": ["gravel", "dirt", "grass", "path"],
+  "structures": {"cover_m": 1.0, "lift_max_m": 1.0, "open_max_m": 30, "deck_min_m": 2.0, "edge_band_m": 0.5, "door_min_m": 1.0, "railing_width_m": 3.5, "post_spacing_m": 2.0, "pier_depth_m": 3.0},
+  "heights": {
+    "feather_min_m": 1.0, "blend_steep": 1.5, "leg_reach_m": 0.5,
+    "health_margin_m": 0.25, "health_width_m": 1.0, "frame_tilt_deg": 30,
+    "round_m": 0.5, "fade_share": 0.3, "fade_gap_m": 1.0,
+    "toe_per_m": 1.0, "toe_max_m": 5.0, "toe_span_m": 6.0, "toe_gap_min": 0.1,
+    "via_fade_m": 1.5, "band_fade_m": 1.0, "mitre_band_m": 2.0, "budget_round_m": 2.0, "wall_max_m": 4.5, "face_max": 2.5, "legs": "ramp", "step_m": 0.001,
+    "region_fade_m": 1.5, "ceiling_gap_m": 0.5, "ceiling_release_m": 8
+  },
+  "ranks": ["carriageway", "platform", "rail_bed", "shoulder_paved", "shoulder", "water_line", "verge", "zone", "bank", "slope", "terrain"],
+  "pairs": {
+    "road/road": {"mouth": "reach", "blend": true},
+    "road/track": {"mouth": "stop", "blend": true},
+    "road/path": {"mouth": "stop", "blend": true},
+    "track/road": {"mouth": "reach", "blend": true},
+    "track/track": {"mouth": "reach", "blend": true},
+    "track/path": {"mouth": "stop", "blend": true},
+    "path/path": {"mouth": "reach", "blend": true},
+    "road/steps": {"mouth": "stop", "blend": false},
+    "track/steps": {"mouth": "stop", "blend": false},
+    "path/steps": {"mouth": "stop", "blend": false},
+    "rail/rail": {"mouth": "join", "blend": false},
+    "road/rail": {"mouth": "join", "blend": false},
+    "rail/road": {"mouth": "join", "blend": false},
+    "water/water": {"mouth": "join", "blend": true},
+    "default": {"mouth": "join", "blend": false}
+  }
+}
diff --git a/data/trailview/roads.json b/data/trailview/roads.json
index 3b28055492..dcd1db84b8 100644
--- a/data/trailview/roads.json
+++ b/data/trailview/roads.json
@@ -1,30 +1,30 @@
 {
-  "rail": {"grade": 0.08, "smooth_m": 80, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "light_rail": {"grade": 0.1, "smooth_m": 50, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "narrow_gauge": {"grade": 0.12, "smooth_m": 50, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "rack": {"grade": 0.5, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "funicular": {"grade": null, "smooth_m": 20, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "motorway": {"grade": 0.06, "smooth_m": 40, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 100, "bank": 0.07, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "motorway_link": {"grade": 0.06, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 60, "bank": 0.07, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "trunk": {"grade": 0.09, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 80, "bank": 0.07, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "trunk_link": {"grade": 0.09, "smooth_m": 25, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 50, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "primary": {"grade": 0.12, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 70, "bank": 0.07, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "primary_link": {"grade": 0.12, "smooth_m": 25, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 45, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "secondary": {"grade": 0.12, "smooth_m": 25, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 60, "bank": 0.065, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "secondary_link": {"grade": 0.12, "smooth_m": 20, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 40, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "tertiary": {"grade": 0.15, "smooth_m": 20, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1, "design_kmh": 50, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "tertiary_link": {"grade": 0.15, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1, "design_kmh": 40, "bank": 0.05, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "unclassified": {"grade": 0.25, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1, "design_kmh": 40, "bank": 0.05, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 1.5, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "residential": {"grade": 0.2, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 30, "bank": 0.03, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 1.5, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "living_street": {"grade": 0.2, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 15, "bank": 0, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "service": {"grade": 0.25, "smooth_m": 12, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 25, "bank": 0.025, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "road": {"grade": 0.2, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 30, "bank": 0.03, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "track": {"grade": 0.35, "smooth_m": 10, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.85, "fill": 0.85, "tilt": 0, "plan_tol_m": 1, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "path": {"grade": null, "smooth_m": 3, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0.5, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "footway": {"grade": null, "smooth_m": 3, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "cycleway": {"grade": null, "smooth_m": 5, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "bridleway": {"grade": null, "smooth_m": 3, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0.5, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "steps": {"grade": null, "smooth_m": 2, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "pedestrian": {"grade": null, "smooth_m": 5, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1},
-  "via_ferrata": {"grade": null, "smooth_m": 2, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1}
+  "rail": {"grade": 0.08, "smooth_m": 80, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1.9, "shoulder_m": 0.35, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 6, "clearance_least_m": 4.8, "bore_m": 6.5, "bore_least_m": 4.8, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "rail", "inner_radius_m": 0, "corner_radius_m": 0, "corner_radius_walk_m": 0, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "light_rail": {"grade": 0.1, "smooth_m": 50, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1.9, "shoulder_m": 0.35, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 6, "clearance_least_m": 4.8, "bore_m": 6.5, "bore_least_m": 4.8, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "rail", "inner_radius_m": 0, "corner_radius_m": 0, "corner_radius_walk_m": 0, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "narrow_gauge": {"grade": 0.12, "smooth_m": 50, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1.9, "shoulder_m": 0.35, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 6, "clearance_least_m": 4.8, "bore_m": 6.5, "bore_least_m": 4.8, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "rail", "inner_radius_m": 0, "corner_radius_m": 0, "corner_radius_walk_m": 0, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "rack": {"grade": 0.5, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1.9, "shoulder_m": 0.35, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 6, "clearance_least_m": 4.8, "bore_m": 6.5, "bore_least_m": 4.8, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "rail", "inner_radius_m": 0, "corner_radius_m": 0, "corner_radius_walk_m": 0, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "funicular": {"grade": null, "smooth_m": 20, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1.9, "shoulder_m": 0.35, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 6, "clearance_least_m": 4.8, "bore_m": 6.5, "bore_least_m": 4.8, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "rail", "inner_radius_m": 0, "corner_radius_m": 0, "corner_radius_walk_m": 0, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "motorway": {"grade": 0.06, "smooth_m": 40, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 100, "bank": 0.07, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 6, "shoulder_m": 0.6, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 9, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "motorway_link": {"grade": 0.06, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 60, "bank": 0.07, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 4.5, "shoulder_m": 0.6, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 9, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "trunk": {"grade": 0.09, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 80, "bank": 0.07, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 5, "shoulder_m": 0.6, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 9, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "trunk_link": {"grade": 0.09, "smooth_m": 25, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 50, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 4.5, "shoulder_m": 0.6, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 9, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "primary": {"grade": 0.12, "smooth_m": 30, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 70, "bank": 0.07, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 4, "shoulder_m": 0.6, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 6, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "primary_link": {"grade": 0.12, "smooth_m": 25, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 45, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 4.5, "shoulder_m": 0.6, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 6, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "secondary": {"grade": 0.12, "smooth_m": 25, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 60, "bank": 0.065, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 3.25, "shoulder_m": 0.6, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 6, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "secondary_link": {"grade": 0.12, "smooth_m": 20, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1.5, "design_kmh": 40, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 3, "shoulder_m": 0.4, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 9, "corner_radius_walk_m": 6, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "tertiary": {"grade": 0.15, "smooth_m": 20, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1, "design_kmh": 50, "bank": 0.06, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 3, "shoulder_m": 0.4, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 7, "corner_radius_walk_m": 5, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "tertiary_link": {"grade": 0.15, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1, "design_kmh": 40, "bank": 0.05, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 2, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 3, "shoulder_m": 0.4, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 5, "corner_radius_m": 7, "corner_radius_walk_m": 5, "leg_wall": true, "shoulder_paved": true, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "unclassified": {"grade": 0.25, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 1, "design_kmh": 40, "bank": 0.05, "widen_m": 2, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 1.5, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 2.5, "shoulder_m": 0.4, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 3, "corner_radius_m": 5, "corner_radius_walk_m": 3, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "residential": {"grade": 0.2, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 30, "bank": 0.03, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 1.5, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 2.5, "shoulder_m": 0.4, "kerb_m": 0.12, "kerb_top_m": 0.16, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 3, "corner_radius_m": 4, "corner_radius_walk_m": 3, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "living_street": {"grade": 0.2, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 15, "bank": 0, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 2, "shoulder_m": 0.4, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 3, "corner_radius_m": 3, "corner_radius_walk_m": 3, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "service": {"grade": 0.25, "smooth_m": 12, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 25, "bank": 0.025, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 2, "shoulder_m": 0.4, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 3, "corner_radius_m": 3, "corner_radius_walk_m": 3, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "road": {"grade": 0.2, "smooth_m": 15, "tol": 0.02, "reach": 10, "least": 5, "cut": 0.6667, "fill": 0.6667, "tilt": 0, "plan_tol_m": 0.5, "design_kmh": 30, "bank": 0.03, "widen_m": 1.5, "keep_m": 0.3, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 3, "shoulder_m": 0.4, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "road", "inner_radius_m": 3, "corner_radius_m": 4, "corner_radius_walk_m": 4, "leg_wall": true, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "track": {"grade": 0.35, "smooth_m": 10, "tol": 0.02, "reach": 10, "least": 5, "cut": 1.0, "fill": 1.0, "tilt": 0, "plan_tol_m": 1, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.3, "ditch_m": 0.3, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 3, "shoulder_m": 0.4, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.15, "sag_height_m": 0.1, "clearance_m": 4.5, "clearance_least_m": 3, "bore_m": 5, "bore_least_m": 3, "deck_least_m": 0.4, "roof_least_m": 0.3, "group": "track", "inner_radius_m": 2, "corner_radius_m": 3, "corner_radius_walk_m": 3, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.15, "fill_max": 1.5, "cut_max": 2},
+  "path": {"grade": null, "smooth_m": 3, "tol": 0.02, "reach": 3, "least": 0, "cut": 1.0, "fill": 1.0, "tilt": 0.5, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1, "shoulder_m": 0, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.15, "sag_height_m": 0.1, "clearance_m": 2.5, "clearance_least_m": 2, "bore_m": 2.6, "bore_least_m": 2, "deck_least_m": 0.2, "roof_least_m": 0.2, "group": "path", "inner_radius_m": 1, "corner_radius_m": 1, "corner_radius_walk_m": 1, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.3, "fill_max": 3, "cut_max": 3},
+  "footway": {"grade": null, "smooth_m": 3, "tol": 0.02, "reach": 3, "least": 0, "cut": 1.0, "fill": 1.0, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1, "shoulder_m": 0, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 2.5, "clearance_least_m": 2, "bore_m": 2.6, "bore_least_m": 2, "deck_least_m": 0.2, "roof_least_m": 0.2, "group": "path", "inner_radius_m": 1, "corner_radius_m": 1, "corner_radius_walk_m": 1, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.3, "fill_max": 3, "cut_max": 3},
+  "cycleway": {"grade": null, "smooth_m": 5, "tol": 0.02, "reach": 3, "least": 0, "cut": 1.0, "fill": 1.0, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1.5, "shoulder_m": 0, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 2.5, "clearance_least_m": 2, "bore_m": 2.6, "bore_least_m": 2, "deck_least_m": 0.2, "roof_least_m": 0.2, "group": "path", "inner_radius_m": 1, "corner_radius_m": 1, "corner_radius_walk_m": 1, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.3, "fill_max": 3, "cut_max": 3},
+  "bridleway": {"grade": null, "smooth_m": 3, "tol": 0.02, "reach": 3, "least": 0, "cut": 1.0, "fill": 1.0, "tilt": 0.5, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1, "shoulder_m": 0, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.15, "sag_height_m": 0.1, "clearance_m": 2.5, "clearance_least_m": 2, "bore_m": 2.6, "bore_least_m": 2, "deck_least_m": 0.2, "roof_least_m": 0.2, "group": "path", "inner_radius_m": 1, "corner_radius_m": 1, "corner_radius_walk_m": 1, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.3, "fill_max": 3, "cut_max": 3},
+  "steps": {"grade": null, "smooth_m": 2, "tol": 0.02, "reach": 3, "least": 0, "cut": 2.1445, "fill": 0.7002, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 1, "shoulder_m": 0, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 2.5, "clearance_least_m": 2, "bore_m": 2.6, "bore_least_m": 2, "deck_least_m": 0.2, "roof_least_m": 0.2, "group": "steps", "inner_radius_m": 0, "corner_radius_m": 0, "corner_radius_walk_m": 0, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.3, "fill_max": 3, "cut_max": 3},
+  "pedestrian": {"grade": null, "smooth_m": 5, "tol": 0.02, "reach": 3, "least": 0, "cut": 1.0, "fill": 1.0, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 3, "shoulder_m": 0, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.05, "sag_height_m": 0.03, "clearance_m": 2.5, "clearance_least_m": 2, "bore_m": 2.6, "bore_least_m": 2, "deck_least_m": 0.2, "roof_least_m": 0.2, "group": "path", "inner_radius_m": 1, "corner_radius_m": 1, "corner_radius_walk_m": 1, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.3, "fill_max": 3, "cut_max": 3},
+  "via_ferrata": {"grade": null, "smooth_m": 2, "tol": 0.02, "reach": 3, "least": 0, "cut": 1.0, "fill": 1.0, "tilt": 0, "plan_tol_m": 0.3, "design_kmh": 0, "bank": 0, "widen_m": 0, "keep_m": 0.5, "ditch_m": 0, "sidewalk_m": 0, "sidewalk_steep": 0.5, "sidewalk_margin_m": 1, "half_m": 0.6, "shoulder_m": 0, "kerb_m": 0, "kerb_top_m": 0, "snap_m": 1, "snap_height_m": 0.5, "sag_plan_m": 0.15, "sag_height_m": 0.1, "clearance_m": 2.5, "clearance_least_m": 2, "bore_m": 2.6, "bore_least_m": 2, "deck_least_m": 0.2, "roof_least_m": 0.2, "group": "path", "inner_radius_m": 1, "corner_radius_m": 1, "corner_radius_walk_m": 1, "leg_wall": false, "shoulder_paved": false, "verge_m": 0, "return_grade": 0.3, "fill_max": 3, "cut_max": 3}
 }
diff --git a/data/trailview/waterways.json b/data/trailview/waterways.json
index d8b6c92f12..0b007fdeda 100644
--- a/data/trailview/waterways.json
+++ b/data/trailview/waterways.json
@@ -1,5 +1,5 @@
 {
-  "river": {"width_m": 10, "tol": 0.02, "reach": 15, "least": 2, "cut": 0.5, "fill": 0.5, "cover_m": 1, "cover_lift_max_m": 1.5, "culvert_max_m": 60},
-  "canal": {"width_m": 10, "tol": 0.02, "reach": 15, "least": 2, "cut": 0.5, "fill": 0.5, "cover_m": 1, "cover_lift_max_m": 1.5, "culvert_max_m": 60},
-  "stream": {"width_m": 1, "tol": 0.02, "reach": 15, "least": 2, "cut": 0.5, "fill": 0.5, "cover_m": 1, "cover_lift_max_m": 1.5, "culvert_max_m": 60}
+  "river": {"width_m": 10, "tol": 0.02, "reach": 15, "least": 2, "cut": 0.5, "fill": 0.5, "cover_m": 1, "cover_lift_max_m": 1.5, "culvert_max_m": 60, "culvert_width_m": 3, "pipe_width_m": 0.6, "stones_width_m": 2, "clearance_m": 1.5, "clearance_least_m": 0.3, "sag_plan_m": 0.05, "sag_height_m": 0.03, "curve_turn_max_deg": 60, "curve_off_max_m": 2, "freeboard_m": 0.8, "bank_m": 2, "depth_m": 1.0, "bank_slope": 0.6, "bank_reach_m": 15, "bank_steepest": 1.5, "underground_m": 10},
+  "canal": {"width_m": 10, "tol": 0.02, "reach": 15, "least": 2, "cut": 0.5, "fill": 0.5, "cover_m": 1, "cover_lift_max_m": 1.5, "culvert_max_m": 60, "culvert_width_m": 3, "pipe_width_m": 0.6, "stones_width_m": 2, "clearance_m": 1.5, "clearance_least_m": 0.3, "sag_plan_m": 0.05, "sag_height_m": 0.03, "curve_turn_max_deg": 60, "curve_off_max_m": 2, "freeboard_m": 0.8, "bank_m": 2, "depth_m": 1.0, "bank_slope": 0.6, "bank_reach_m": 15, "bank_steepest": 1.5, "underground_m": 10},
+  "stream": {"width_m": 1, "tol": 0.02, "reach": 15, "least": 2, "cut": 0.5, "fill": 0.5, "cover_m": 1, "cover_lift_max_m": 1.5, "culvert_max_m": 60, "culvert_width_m": 3, "pipe_width_m": 0.6, "stones_width_m": 2, "clearance_m": 1.5, "clearance_least_m": 0.3, "sag_plan_m": 0.05, "sag_height_m": 0.03, "curve_turn_max_deg": 60, "curve_off_max_m": 2, "freeboard_m": 0.4, "bank_m": 0.6, "depth_m": 0.3, "bank_slope": 1.2, "bank_reach_m": 4, "bank_steepest": 2.0, "underground_m": 10}
 }
diff --git a/docs/design/map.json b/docs/design/map.json
index 4bcd67b123..896a1942d7 100644
--- a/docs/design/map.json
+++ b/docs/design/map.json
@@ -133,7 +133,7 @@
    "depends_on": [],
    "test_depends_on": [],
    "violations": 1,
-   "lines": 33260,
+   "lines": 33274,
    "problems": [
     {
      "rule": "R4",
@@ -305,7 +305,7 @@
     "repository-tooling"
    ],
    "violations": 10,
-   "lines": 11632,
+   "lines": 12271,
    "problems": [
     {
      "rule": "cycle",
@@ -333,7 +333,7 @@
     },
     {
      "rule": "cycle",
-     "message": "device-map-builder -> trailview closes a cycle: builder/web/scripts/check-wgsl.mjs -> builder/web/src/lib/trailview/gpu/include.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/frame/space.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/terrain/bins.ts, and 26 more"
+     "message": "device-map-builder -> trailview closes a cycle: builder/web/scripts/check-wgsl.mjs -> builder/web/src/lib/trailview/gpu/include.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/frame/space.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/terrain/bins.ts, and 28 more"
     },
     {
      "rule": "cycle",
@@ -543,7 +543,7 @@
     "content"
    ],
    "violations": 10,
-   "lines": 24637,
+   "lines": 24646,
    "problems": [
     {
      "rule": "cycle",
@@ -696,7 +696,7 @@
     "repository-tooling"
    ],
    "violations": 4,
-   "lines": 9951,
+   "lines": 9954,
    "problems": [
     {
      "rule": "R1",
@@ -708,7 +708,7 @@
     },
     {
      "rule": "R1",
-     "message": "crate obc-data-steps (obc-data) holds 2 file(s) of planner-map-baking"
+     "message": "crate obc-data-steps (obc-data) holds 4 file(s) of planner-map-baking"
     },
     {
      "rule": "R1",
@@ -725,11 +725,11 @@
    "depends_on": [],
    "test_depends_on": [],
    "violations": 2,
-   "lines": 6068,
+   "lines": 6121,
    "problems": [
     {
      "rule": "R1",
-     "message": "crate obc-data-steps (obc-data) holds 2 file(s) of planner-map-baking"
+     "message": "crate obc-data-steps (obc-data) holds 4 file(s) of planner-map-baking"
     },
     {
      "rule": "R4",
@@ -780,7 +780,7 @@
    ],
    "test_depends_on": [],
    "violations": 0,
-   "lines": 18785,
+   "lines": 18954,
    "problems": []
   },
   {
@@ -856,7 +856,7 @@
     },
     {
      "rule": "cycle",
-     "message": "trailview -> route-planning closes a cycle: builder/web/src/lib/trailview/dressing/dressing.ts -> builder/web/src/lib/planner/layers/mercator.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/config.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/geo.ts, and 36 more"
+     "message": "trailview -> route-planning closes a cycle: builder/web/src/lib/trailview/dressing/dressing.ts -> builder/web/src/lib/planner/layers/mercator.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/config.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/geo.ts, and 38 more"
     }
    ]
   },
@@ -976,11 +976,11 @@
    ],
    "test_depends_on": [],
    "violations": 5,
-   "lines": 55663,
+   "lines": 101940,
    "problems": [
     {
      "rule": "cycle",
-     "message": "device-map-builder -> trailview closes a cycle: builder/web/scripts/check-wgsl.mjs -> builder/web/src/lib/trailview/gpu/include.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/frame/space.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/terrain/bins.ts, and 26 more"
+     "message": "device-map-builder -> trailview closes a cycle: builder/web/scripts/check-wgsl.mjs -> builder/web/src/lib/trailview/gpu/include.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/frame/space.ts, builder/web/scripts/road-census.ts -> builder/web/src/lib/trailview/terrain/bins.ts, and 28 more"
     },
     {
      "rule": "cycle",
@@ -988,11 +988,11 @@
     },
     {
      "rule": "dependency",
-     "message": "trailview tests use device-map-builder but test_depends_on does not list it: builder/web/src/lib/trailview/roads/mesh.test.ts -> builder/web/test-support/trailview/census.ts (test)"
+     "message": "trailview tests use device-map-builder but test_depends_on does not list it: builder/web/src/lib/trailview/roads/mesh.test.ts -> builder/web/test-support/trailview/census.ts (test), builder/web/src/lib/trailview/terrain/model.test.ts -> builder/web/test-support/fake-caches.ts (test), builder/web/src/lib/trailview/terrain/stamp-cache.test.ts -> builder/web/test-support/fake-caches.ts (test), and 2 more"
     },
     {
      "rule": "cycle",
-     "message": "trailview -> route-planning closes a cycle: builder/web/src/lib/trailview/dressing/dressing.ts -> builder/web/src/lib/planner/layers/mercator.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/config.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/geo.ts, and 36 more"
+     "message": "trailview -> route-planning closes a cycle: builder/web/src/lib/trailview/dressing/dressing.ts -> builder/web/src/lib/planner/layers/mercator.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/config.ts, builder/web/src/lib/trailview/engine.ts -> builder/web/src/lib/planner/geo.ts, and 38 more"
     },
     {
      "rule": "R4",
@@ -1012,7 +1012,7 @@
    ],
    "test_depends_on": [],
    "violations": 0,
-   "lines": 87,
+   "lines": 100,
    "problems": []
   },
   {
@@ -1045,7 +1045,7 @@
    ],
    "test_depends_on": [],
    "violations": 0,
-   "lines": 10742,
+   "lines": 11044,
    "problems": []
   },
   {
diff --git a/docs/design/repository-tooling.md b/docs/design/repository-tooling.md
index 35161aee87..da8a6ae19f 100644
--- a/docs/design/repository-tooling.md
+++ b/docs/design/repository-tooling.md
@@ -10,6 +10,7 @@ owns:
   - tools/install-geos.sh
   - tools/install-riscv.sh
   - tools/obc-dev.sh
+  - tools/sccache-rustc.sh
   - tools/ready.py
   - tools/agent_time.py
   - tools/test_plan.py
diff --git a/docs/design/trailview.md b/docs/design/trailview.md
index 05f84c1aa1..ac303c322b 100644
--- a/docs/design/trailview.md
+++ b/docs/design/trailview.md
@@ -5,7 +5,11 @@ area: Data and services
 purpose: "Renders a region as an explorable 3-D landscape in the browser."
 owns:
   - host/obc-trailview-features/**
+  - host/obc-ground-plan/**
+  - builder/ground-plan-wasm/**
   - builder/web/src/lib/trailview/**
+  - builder/web/src/plan-timing.ts
+  - builder/web/plan-timing.html
   - tools/trailview/**
   - tools/planner_trailview_canopy.py
 depends_on:
diff --git a/docs/testing.md b/docs/testing.md
index fdccd1543a..b405aff4ec 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -43,8 +43,8 @@ Selection is per suite, never per test function. A binary that mixes ordinary wo
 captured-fixture, live or manual work is split into separate units. Captured fixtures are ordinary
 work gated on `required-features = ["external-fixtures"]`; a missing package fails with the exact
 `obc fixtures sync` command. Physical procedures have no route; they live in their issue.
-Each Monday, `test-weekly.yml` runs manual iOS application tests, every TrailView browser test and
-ordinary storage tests with default features.
+Each Monday, `test-weekly.yml` runs manual iOS application tests and ordinary storage tests with
+default features.
 
 ## The plan documents
 
@@ -73,7 +73,7 @@ A `[[suite]]` entry is verification no Cargo package owns:
 | `scoped` | follows its own inputs instead of broad policy or unowned-deletion selection |
 | `rust_packages` | linked libraries; Cargo supplies their non-development dependencies |
 | `rust_excludes` | source paths outside the linked feature set |
-| `package`, `targets` | Cargo test targets this suite owns, which then belong to no tier |
+| `package`, `targets` | Cargo test targets this suite owns; the fast tier runs them when the plan selects an ordinary or required owner, or with no plan (`obc test full`) |
 
 Neither entry lists dependencies, test counts, durations or source files; Cargo and the result
 artifacts supply those. The CI job table is in `tools/test_plan.py`; `obc suites validate-filters`
diff --git a/firmware/tools/dependency_rules.json b/firmware/tools/dependency_rules.json
index da793633b7..85671d9c53 100644
--- a/firmware/tools/dependency_rules.json
+++ b/firmware/tools/dependency_rules.json
@@ -66,6 +66,8 @@
       "obc-fit",
       "obc-fixtures",
       "obc-flat-device",
+      "obc-ground-plan",
+      "obc-ground-plan-bridge",
       "obc-host-core",
       "obc-inspect",
       "obc-ios-host",
diff --git a/host/obc-data-steps/src/functions.rs b/host/obc-data-steps/src/functions.rs
index 567eefb35c..af11eb53ed 100644
--- a/host/obc-data-steps/src/functions.rs
+++ b/host/obc-data-steps/src/functions.rs
@@ -26,6 +26,8 @@ pub static ROUTING: Function = Function { name: "planner-router-build/routing",
 pub static SEARCH: Function = Function { name: "obc-search-bake/search", run: obc_search_bake::step::step };
 pub static TRAILVIEW_FEATURES: Function =
     Function { name: "obc-trailview-features/features", run: obc_trailview_features::step::step };
+pub static TRAILVIEW_STAMPS: Function =
+    Function { name: "obc-trailview-features/stamps", run: obc_trailview_features::stamps::step };
 pub static PLANNER_CATALOG: Function =
     Function { name: "obc-data-steps/planner-catalog", run: crate::planner::catalog::pointer };
 
@@ -48,6 +50,7 @@ pub const FUNCTIONS: &[&Function] = &[
     &ROUTING,
     &SEARCH,
     &TRAILVIEW_FEATURES,
+    &TRAILVIEW_STAMPS,
     &PLANNER_CATALOG,
     &obc_data::engine::PASS,
 ];
diff --git a/host/obc-data-steps/src/planner.rs b/host/obc-data-steps/src/planner.rs
index f655e5f514..b31b63df8c 100644
--- a/host/obc-data-steps/src/planner.rs
+++ b/host/obc-data-steps/src/planner.rs
@@ -64,9 +64,11 @@ pub static PLANNER_PLACES: Layer = whole("planner/places", 1, &[&WEB_PLANNER]);
 pub static PLANNER_CLIMATE: Layer = whole("planner/climate", 1, &[&WEB_PLANNER]);
 /// The snow archives of `specs/planner-snow-tiles.md`.
 pub static PLANNER_SNOW: Layer = whole("planner/snow", 2, &[&WEB_PLANNER]);
-/// Its format is `features_format` of `specs/trailview-features.md`.
+/// Its format is `features_format` of `specs/trailview-features.md`. Its step `planner/trailview-stamps`
+/// holds what the stamp worker makes of the tiles; `stamp_version` of `specs/trailview-tiles.md` says
+/// which stamp code made it.
 pub static PLANNER_TRAILVIEW_FEATURES: Layer =
-    Layer { revision: 12, ..whole("planner/trailview-features", 4, &[&WEB_PLANNER]) };
+    Layer { revision: 21, ..whole("planner/trailview-features", 4, &[&WEB_PLANNER]) };
 /// The TrailView ruleset, `rules.json` of `specs/trailview-tiles.md`. Its format is `format` of
 /// `rules.json`, `FORMAT` of `tools/trailview/rules.py`.
 pub static PLANNER_TRAILVIEW_RULES: Layer =
@@ -608,21 +610,40 @@ impl Planner {
             let waterways: serde_json::Value =
                 serde_json::from_str(include_str!("../../../data/trailview/waterways.json"))
                     .map_err(|e| Unplanned::Failed(format!("data/trailview/waterways.json: {e}")))?;
+            let finishes: serde_json::Value =
+                serde_json::from_str(include_str!("../../../data/trailview/finishes.json"))
+                    .map_err(|e| Unplanned::Failed(format!("data/trailview/finishes.json: {e}")))?;
             // The heights of roads, rivers and lakes come from the master terrain, by the class rules of the
             // roads; the sea, which OSM maps only as coastlines, from the water polygons.
             let sea = snapshot(inputs, store, "water-polygons", Vec::new(), &mut wanted)?;
+            let plan: serde_json::Value = serde_json::from_str(include_str!("../../../data/trailview/plan.json"))
+                .map_err(|e| Unplanned::Failed(format!("data/trailview/plan.json: {e}")))?;
+            // The rules of the ground plan's levels that the bake runs, as the solver's rows of the roads.
+            let levels = obc_trailview_features::kinds::level_rows(&roads, &waterways, &plan);
             let roads = obc_trailview_features::kinds::solver_rows(&roads);
             let waterways = obc_trailview_features::kinds::waterway_rows(&waterways);
+            let finishes = obc_trailview_features::kinds::finish_rows(&finishes);
             steps.push(Step {
                 layer: &PLANNER_TRAILVIEW_FEATURES,
                 name: "planner/trailview-features".into(),
                 inputs: vec![Input::step("planner/osm"), Input::step("planner/terrain/grid"), sea],
-                options: json!({"bounds": bounds, "kinds": kinds, "roads": roads, "waterways": waterways,
-                                "attribution": attribution("osm-planet")}),
+                options: json!({"bounds": bounds, "kinds": kinds, "roads": roads, "finishes": finishes,
+                                "waterways": waterways, "levels": levels, "attribution": attribution("osm-planet")}),
                 outputs: vec!["trailview-features.pmtiles".into()],
                 run: Run::Rust(&functions::TRAILVIEW_FEATURES),
                 client: Client::All,
             });
+            steps.push(Step {
+                layer: &PLANNER_TRAILVIEW_FEATURES,
+                name: "planner/trailview-stamps".into(),
+                inputs: vec![Input::step("planner/trailview-features")],
+                // A change of the stamp code stales this step only; the feature tiles stay.
+                options: json!({"bounds": bounds, "attribution": attribution("osm-planet"),
+                                "stamp_sources": stamp_sources(root).map_err(Unplanned::Failed)?}),
+                outputs: vec!["trailview-stamps.pmtiles".into()],
+                run: Run::Rust(&functions::TRAILVIEW_STAMPS),
+                client: Client::All,
+            });
         }
         steps.extend(trailview(root, inputs, store, &on, (bounds, &requested), &config.trailview, &mut wanted)?);
         if on("trailview-canopy") {
@@ -635,6 +656,7 @@ impl Planner {
             "overlays",
             "climate",
             "trailview-features",
+            "trailview-stamps",
             "trailview-ground",
             "trailview-canopy",
         ];
@@ -1217,25 +1239,50 @@ fn trailview(
 /// The digest of the JSON files of `data/trailview/`, by their paths in it, as `digest` of
 /// `tools/trailview/rules.py` gives it.
 fn ruleset(root: &Path) -> Result {
-    fn walk(dir: &Path, base: &Path, out: &mut Vec<(String, String)>) -> Result<(), String> {
-        for entry in std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))? {
-            let path = entry.map_err(|e| e.to_string())?.path();
-            if path.is_dir() {
-                walk(&path, base, out)?;
-            } else if path.extension().is_some_and(|extension| extension == "json") {
-                let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
-                let name = path.strip_prefix(base).unwrap().to_string_lossy().replace('\\', "/");
-                out.push((name, obc_data::store::sha256_hex(&bytes)));
-            }
-        }
-        Ok(())
-    }
     let base = root.join("data/trailview");
     let mut files = Vec::new();
-    walk(&base, &base, &mut files)?;
+    walk(&base, &base, &|path| path.extension().is_some_and(|extension| extension == "json"), &mut files)?;
+    Ok(obc_data::engine::digest(files.iter().map(|(name, sha256)| (name.as_str(), sha256.as_str()))))
+}
+
+/// The digest of the files that the TrailView stamp code can read, by their paths in the repository: the
+/// TypeScript of `builder/web/src/lib/trailview/` but its tests and generated packages, the JSON of
+/// `data/trailview/`, the bake module, the stamp process and the npm lock. It changes with each change of the
+/// stamp version, and with more: the exact version needs Node and the npm packages, which a plan has not.
+fn stamp_sources(root: &Path) -> Result {
+    let mut files = Vec::new();
+    let typescript = |path: &Path| {
+        let name = path.to_string_lossy();
+        name.ends_with(".ts") && !name.ends_with(".test.ts") && !path.components().any(|part| part.as_os_str() == "pkg")
+    };
+    walk(&root.join("builder/web/src/lib/trailview"), root, &typescript, &mut files)?;
+    walk(&root.join("data/trailview"), root, &|path| path.extension().is_some_and(|e| e == "json"), &mut files)?;
+    for name in [
+        "builder/web/vite/stamp-bundle.ts",
+        "builder/web/scripts/trailview-stamps.mjs",
+        "builder/web/package-lock.json",
+    ] {
+        let bytes = std::fs::read(root.join(name)).map_err(|e| format!("{name}: {e}"))?;
+        files.push((name.to_string(), obc_data::store::sha256_hex(&bytes)));
+    }
     Ok(obc_data::engine::digest(files.iter().map(|(name, sha256)| (name.as_str(), sha256.as_str()))))
 }
 
+/// The SHA-256 of each file under `dir` that `keep` takes, by its path from `base`.
+fn walk(dir: &Path, base: &Path, keep: &dyn Fn(&Path) -> bool, out: &mut Vec<(String, String)>) -> Result<(), String> {
+    for entry in std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))? {
+        let path = entry.map_err(|e| e.to_string())?.path();
+        if path.is_dir() {
+            walk(&path, base, keep, out)?;
+        } else if keep(&path) {
+            let bytes = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
+            let name = path.strip_prefix(base).unwrap().to_string_lossy().replace('\\', "/");
+            out.push((name, obc_data::store::sha256_hex(&bytes)));
+        }
+    }
+    Ok(())
+}
+
 /// The sources of a ground chain that its step reads over `bounds`, each once: a source with an
 /// `extent` only where the extent meets the bounds.
 fn ground_sources<'a>(
@@ -1673,13 +1720,18 @@ mod tests {
     fn a_part_that_is_off_keeps_only_the_steps_that_a_part_that_is_on_reads() {
         let temp = temp("planner-parts");
         let store = store(&temp, &["2026-10-01"]);
-        let only = |parts: &[&str]| {
+        let planned = |parts: &[&str]| {
             let mut inputs = inputs(AREA, &[]);
             inputs.settings.layers = parts.iter().map(|part| part.to_string()).collect();
-            let steps = Planner.steps(&root(), &inputs, ®ions(), &store).unwrap().steps;
-            steps.into_iter().map(|step| step.name).collect::>()
+            Planner.steps(&root(), &inputs, ®ions(), &store).unwrap().steps
         };
+        let only = |parts: &[&str]| planned(parts).into_iter().map(|step| step.name).collect::>();
         let features = only(&["trailview-features"]);
+        let bake = planned(&["trailview-features"]).into_iter().find(|s| s.name == "planner/trailview-features");
+        let options = bake.unwrap().options;
+        assert!(options["finishes"]["gravel"]["shoulder_m"].is_number() && options["roads"][0]["half_m"].is_number());
+        let stamps = planned(&["trailview-features"]).into_iter().find(|s| s.name == "planner/trailview-stamps");
+        assert_eq!(stamps.unwrap().options["stamp_sources"], json!(stamp_sources(&root()).unwrap()));
         assert!(["planner/terrain/grid", "planner/trailview-features/grid", "planner/index", catalog::STEP]
             .iter()
             .all(|step| features.contains(*step)));
@@ -1980,7 +2032,7 @@ mod tests {
                 ["planner", "places", ..] => "planner/places",
                 ["planner", "climate", ..] => "planner/climate",
                 ["planner", "snow", ..] => "planner/snow",
-                ["planner", "trailview-features", ..] => "planner/trailview-features",
+                ["planner", "trailview-features" | "trailview-stamps", ..] => "planner/trailview-features",
                 ["planner", "trailview-rules", ..] => "planner/trailview-rules",
                 ["planner", "trailview-material" | "trailview-lithology" | "trailview-region" | "trailview-ground", ..] => {
                     "planner/trailview-ground"
diff --git a/host/obc-data-steps/src/planner/catalog.rs b/host/obc-data-steps/src/planner/catalog.rs
index fcf8d2aecd..f2847ede7c 100644
--- a/host/obc-data-steps/src/planner/catalog.rs
+++ b/host/obc-data-steps/src/planner/catalog.rs
@@ -49,12 +49,13 @@ pub fn named<'a>(
 
 /// The data layers of a release, as `DATA_LAYERS` of `tools/planner_runtime.py`, that `layers` of the
 /// catalogue lists where the release has their TileJSON.
-const DATA_LAYERS: [&str; 11] = [
+const DATA_LAYERS: [&str; 12] = [
     "snow",
     "snow-levels",
     "snow-seasons",
     "climate",
     "trailview-features",
+    "trailview-stamps",
     "trailview-canopy",
     "trailview-ground",
     "trailview-colour-q1",
diff --git a/host/obc-data/README.md b/host/obc-data/README.md
index 08a08b70b2..b8a1c538fc 100644
--- a/host/obc-data/README.md
+++ b/host/obc-data/README.md
@@ -7,8 +7,9 @@ The [data contract](../../specs/obc-data.md) defines bytes and admission checks.
 
 ## Setup
 
-Prepare Rust, Python with `uv`, GEOS and Osmium before an update, and a Java 21 JDK and Maven for
-the planner layers; `obc data` does not install them.
+Prepare Rust, Python with `uv`, GEOS and Osmium before an update, a Java 21 JDK and Maven for
+the planner layers, and `npm ci --prefix builder/web` for TrailView; `obc data` does
+not install them.
 `obc data setup` shows what this machine can do and the tools and credentials that it has.
 
 `data/targets.toml` names the targets: `local` is a folder beside the store, and `prod` the
diff --git a/host/obc-data/src/cli/setup_cli.rs b/host/obc-data/src/cli/setup_cli.rs
index 1e48d8b858..48cc712843 100644
--- a/host/obc-data/src/cli/setup_cli.rs
+++ b/host/obc-data/src/cli/setup_cli.rs
@@ -108,7 +108,8 @@ struct Spec {
     name: &'static str,
     needed_for: &'static str,
     version: &'static [&'static str],
-    minimum: Option,
+    /// The major and the minor version.
+    minimum: Option<(u32, u32)>,
     install: [&'static str; 2],
 }
 
@@ -152,7 +153,7 @@ const TOOLS: [Spec; 9] = [
         name: "Java 21+",
         needed_for: "planner/basemap",
         version: &["java", "--version"],
-        minimum: Some(21),
+        minimum: Some((21, 0)),
         install: ["brew install openjdk@21", "sudo apt install openjdk-21-jdk-headless"],
     },
     Spec {
@@ -163,11 +164,11 @@ const TOOLS: [Spec; 9] = [
         install: ["brew install maven", "sudo apt install maven"],
     },
     Spec {
-        name: "Node 22+",
-        needed_for: "this page, the web apps",
+        name: "Node 22.18+",
+        needed_for: "this page, the web apps, the TrailView stamps (they import TypeScript)",
         version: &["node", "--version"],
-        minimum: Some(22),
-        install: ["brew install node", "install Node 22 or newer with the package manager"],
+        minimum: Some((22, 18)),
+        install: ["brew install node", "install Node 22.18 or newer with the package manager"],
     },
     Spec {
         name: "rclone",
@@ -180,7 +181,7 @@ const TOOLS: [Spec; 9] = [
 
 /// The jobs and the tools that each needs. A credential that a job needs is in [`setup`].
 const DEVICE: [&str; 3] = ["Rust", "C compiler", "osmium-tool"];
-const PLANNER: [&str; 7] = ["Rust", "C compiler", "osmium-tool", "GEOS", "uv", "Java 21+", "Maven"];
+const PLANNER: [&str; 8] = ["Rust", "C compiler", "osmium-tool", "GEOS", "uv", "Java 21+", "Maven", "Node 22.18+"];
 
 /// The tools that the planner steps need and this machine lacks.
 pub(super) fn planner_missing() -> Vec {
@@ -387,9 +388,12 @@ fn tools<'a>(specs: impl IntoIterator, path: &OsStr, home: Opti
                 None => (Readiness::Missing, install.to_string()),
                 Some(version) => match spec
                     .minimum
-                    .filter(|&minimum| major(&version).is_some_and(|major| major < minimum))
+                    .filter(|&minimum| numbers(&version).is_some_and(|found| found < minimum))
                 {
-                    Some(minimum) => (Readiness::Missing, format!("{version}; needs {minimum} or newer: {install}")),
+                    Some((major, 0)) => (Readiness::Missing, format!("{version}; needs {major} or newer: {install}")),
+                    Some((major, minor)) => {
+                        (Readiness::Missing, format!("{version}; needs {major}.{minor} or newer: {install}"))
+                    }
                     None => (Readiness::Ready, version),
                 },
             };
@@ -410,10 +414,12 @@ fn version(program: &Path, args: &[&str]) -> Option {
     Some(first(&output.stdout).or_else(|| first(&output.stderr)).unwrap_or_else(|| "present".into()))
 }
 
-/// The first number in a version line: `21` of `openjdk 21.0.5`, `22` of `v22.1.0`.
-fn major(version: &str) -> Option {
-    let digits: String = version.chars().skip_while(|c| !c.is_ascii_digit()).take_while(char::is_ascii_digit).collect();
-    digits.parse().ok()
+/// The first two numbers in a version line: `(21, 0)` of `openjdk 21.0.5`, `(22, 1)` of `v22.1.0`, `(17, 0)` of `17`.
+fn numbers(version: &str) -> Option<(u32, u32)> {
+    let start = version.find(|c: char| c.is_ascii_digit())?;
+    let mut parts = version[start..].split(|c: char| !c.is_ascii_digit());
+    let major = parts.next()?.parse().ok()?;
+    Some((major, parts.next().and_then(|minor| minor.parse().ok()).unwrap_or(0)))
 }
 
 /// The size of the files under `dir`; links are not followed.
@@ -476,7 +482,15 @@ mod tests {
             "sudo apt install openjdk-21-jdk-headless"
         };
         assert_eq!(tool("osmium-tool"), (Readiness::Ready, "osmium version 1.17.0"));
-        assert_eq!(tool("Node 22+"), (Readiness::Ready, "v22.1.0"));
+        let node = if cfg!(target_os = "macos") {
+            "brew install node"
+        } else {
+            "install Node 22.18 or newer with the package manager"
+        };
+        assert_eq!(
+            tool("Node 22.18+"),
+            (Readiness::Missing, format!("v22.1.0; needs 22.18 or newer: {node}").as_str())
+        );
         assert_eq!(
             tool("Java 21+"),
             (Readiness::Missing, format!("openjdk 17.0.2 2022-01-18; needs 21 or newer: {java}").as_str())
diff --git a/host/obc-ground-plan/Cargo.toml b/host/obc-ground-plan/Cargo.toml
new file mode 100644
index 0000000000..d2282a221e
--- /dev/null
+++ b/host/obc-ground-plan/Cargo.toml
@@ -0,0 +1,32 @@
+[package]
+name = "obc-ground-plan"
+version = "0.1.0"
+edition = "2021"
+publish = false
+license = "GPL-3.0-only"
+description = "The TrailView ground plan of one cell: integer geometry, terrain heights and cross-sections from the feature tiles, the terrain pages and the rule tables"
+
+# The storeys over the ground (decks): their faces, records, meshes and shells. The crate's tests and its debug tool
+# build them; a dependent turns it on to link them (the bridge's own feature `storeys`).
+[features]
+default = ["storeys"]
+storeys = []
+
+[dependencies]
+# Integer polygon slices. No `allow_multithreading`: the crate runs on one thread.
+i_overlay = { version = "9.1.0", default-features = false }
+libm = { workspace = true }
+# The mesh's constrained Delaunay triangulation. Pinned: its exact predicates and its insertion
+# order decide the triangles.
+spade = { version = "=2.15.1", default-features = false }
+# Every build parses the tables the same: the row order is the rank, and floats round-trip.
+serde_json = { workspace = true, features = ["preserve_order", "float_roundtrip"] }
+
+[dev-dependencies]
+flate2 = { workspace = true }
+image = { workspace = true, features = ["png", "webp"] }
+tiny-skia = { version = "0.11", default-features = false, features = ["std", "simd"] }
+
+[[example]]
+name = "debug"
+path = "examples/debug/main.rs"
diff --git a/host/obc-ground-plan/README.md b/host/obc-ground-plan/README.md
new file mode 100644
index 0000000000..70113d2174
--- /dev/null
+++ b/host/obc-ground-plan/README.md
@@ -0,0 +1,112 @@
+# TrailView ground plan
+
+The ground plan of one zoom-16 cell: from the zoom-13 feature tiles about it
+([spec](../../specs/trailview-features.md)), its stored terrain pages and the rule tables of
+`data/trailview` to integer geometry, terrain heights and cross-sections. It is a pure function of
+its inputs: integers, `libm` and ordered collections, no I/O and no threads.
+
+| Module | What it holds |
+| --- | --- |
+| `frame` | `GlobalPoint` (`i64`, 2^-34 of the Mercator square), `CellKey`, the input margin |
+| `tile` | The reader of format 4, the owner of each element of a cell's tiles, `TileCache` |
+| `terrain` | `StoredPage`, `Terrain::wanted` and `Terrain::height`, the Catmull-Rom of the viewer |
+| `sections` | `Sections::way` and `Sections::water` from `roads.json`, `finishes.json`, `waterways.json`; `WidthRules`, the width rule that the feature bake shares; the reach table |
+| `graph` | `graph::build`: the way graph of a cell (parts, ways, samples, junctions, joints, ends, crossings, decks); `graph::check`; `graph::levels`, which the feature bake runs, and `graph::level_tags`, the tags that carry the levels in the tiles and their reader |
+| `cell` | `build_cell`: a cell from its request bytes, stage by stage (`STAGES`), with the time of each; `build_storeys`: the same with the storeys over the ground (decks); `far_request`: a cell's far block alone |
+| `transport` | `Request` (the canonical request bytes), `Flat` (the plan as flat integer arrays, its stats and digest), `vocabulary()` |
+| `debug` | The palette that the debug tool and the viewer's debug draw share |
+| `probe` | Per thread, the caps that a build and the CPU height function hit, for the census; the WASM build counts nothing |
+
+The census of every cell of a release is the binary `census` of
+[`obc-trailview-features`](../obc-trailview-features/README.md#census), beside the release readers.
+
+## Test
+
+```sh
+obc test -p obc-ground-plan
+obc exec cargo clippy -p obc-ground-plan --all-targets -- -D warnings
+```
+
+The fixture tests read `builder/web/tests/browser/trailview/fixture/` and
+`specs/vectors/trailview-features.*`.
+
+## Debug tool
+
+```sh
+obc exec cargo run --release -p obc-ground-plan --example debug -- \
+  --places v06,i07-hairpin [--views builder/web/tests/browser/trailview/road-views-top.json] \
+  [--at NAME=LAT,LON]... [--fixture DIR] [--out .artifacts/ground-plan/debug] \
+  [--size-m 128] [--px 1600] [--layers terrain,inputs,cells] [--gltf] [--probe N] \
+  [--census] [--bench] [--faces-bench [--runs N]]
+obc exec cargo run --release -p obc-ground-plan --example debug -- --sheet COLUMNS,out.png,a.png,...
+obc exec cargo run --release -p obc-ground-plan --example debug -- \
+  requests --out DIR (--places NAMES | --all) [--runs 5]   # requests for check 7 and the timing page
+```
+
+`requests` writes per cell its request bytes and an entry of `index.json`: the plan digest, the
+far block's digest (`far`), bytes (`far_bytes`) and the counts of its check against the near block
+(`far_check`), and the native median times per stage, of the whole build (`total`) and of a
+far-only build (`far`). A far block that the crate refuses is `far: "refused: …"`; the run goes on.
+A far-only build that differs, or a fault of the check, stops the run.
+
+A place is a view of `--views` named `-top`, at the `lat` and `lon` of its query.
+`--places A` takes `A` and every place whose name starts with `A-`. Per place, `--out` gets
+`.png` (north up), `.json` (cells, tiles, counts, unknown pixels, height range, widths
+capped at 15 m, times), with `--gltf` `.glb` (x east, y up, z south, metres about the
+centre), and with `--probe N` `.probe.json` (`[lon, lat, height]` away from every stamp).
+Each layer draws each cell under a mask of its square: a step at a cell line is a fault.
+With the layer `graph`, `.json` also lists the owned points and crossings in the picture.
+With the layer `faces`, it lists the rounds in the picture (centre, radius, owner).
+`--census` writes `junctions.json` over every fixture cell: the owned junctions by host and guest
+class, the host rules, close junction pairs and the summed `GraphStats`. `--bench` writes
+`graph-bench.json`: the build time of the graph per fixture cell (the median of 5, and the first run), and its heap.
+`--faces-bench` writes `faces-bench.json`: per fixture cell the face build time (the best of `--runs`),
+checks 1 and 2, kinks, short features and crashes, with every kink, short feature and fragment place. It builds on 4 threads and prints one line per cell as it ends.
+Run it under a memory cap:
+`systemd-run --user --scope -p MemoryMax=3G -p MemorySwapMax=0 timeout 600  --faces-bench`.
+`--sheet` puts the pictures in rows of `COLUMNS` into `out.png`.
+`--storeys` writes per place the storeys over the ground from above (`-storeys.png`), seen obliquely with the
+crate's heights (`-oblique.png`, `--oblique HEADING,PITCH`, default 30,35), their counts and checks
+(`-storeys.json`) and with `--gltf` `-storeys.glb`.
+
+The heights (run each under the memory cap above):
+
+```sh
+D="obc exec cargo run --release -p obc-ground-plan --example debug -- heights"
+$D --out DIR --places A,B [--at NAME=LAT,LON] [--size-m M] [--px N] [--sections H,...]
+$D --out DIR --fixture-steps [--grid M] [--cells X,Y;...]
+$D --why LAT,LON[;...]     # or --why-g X,Y[;...] (global frame units)
+$D --cost DIR
+$D --out DIR --gpu-check --places A,B [--at NAME=LAT,LON]
+```
+
+| Option | Output |
+| --- | --- |
+| `--places`, `--at` | `NAME-steps.png` (contours every 0.1 m, face edges, steps by class), `NAME-ripple.png`, `NAME-section-H.png` per heading, `heights-view.json` |
+| `--fixture-steps` | `fixture-steps.json` (steps by rule, borders, ripple, steps at label edges with no rule, slopes steeper than a rock face), `inside.json`, `unnamed.json`, `slots-full.json`, `host-missing.json`, `border-differ.json`, `edge-steps.json` |
+| `--why` | Prints the records and both sides' causes at the point and 2 units about it |
+| `--cost` | `cost.json`: the heights per fixture cell on one thread |
+| `--gpu-check` | `blocks.bin` and `points.json` for the GPU probe |
+
+The GPU probe compares the viewer's `heights.wgsl` with `points.json`. Run it from `builder/web`,
+one GPU user at a time:
+
+```sh
+flock /tmp/trailview-gpu.lock node tests/browser/trailview/model-probe.mjs DIR
+```
+
+| Layer | Colour |
+| --- | --- |
+| `terrain` | Hillshade from the north-west; thin contours every 1 m, dark every 5 m; magenta: no height |
+| `inputs` | Bands: grey carriageway over a pale shoulder, blue water. Chords: orange main road, brown road, red path, black track, purple tunnel or gallery, blue waterway, grey other line; dashed on a bridge or in a tunnel. A dot per vertex, a square where `side` is set. Pink: the outer edge of a sidewalk. Grey fill: building; blue fill: lake, river area, sea; green outline: other area. Black dot: point |
+| `cells` | Black: cell lines; faint: level-18 node lines; dashed red: the centre cell grown by its margin; cross: the centre; bar: 10 m |
+| `graph` | Samples: brown road, red path, black rail, blue water; dashed on a deck, dotted in a tunnel; a tick at a cell line. Red: link; orange: synthetic deck. Green dot: junction, with its host arms thick green and its guest arms thin purple for 8 m. Black dot: joint; ring: end. A crossing's letter: D deck, C culvert, F ford, P pipe in stones, S stepping stones, B footbridge, L level crossing, X stacked |
+
+## Pitfalls
+
+- Every transcendental goes through `libm`, and no `HashMap` or `HashSet`: `clippy.toml` forbids
+  the std ones in the crate, its tests and the tool. Rust fuses no multiply and add unless the code
+  calls `mul_add`; do not call it.
+- The feature bake links `sections`: a change to the width rules changes the feature tiles, and the
+  layer bakes again.
+- `image` and `tiny-skia` are dev-dependencies: the tool is an example, so they never reach WASM.
diff --git a/host/obc-ground-plan/clippy.toml b/host/obc-ground-plan/clippy.toml
new file mode 100644
index 0000000000..d3575dbbc5
--- /dev/null
+++ b/host/obc-ground-plan/clippy.toml
@@ -0,0 +1,60 @@
+# The crate gives the same bytes native and in WASM: every transcendental goes through libm, and no
+# collection iterates in an order that changes per run.
+disallowed-methods = [
+    { path = "f64::sin", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::cos", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::tan", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::sin_cos", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::asin", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::acos", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::atan", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::atan2", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::sinh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::cosh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::tanh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::asinh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::acosh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::atanh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::exp", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::exp2", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::exp_m1", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::ln", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::ln_1p", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::log", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::log2", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::log10", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::powf", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::powi", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::cbrt", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f64::hypot", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::sin", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::cos", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::tan", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::sin_cos", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::asin", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::acos", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::atan", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::atan2", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::sinh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::cosh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::tanh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::asinh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::acosh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::atanh", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::exp", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::exp2", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::exp_m1", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::ln", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::ln_1p", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::log", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::log2", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::log10", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::powf", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::powi", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::cbrt", reason = "use libm: the same bytes native and in WASM" },
+    { path = "f32::hypot", reason = "use libm: the same bytes native and in WASM" },
+]
+disallowed-types = [
+    { path = "std::collections::HashMap", reason = "the order changes per run: use BTreeMap, BTreeSet or a sorted Vec" },
+    { path = "std::collections::HashSet", reason = "the order changes per run: use BTreeMap, BTreeSet or a sorted Vec" },
+]
diff --git a/host/obc-ground-plan/examples/debug/draw.rs b/host/obc-ground-plan/examples/debug/draw.rs
new file mode 100644
index 0000000000..8d7fb74bff
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/draw.rs
@@ -0,0 +1,465 @@
+//! The layers of the debug pictures. Each layer draws each cell's own content under a mask of the
+//! cell's square, so every cell line shows two independent builds.
+
+use std::collections::BTreeMap;
+use std::time::Instant;
+
+use core::f64::consts::PI;
+
+use obc_ground_plan::frame::{CellKey, GlobalPoint, CELL_UNITS};
+use obc_ground_plan::sections::Sections;
+use obc_ground_plan::tile::{tile_square, Feature, Geometry, Part};
+use obc_ground_plan::CellInput;
+use tiny_skia::{
+    Color, FillRule, LineCap, LineJoin, Mask, Paint, PathBuilder, Pixmap, Rect, Stroke, StrokeDash, Transform,
+};
+
+use crate::{WATERS, WAYS};
+
+/// OSM bridge values of a way that lies on the ground.
+const GROUND: [&str; 3] = ["no", "boardwalk", "low_water_crossing"];
+/// Level-18 node edges: 2^16 frame units.
+const NODE_18: i64 = 1 << 16;
+
+pub struct Canvas {
+    pub pixmap: Pixmap,
+    x0: f64,
+    y0: f64,
+    /// Frame units per pixel, and metres per frame unit at the centre.
+    upp: f64,
+    mpu: f64,
+}
+
+pub struct Heights {
+    pub values: Vec>,
+    pub unknown: usize,
+    pub range: Option<[f64; 2]>,
+    pub ns: f64,
+}
+
+impl Canvas {
+    pub fn new(px: u32, x0: f64, y0: f64, upp: f64, mpu: f64) -> Canvas {
+        let mut pixmap = Pixmap::new(px, px).expect("a picture of some pixels");
+        pixmap.fill(Color::from_rgba8(235, 235, 230, 255));
+        Canvas { pixmap, x0, y0, upp, mpu }
+    }
+
+    fn size(&self) -> u32 {
+        self.pixmap.width()
+    }
+
+    pub fn px(&self, p: GlobalPoint) -> (f32, f32) {
+        (((p.x as f64 - self.x0) / self.upp) as f32, ((p.y as f64 - self.y0) / self.upp) as f32)
+    }
+
+    fn at(&self, i: f64, j: f64) -> GlobalPoint {
+        GlobalPoint { x: (self.x0 + i * self.upp).round() as i64, y: (self.y0 + j * self.upp).round() as i64 }
+    }
+
+    pub fn metres(&self, m: f64) -> f32 {
+        (m / self.mpu / self.upp) as f32
+    }
+
+    /// A mask of the closed square [x0, y0, x1, y1] of the frame.
+    pub fn mask(&self, [x0, y0, x1, y1]: [i64; 4]) -> Option {
+        let (a, b) = (self.px(GlobalPoint { x: x0, y: y0 }), self.px(GlobalPoint { x: x1, y: y1 }));
+        let rect = Rect::from_ltrb(
+            a.0.max(-1.0),
+            a.1.max(-1.0),
+            b.0.min(self.size() as f32 + 1.0),
+            b.1.min(self.size() as f32 + 1.0),
+        )?;
+        let mut mask = Mask::new(self.size(), self.size())?;
+        mask.fill_path(&PathBuilder::from_rect(rect), FillRule::Winding, false, Transform::identity());
+        Some(mask)
+    }
+}
+
+pub fn paint(r: u8, g: u8, b: u8, a: u8) -> Paint<'static> {
+    let mut paint = Paint::default();
+    paint.set_color_rgba8(r, g, b, a);
+    paint.anti_alias = true;
+    paint
+}
+
+pub fn stroke(width: f32, dashed: bool) -> Stroke {
+    Stroke {
+        width,
+        line_cap: LineCap::Round,
+        line_join: LineJoin::Round,
+        dash: dashed.then(|| StrokeDash::new(vec![6.0, 4.0], 0.0)).flatten(),
+        ..Stroke::default()
+    }
+}
+
+/// The cell square of a key.
+pub fn cell_square(key: CellKey) -> [i64; 4] {
+    let o = key.origin();
+    [o.x, o.y, o.x + CELL_UNITS, o.y + CELL_UNITS]
+}
+
+/// Whether a tile's half-open square holds a point: the tile owns it.
+pub fn holds(tile: (u32, u32), p: GlobalPoint) -> bool {
+    let [x0, y0, x1, y1] = tile_square(tile);
+    (x0..x1).contains(&p.x) && (y0..y1).contains(&p.y)
+}
+
+/// Whether a point lies inside an area, by the copy of the tile that owns the point: even-odd over its rings.
+pub fn inside(f: &Feature, p: GlobalPoint) -> bool {
+    let mut odd = false;
+    for part in f.parts.iter().filter(|part| holds(part.tile, p)) {
+        let n = part.points.len();
+        for i in 0..n {
+            let (a, b) = (part.points[i], part.points[(i + 1) % n]);
+            if (a.y > p.y) != (b.y > p.y) {
+                let x = a.x as f64 + (p.y - a.y) as f64 * (b.x - a.x) as f64 / (b.y - a.y) as f64;
+                if (p.x as f64) < x {
+                    odd = !odd;
+                }
+            }
+        }
+    }
+    odd
+}
+
+/// The height at each pixel centre, from the cell that holds the pixel.
+pub fn heights(canvas: &Canvas, cells: &BTreeMap) -> Heights {
+    let size = canvas.size() as usize;
+    let start = Instant::now();
+    let values: Vec> = (0..size * size)
+        .map(|n| {
+            let p = canvas.at((n % size) as f64 + 0.5, (n / size) as f64 + 0.5);
+            cells.get(&CellKey::of(p)).and_then(|cell| cell.terrain.height(p))
+        })
+        .collect();
+    let ns = start.elapsed().as_secs_f64() * 1e9 / values.len() as f64;
+    let known = values.iter().flatten();
+    let range = known.clone().copied().reduce(f64::min).zip(known.copied().reduce(f64::max)).map(|(a, b)| [a, b]);
+    Heights { unknown: values.iter().filter(|h| h.is_none()).count(), values, range, ns }
+}
+
+/// The light of a slope (rise per metre east and south) from 315°, 45° up.
+pub fn shade(east: f64, south: f64) -> f64 {
+    let (azimuth, altitude) = (315.0 * PI / 180.0, PI / 4.0);
+    let light =
+        [libm::cos(altitude) * libm::sin(azimuth), libm::cos(altitude) * libm::cos(azimuth), libm::sin(altitude)];
+    // The normal in (east, north, up).
+    let normal = [-east, south, 1.0];
+    let length = (normal[0] * normal[0] + normal[1] * normal[1] + 1.0).sqrt();
+    ((normal[0] * light[0] + normal[1] * light[1] + normal[2] * light[2]) / length).max(0.0)
+}
+
+/// A hillshade with contours every 1 m (thin) and 5 m (dark); magenta where no height is known.
+pub fn terrain(canvas: &mut Canvas, heights: &[Option]) {
+    let size = canvas.size() as usize;
+    let pixel_m = canvas.upp * canvas.mpu;
+    let h = |i: usize, j: usize| heights[j.min(size - 1) * size + i.min(size - 1)];
+    let data = canvas.pixmap.data_mut();
+    for j in 0..size {
+        for i in 0..size {
+            let rgb = match h(i, j) {
+                None => [255, 0, 255],
+                Some(here) => {
+                    let at = |di: isize, dj: isize| {
+                        h((i as isize + di).max(0) as usize, (j as isize + dj).max(0) as usize).unwrap_or(here)
+                    };
+                    let east = (at(1, 0) - at(-1, 0)) / (2.0 * pixel_m);
+                    let south = (at(0, 1) - at(0, -1)) / (2.0 * pixel_m);
+                    let light = 0.35 + 0.65 * shade(east, south);
+                    let mut rgb = [205.0 * light, 215.0 * light, 190.0 * light];
+                    let differs =
+                        |step: f64| [at(1, 0), at(0, 1)].iter().any(|&n| (n / step).floor() != (here / step).floor());
+                    let darken = if differs(5.0) {
+                        0.45
+                    } else if differs(1.0) {
+                        0.8
+                    } else {
+                        1.0
+                    };
+                    rgb.iter_mut().for_each(|c| *c *= darken);
+                    rgb.map(|c| c.clamp(0.0, 255.0) as u8)
+                }
+            };
+            let p = 4 * (j * size + i);
+            data[p..p + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]);
+        }
+    }
+}
+
+/// The points of a polyline in pixels.
+pub fn path(canvas: &Canvas, points: &[GlobalPoint], close: bool) -> Option {
+    let mut builder = PathBuilder::new();
+    for (i, &p) in points.iter().enumerate() {
+        let (x, y) = canvas.px(p);
+        if i == 0 {
+            builder.move_to(x, y)
+        } else {
+            builder.line_to(x, y)
+        }
+    }
+    if close {
+        builder.close();
+    }
+    builder.finish()
+}
+
+/// The runs of consecutive owned segments of a line part.
+fn owned_runs(part: &Part) -> Vec<&[GlobalPoint]> {
+    let mut runs = Vec::new();
+    let mut start = None;
+    for i in 0..=part.own.len() {
+        match (start, part.own.get(i).copied().unwrap_or(false)) {
+            (None, true) => start = Some(i),
+            (Some(s), false) => {
+                runs.push(&part.points[s..=i]);
+                start = None;
+            }
+            _ => {}
+        }
+    }
+    runs
+}
+
+fn kind_colour(kind: &str) -> (u8, u8, u8) {
+    match kind {
+        "main-road" => (200, 90, 20),
+        "road" => (120, 100, 30),
+        "path" => (170, 40, 40),
+        "railway" => (40, 40, 40),
+        "tunnel" | "gallery" => (110, 50, 150),
+        "river" | "stream" => (30, 80, 200),
+        _ => (90, 90, 90),
+    }
+}
+
+/// The ways as chords and bands, the sidewalks, water, areas and points.
+pub fn inputs(canvas: &mut Canvas, cells: &BTreeMap, sections: &Sections) {
+    for (&key, cell) in cells {
+        let Some(mask) = canvas.mask(cell_square(key)) else { continue };
+        // Areas: each copy under the cell and its own tile's square.
+        for f in cell.features.iter().filter(|f| f.geometry == Geometry::Area) {
+            let mut polygons: Vec> = Vec::new();
+            for part in &f.parts {
+                match polygons.last_mut() {
+                    Some(polygon) if !part.outer => polygon.push(part),
+                    _ => polygons.push(vec![part]),
+                }
+            }
+            for polygon in polygons {
+                let [a, b] = [cell_square(key), tile_square(polygon[0].tile)];
+                let both = [a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])];
+                if both[0] >= both[2] || both[1] >= both[3] {
+                    continue;
+                }
+                let Some(clip) = canvas.mask(both) else { continue };
+                let mut builder = PathBuilder::new();
+                for ring in &polygon {
+                    if let Some(ring) = path(canvas, &ring.points, true) {
+                        builder.push_path(&ring);
+                    }
+                }
+                let Some(shape) = builder.finish() else { continue };
+                let fill = match f.kind.as_str() {
+                    "building" | "building-part" => Some(paint(130, 130, 130, 200)),
+                    "lake" | "river-area" | "sea" => Some(paint(90, 140, 220, 170)),
+                    _ => None,
+                };
+                match fill {
+                    Some(fill) => {
+                        canvas.pixmap.fill_path(&shape, &fill, FillRule::EvenOdd, Transform::identity(), Some(&clip))
+                    }
+                    None => canvas.pixmap.stroke_path(
+                        &shape,
+                        &paint(40, 110, 40, 220),
+                        &stroke(1.0, false),
+                        Transform::identity(),
+                        Some(&clip),
+                    ),
+                }
+            }
+        }
+        let lines: Vec<&Feature> = cell.features.iter().filter(|f| f.geometry == Geometry::Line).collect();
+        // Bands: every shoulder, lighter, under every carriageway; water as its half-width.
+        for pass in 0..2 {
+            for f in &lines {
+                let kind = f.kind.as_str();
+                let band = match (pass, WAYS.contains(&kind), WATERS.contains(&kind)) {
+                    (0, true, _) => {
+                        let s = sections.way(kind, &f.tags, false);
+                        (s.half_m + s.shoulder_m, paint(250, 245, 200, 110))
+                    }
+                    (1, true, _) => (sections.way(kind, &f.tags, false).half_m, paint(120, 120, 120, 120)),
+                    (1, _, true) => (sections.water(kind, &f.tags).half_m, paint(60, 120, 230, 130)),
+                    _ => continue,
+                };
+                for part in &f.parts {
+                    for run in owned_runs(part) {
+                        if let Some(line) = path(canvas, run, false) {
+                            let width = 2.0 * canvas.metres(band.0);
+                            canvas.pixmap.stroke_path(
+                                &line,
+                                &band.1,
+                                &stroke(width, false),
+                                Transform::identity(),
+                                Some(&mask),
+                            );
+                        }
+                    }
+                }
+            }
+        }
+        // Sidewalks: a line at the outer edge of each side that `walk` marks.
+        for f in lines.iter().filter(|f| WAYS.contains(&f.kind.as_str())) {
+            let s = sections.way(&f.kind, &f.tags, false);
+            let offset = canvas.metres(s.half_m + s.sidewalk_m);
+            for part in &f.parts {
+                let Some(plan) = &part.plan else { continue };
+                for (i, &own) in part.own.iter().enumerate() {
+                    if !own || plan.walk[i] == 0 {
+                        continue;
+                    }
+                    let ((ax, ay), (bx, by)) = (canvas.px(part.points[i]), canvas.px(part.points[i + 1]));
+                    let length = ((bx - ax) * (bx - ax) + (by - ay) * (by - ay)).sqrt().max(1e-6);
+                    // Left of the direction, with y down the picture.
+                    let (lx, ly) = ((by - ay) / length, -(bx - ax) / length);
+                    for (bit, sign) in [(1u8, 1.0f32), (2, -1.0)] {
+                        if plan.walk[i] & bit == 0 {
+                            continue;
+                        }
+                        let (dx, dy) = (sign * lx * offset, sign * ly * offset);
+                        let mut builder = PathBuilder::new();
+                        builder.move_to(ax + dx, ay + dy);
+                        builder.line_to(bx + dx, by + dy);
+                        if let Some(edge) = builder.finish() {
+                            canvas.pixmap.stroke_path(
+                                &edge,
+                                &paint(200, 30, 120, 255),
+                                &stroke(1.0, false),
+                                Transform::identity(),
+                                Some(&mask),
+                            );
+                        }
+                    }
+                }
+            }
+        }
+        // Chords, dashed on a bridge or in a tunnel, and their vertices.
+        for f in &lines {
+            let (r, g, b) = kind_colour(&f.kind);
+            let bridge = f.tags.get("bridge").is_some_and(|v| !GROUND.contains(&v.as_str()));
+            let tunnel = f.kind == "tunnel" || f.tags.get("tunnel").is_some_and(|v| v != "no");
+            let width = if WAYS.contains(&f.kind.as_str()) || WATERS.contains(&f.kind.as_str()) { 1.5 } else { 1.0 };
+            for part in &f.parts {
+                for run in owned_runs(part) {
+                    if let Some(line) = path(canvas, run, false) {
+                        canvas.pixmap.stroke_path(
+                            &line,
+                            &paint(r, g, b, 255),
+                            &stroke(width, bridge || tunnel),
+                            Transform::identity(),
+                            Some(&mask),
+                        );
+                    }
+                }
+                for (v, &p) in part.points.iter().enumerate() {
+                    let touches = part.own.get(v).copied().unwrap_or(false) || v > 0 && part.own[v - 1];
+                    if !touches {
+                        continue;
+                    }
+                    let (x, y) = canvas.px(p);
+                    let side = part.plan.as_ref().is_some_and(|plan| plan.side[v] != 0);
+                    let mark = if side {
+                        Rect::from_xywh(x - 2.5, y - 2.5, 5.0, 5.0).map(PathBuilder::from_rect)
+                    } else {
+                        PathBuilder::from_circle(x, y, 1.6)
+                    };
+                    if let Some(mark) = mark {
+                        canvas.pixmap.fill_path(
+                            &mark,
+                            &paint(r, g, b, 255),
+                            FillRule::Winding,
+                            Transform::identity(),
+                            Some(&mask),
+                        );
+                    }
+                }
+            }
+        }
+        // Points.
+        for f in cell.features.iter().filter(|f| f.geometry == Geometry::Point) {
+            for part in &f.parts {
+                for (&p, &own) in part.points.iter().zip(&part.own) {
+                    let (x, y) = canvas.px(p);
+                    if let (true, Some(dot)) = (own, PathBuilder::from_circle(x, y, 2.5)) {
+                        canvas.pixmap.fill_path(
+                            &dot,
+                            &paint(20, 20, 20, 255),
+                            FillRule::Winding,
+                            Transform::identity(),
+                            Some(&mask),
+                        );
+                    }
+                }
+            }
+        }
+    }
+}
+
+/// The cell lines, the margin of the centre's cell, level-18 node lines, the centre and a 10 m bar.
+pub fn cells(canvas: &mut Canvas, keys: &[CellKey], centre: GlobalPoint) {
+    let size = canvas.size() as f32;
+    let line = |canvas: &mut Canvas, a: (f32, f32), b: (f32, f32), colour: Paint, width: f32, dashed: bool| {
+        let mut builder = PathBuilder::new();
+        builder.move_to(a.0, a.1);
+        builder.line_to(b.0, b.1);
+        if let Some(path) = builder.finish() {
+            canvas.pixmap.stroke_path(&path, &colour, &stroke(width, dashed), Transform::identity(), None);
+        }
+    };
+    let (x0, y0) = (canvas.x0 as i64, canvas.y0 as i64);
+    let (x1, y1) = (x0 + (size as f64 * canvas.upp) as i64, y0 + (size as f64 * canvas.upp) as i64);
+    let mut x = x0.div_euclid(NODE_18) * NODE_18;
+    while x <= x1 {
+        let (px, _) = canvas.px(GlobalPoint { x, y: y0 });
+        line(canvas, (px, 0.0), (px, size), paint(0, 0, 0, 40), 1.0, false);
+        x += NODE_18;
+    }
+    let mut y = y0.div_euclid(NODE_18) * NODE_18;
+    while y <= y1 {
+        let (_, py) = canvas.px(GlobalPoint { x: x0, y });
+        line(canvas, (0.0, py), (size, py), paint(0, 0, 0, 40), 1.0, false);
+        y += NODE_18;
+    }
+    for &key in keys {
+        let [a, b, c, d] = cell_square(key);
+        let (p, q) = (canvas.px(GlobalPoint { x: a, y: b }), canvas.px(GlobalPoint { x: c, y: d }));
+        if let Some(rect) = Rect::from_ltrb(p.0, p.1, q.0, q.1) {
+            canvas.pixmap.stroke_path(
+                &PathBuilder::from_rect(rect),
+                &paint(0, 0, 0, 200),
+                &stroke(1.5, false),
+                Transform::identity(),
+                None,
+            );
+        }
+    }
+    let [a, b, c, d] = CellKey::of(centre).grown();
+    let (p, q) = (canvas.px(GlobalPoint { x: a, y: b }), canvas.px(GlobalPoint { x: c, y: d }));
+    if let Some(rect) = Rect::from_ltrb(p.0, p.1, q.0, q.1) {
+        canvas.pixmap.stroke_path(
+            &PathBuilder::from_rect(rect),
+            &paint(220, 0, 0, 220),
+            &stroke(2.0, true),
+            Transform::identity(),
+            None,
+        );
+    }
+    let (cx, cy) = canvas.px(centre);
+    line(canvas, (cx - 12.0, cy), (cx + 12.0, cy), paint(0, 0, 0, 255), 2.0, false);
+    line(canvas, (cx, cy - 12.0), (cx, cy + 12.0), paint(0, 0, 0, 255), 2.0, false);
+    let bar = canvas.metres(10.0);
+    let (left, bottom) = (20.0, size - 20.0);
+    line(canvas, (left, bottom), (left + bar, bottom), paint(0, 0, 0, 255), 4.0, false);
+    line(canvas, (left, bottom - 8.0), (left, bottom + 2.0), paint(0, 0, 0, 255), 2.0, false);
+    line(canvas, (left + bar, bottom - 8.0), (left + bar, bottom + 2.0), paint(0, 0, 0, 255), 2.0, false);
+}
diff --git a/host/obc-ground-plan/examples/debug/faces.rs b/host/obc-ground-plan/examples/debug/faces.rs
new file mode 100644
index 0000000000..5a0b3e436c
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/faces.rs
@@ -0,0 +1,350 @@
+//! The layer `faces` and the face bench with checks 1 and 2 over the fixture.
+
+use std::collections::BTreeMap;
+use std::time::Instant;
+
+use serde_json::{json, Value};
+use tiny_skia::{FillRule, PathBuilder, Transform};
+
+use crate::draw::{cell_square, paint, path, stroke, Canvas};
+use crate::fixture::Fixture;
+use obc_ground_plan::debug;
+use obc_ground_plan::faces::check::{
+    artefacts, feature_names, kinks, neighbours, partition, short_features, Artefact, ArtefactKind, Fault, Kink,
+    ShortFeature,
+};
+use obc_ground_plan::faces::{self, window, FacePlan, Owner, Rules};
+use obc_ground_plan::frame::{CellKey, GlobalPoint};
+use obc_ground_plan::graph::{self, WayGraph};
+use obc_ground_plan::CellInput;
+
+fn draw_plan(canvas: &mut Canvas, plan: &FacePlan, graph: &WayGraph, input: &CellInput, rules: &Rules) {
+    let o = plan.cell.origin();
+    let g = |p: [i32; 2]| GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) };
+    let mask = canvas.mask(cell_square(plan.cell));
+    for f in &plan.faces {
+        let Some((r, gr, b, a)) = debug::face_colour(f.surface, matches!(f.owner, Owner::Junction(_))) else {
+            continue;
+        };
+        // The legs of a way alternate in hue: odd legs bluer. A band that names its leg's line is red.
+        let (r, gr) = if f.legs[0] % 2 == 1 { (r / 2, gr / 2 + 40) } else { (r, gr) };
+        let (r, gr, b) =
+            if matches!(f.owner, Owner::Terrain) && f.material.is_some() { (255, gr / 3, b / 3) } else { (r, gr, b) };
+        let mut builder = PathBuilder::new();
+        for ring in &f.rings {
+            for (i, &v) in ring.iter().enumerate() {
+                let (x, y) = canvas.px(g(plan.vertices[v as usize]));
+                if i == 0 {
+                    builder.move_to(x, y);
+                } else {
+                    builder.line_to(x, y);
+                }
+            }
+            builder.close();
+        }
+        if let Some(p) = builder.finish() {
+            canvas.pixmap.fill_path(&p, &paint(r, gr, b, a), FillRule::EvenOdd, Transform::identity(), mask.as_ref());
+        }
+    }
+    for e in &plan.edges {
+        let (a, b) = (g(plan.vertices[e.a as usize]), g(plan.vertices[e.b as usize]));
+        if let Some(p) = path(canvas, &[a, b], false) {
+            let (r, gr, b) = debug::edge_colour(e.kind);
+            canvas.pixmap.stroke_path(
+                &p,
+                &paint(r, gr, b, 150),
+                &stroke(0.6, false),
+                Transform::identity(),
+                mask.as_ref(),
+            );
+        }
+    }
+    // Kinks: orange rings.
+    for k in kinks(plan, graph, input, rules) {
+        let (x, y) = canvas.px(g(k.at));
+        if let Some(p) = PathBuilder::from_circle(x, y, 9.0) {
+            canvas.pixmap.stroke_path(
+                &p,
+                &paint(240, 140, 0, 255),
+                &stroke(2.5, false),
+                Transform::identity(),
+                mask.as_ref(),
+            );
+        }
+    }
+    // Short features: green squares.
+    for k in short_features(plan) {
+        let (x, y) = canvas.px(g(k.at));
+        if let Some(r) = tiny_skia::Rect::from_xywh(x - 8.0, y - 8.0, 16.0, 16.0) {
+            let p = PathBuilder::from_rect(r);
+            canvas.pixmap.stroke_path(
+                &p,
+                &paint(0, 170, 60, 255),
+                &stroke(2.5, false),
+                Transform::identity(),
+                mask.as_ref(),
+            );
+        }
+    }
+    // Artefacts: magenta rings.
+    for a in artefacts(plan, graph) {
+        let (x, y) = canvas.px(g(a.at));
+        if let Some(p) = PathBuilder::from_circle(x, y, 6.0) {
+            canvas.pixmap.stroke_path(
+                &p,
+                &paint(230, 0, 200, 255),
+                &stroke(2.0, false),
+                Transform::identity(),
+                mask.as_ref(),
+            );
+        }
+    }
+    // The circle of each round: blue, with its centre.
+    for c in &plan.corners {
+        let (x, y) = canvas.px(g(c.centre));
+        let r = canvas.metres(c.radius_m);
+        for (circle, width) in [(PathBuilder::from_circle(x, y, r), 1.2), (PathBuilder::from_circle(x, y, 2.0), 3.0)] {
+            if let Some(p) = circle {
+                canvas.pixmap.stroke_path(
+                    &p,
+                    &paint(30, 80, 220, 220),
+                    &stroke(width, false),
+                    Transform::identity(),
+                    mask.as_ref(),
+                );
+            }
+        }
+    }
+    for j in &graph.junctions {
+        let (x, y) = canvas.px(g(j.pos));
+        if let Some(p) = PathBuilder::from_circle(x, y, 2.5) {
+            canvas.pixmap.fill_path(
+                &p,
+                &paint(0, 160, 60, 255),
+                FillRule::Winding,
+                Transform::identity(),
+                mask.as_ref(),
+            );
+        }
+    }
+}
+
+/// The faces of each cell inside its square: carriageways grey, junction faces purple, shoulders
+/// grey-tan, slopes olive, rail beds brown, crossings red; edges thin; artefacts in magenta rings;
+/// junction points green.
+pub fn layer(
+    canvas: &mut Canvas,
+    plans: &BTreeMap,
+    cells: &BTreeMap,
+    rules: &Rules,
+) {
+    for (key, (plan, graph)) in plans {
+        draw_plan(canvas, plan, graph, &cells[key], rules);
+    }
+}
+
+pub fn quantiles(mut v: Vec) -> Value {
+    if v.is_empty() {
+        return json!(null);
+    }
+    v.sort_by(f64::total_cmp);
+    let q = |f: f64| v[((v.len() - 1) as f64 * f).round() as usize];
+    json!({"n": v.len(), "median": q(0.5), "p95": q(0.95), "max": q(1.0)})
+}
+
+/// A cell with this many junctions or more is a town cell in the profile.
+pub const TOWN_JUNCTIONS: u32 = 20;
+
+/// One cell of the bench: its plan and graph, the build time (the least of `runs`) and its checks.
+struct Built {
+    plan: FacePlan,
+    graph: WayGraph,
+    features: Vec<[u32; 3]>,
+    ms: f64,
+    faults: Vec,
+    kinks: Vec,
+    short: Vec,
+    artefacts: Vec,
+}
+
+/// A cell's build of least time of `runs` and its check 1 and kinks; None if a build panics.
+fn bench_cell(key: CellKey, input: &obc_ground_plan::CellInput, rules: &Rules, runs: usize) -> Option {
+    let graph = graph::build(key, input, &rules.sections);
+    let (mut best, mut plan) = (f64::INFINITY, None);
+    for _ in 0..runs {
+        let start = Instant::now();
+        let built =
+            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| faces::build(&graph, input, rules, key, 0, true)));
+        best = best.min(start.elapsed().as_secs_f64() * 1e3);
+        plan = Some(built.ok()?);
+    }
+    let plan = plan?;
+    let (faults, kinks, artefacts) =
+        (partition(&plan, window(key, 0.0)), kinks(&plan, &graph, input, rules), artefacts(&plan, &graph));
+    let short = short_features(&plan);
+    Some(Built { plan, graph, features: feature_names(input), ms: best, faults, kinks, short, artefacts })
+}
+
+/// Per fixture cell: the face build's total time (the run of least time of `runs`), its sizes,
+/// check 1 (partition faults and artefacts) and check 2 (each shared border), with panics caught. The
+/// cells build on the workers of `Fixture::map`; each prints its line as it ends.
+pub fn bench(fixture: &mut Fixture, cells: &[CellKey], rules: &Rules, runs: usize) -> Value {
+    let built = fixture.map(cells, |key, input| {
+        let b = bench_cell(key, &input, rules, runs);
+        match &b {
+            Some(b) => {
+                let s = &b.plan.stats;
+                eprintln!(
+                    "cell {} {} {:.1} ms, {} candidates, {} segments, {} faces, {} vertices",
+                    key.x, key.y, b.ms, s.candidates, s.slice_segments, s.faces, s.vertices
+                );
+            }
+            None => eprintln!("cell {} {} crash", key.x, key.y),
+        }
+        b
+    });
+    let mut total_ms: BTreeMap> = BTreeMap::new();
+    let mut sizes: BTreeMap<&str, Vec> = BTreeMap::new();
+    let mut slowest: Vec<(f64, [u32; 2])> = Vec::new();
+    let mut plans: BTreeMap)> = BTreeMap::new();
+    let (mut partition_faults, mut artefact_cells, mut crashes) = (Vec::new(), Vec::new(), Vec::new());
+    let mut kinds: BTreeMap = BTreeMap::new();
+    let mut causes: BTreeMap)> = BTreeMap::new();
+    let (mut kink_count, mut kink_examples) = (0, Vec::new());
+    let mut short_examples = Vec::new();
+    for (&key, b) in cells.iter().zip(built) {
+        let Some(Built { plan, graph, features, ms: total, faults, kinks: bent, short, artefacts: found }) = b else {
+            crashes.push([key.x, key.y]);
+            continue;
+        };
+        let town = plan.stats.junctions >= TOWN_JUNCTIONS;
+        total_ms.entry(town).or_default().push(total);
+        slowest.push((total, [key.x, key.y]));
+        let s = &plan.stats;
+        for (name, v) in [
+            ("ways", s.ways),
+            ("points", s.junctions + s.joints + s.turns),
+            ("candidates", s.candidates),
+            ("slice_segments", s.slice_segments),
+            ("faces", s.faces),
+            ("vertices", s.vertices),
+        ] {
+            sizes.entry(name).or_default().push(f64::from(v));
+        }
+        for f in faults {
+            partition_faults.push(format!("{key:?}: {}", f.what));
+        }
+        kink_count += bent.len();
+        for k in &bent {
+            let o = key.origin();
+            let (lon, lat) = crate::lon_lat(GlobalPoint { x: o.x + i64::from(k.at[0]), y: o.y + i64::from(k.at[1]) });
+            kink_examples.push(json!({"cell": [key.x, key.y], "lat": lat, "lon": lon, "radius_m": k.radius_m}));
+        }
+        for k in &short {
+            let o = key.origin();
+            let (lon, lat) = crate::lon_lat(GlobalPoint { x: o.x + i64::from(k.at[0]), y: o.y + i64::from(k.at[1]) });
+            short_examples.push(json!({"cell": [key.x, key.y], "lat": lat, "lon": lon, "size_m": k.size_m,
+                "turn_deg": k.turn.to_degrees()}));
+        }
+        // One count per face and kind.
+        let mut seen = std::collections::BTreeSet::new();
+        let mut here = 0;
+        for x in &found {
+            let f = &plan.faces[x.face as usize];
+            let owner = match f.owner {
+                Owner::Terrain => "terrain",
+                Owner::Way(_) => "way",
+                Owner::Junction(_) => "junction",
+                Owner::Platform(_) => "platform",
+            };
+            if !seen.insert((x.face, x.kind)) {
+                continue;
+            }
+            here += 1;
+            let o = key.origin();
+            let (lon, lat) = crate::lon_lat(GlobalPoint { x: o.x + i64::from(x.at[0]), y: o.y + i64::from(x.at[1]) });
+            let e = causes.entry(format!("{:?} {:?} {owner}", x.kind, f.surface)).or_insert((0, Vec::new()));
+            e.0 += 1;
+            if e.1.len() < 8 || x.kind == ArtefactKind::Fragment {
+                e.1.push(json!({"cell": [key.x, key.y], "lat": lat, "lon": lon}));
+            }
+            *kinds.entry(format!("{:?}", x.kind)).or_insert(0) += 1;
+        }
+        if here > 0 {
+            artefact_cells.push(json!({"cell": [key.x, key.y], "artefacts": here}));
+        }
+        plans.insert(key, (plan, graph, features));
+    }
+    let mut border_faults = Vec::new();
+    let mut borders = 0;
+    for (&key, a) in &plans {
+        for (east, other) in [(true, CellKey { x: key.x + 1, y: key.y }), (false, CellKey { x: key.x, y: key.y + 1 })] {
+            if let Some(b) = plans.get(&other) {
+                borders += 1;
+                for f in neighbours((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), east) {
+                    border_faults.push(format!("{key:?}|{other:?}: {}", f.what));
+                }
+            }
+        }
+    }
+    slowest.sort_by(|a, b| b.0.total_cmp(&a.0));
+    let profile: serde_json::Map = total_ms
+        .into_iter()
+        .map(|(town, v)| (format!("{} total", if town { "town" } else { "rural" }), quantiles(v)))
+        .collect();
+    json!({
+        "cells": cells.len(),
+        "crashes": crashes,
+        "check1_partition_faults": partition_faults.len(),
+        "check1_partition_examples": partition_faults.iter().take(10).collect::>(),
+        "check1_artefact_faces": kinds,
+        "check1_artefact_cells": artefact_cells,
+        "kinks": kink_count,
+        "kink_places": kink_examples,
+        "short_features": short_examples.len(),
+        "short_places": short_examples,
+        "check1_artefact_causes": causes.into_iter().map(|(k, (n, ex))| json!({"cause": k, "faces": n, "examples": ex})).collect::>(),
+        "borders": borders,
+        "check2_faults": border_faults.len(),
+        "check2_examples": border_faults.iter().take(10).collect::>(),
+        "ms": profile,
+        "slowest": slowest.iter().take(5).map(|(t, k)| json!({"cell": k, "ms": t})).collect::>(),
+        "sizes": sizes.into_iter().map(|(k, v)| (k.to_string(), quantiles(v))).collect::>(),
+    })
+}
+
+/// The rounds in the picture: per round, its centre in pixels, its radius and its owner's kind.
+pub fn corners(canvas: &Canvas, plans: &BTreeMap) -> Value {
+    let size = canvas.pixmap.width() as f32;
+    let mut out = Vec::new();
+    for (plan, _) in plans.values() {
+        let o = plan.cell.origin();
+        for c in &plan.corners {
+            let (x, y) = canvas.px(GlobalPoint { x: o.x + i64::from(c.centre[0]), y: o.y + i64::from(c.centre[1]) });
+            if (0.0..size).contains(&x) && (0.0..size).contains(&y) {
+                let owner = match c.owner {
+                    Owner::Junction(_) => "junction",
+                    Owner::Way(_) => "way",
+                    Owner::Terrain => "terrain",
+                    Owner::Platform(_) => "platform",
+                };
+                out.push(json!({"at": [x.round(), y.round()], "radius_m": c.radius_m, "owner": owner}));
+            }
+        }
+    }
+    Value::Array(out)
+}
+
+/// One plan per cell for the picture layer.
+pub fn plans(
+    cells: &BTreeMap,
+    rules: &Rules,
+) -> BTreeMap {
+    cells
+        .iter()
+        .map(|(&k, input)| {
+            let graph = graph::build(k, input, &rules.sections);
+            (k, (faces::build(&graph, input, rules, k, 0, true), graph))
+        })
+        .collect()
+}
diff --git a/host/obc-ground-plan/examples/debug/gltf.rs b/host/obc-ground-plan/examples/debug/gltf.rs
new file mode 100644
index 0000000000..0ac8cef149
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/gltf.rs
@@ -0,0 +1,128 @@
+//! The glTF of a place: binary glTF 2.0 with one mesh per layer, x east, y up, z south, in metres
+//! about the centre and its height.
+
+use std::collections::BTreeMap;
+
+use obc_ground_plan::frame::{metres_per_unit, CellKey, GlobalPoint};
+use obc_ground_plan::CellInput;
+use serde_json::json;
+
+use crate::draw::shade;
+
+/// The terrain grid's step.
+const STEP_M: f64 = 0.5;
+
+pub struct Mesh {
+    pub name: String,
+    pub positions: Vec<[f32; 3]>,
+    pub colours: Vec<[f32; 3]>,
+    pub indices: Vec,
+}
+
+/// The terrain under the square on a grid of `STEP_M`, hillshaded; magenta at 0 m where no height is known.
+pub fn terrain(cells: &BTreeMap, centre: GlobalPoint, size_m: f64) -> Mesh {
+    let mpu = metres_per_unit(centre.y);
+    let n = (size_m / STEP_M) as usize + 1;
+    let point = |i: usize, j: usize| {
+        let (east, south) = (i as f64 * STEP_M - size_m / 2.0, j as f64 * STEP_M - size_m / 2.0);
+        GlobalPoint { x: centre.x + (east / mpu).round() as i64, y: centre.y + (south / mpu).round() as i64 }
+    };
+    let height = |p: GlobalPoint| cells.get(&CellKey::of(p)).and_then(|c| c.terrain.height(p));
+    let base = height(centre).unwrap_or(0.0);
+    let heights: Vec> = (0..n * n).map(|k| height(point(k % n, k / n))).collect();
+    let at =
+        |i: isize, j: isize| heights[(j.clamp(0, n as isize - 1) as usize) * n + i.clamp(0, n as isize - 1) as usize];
+    let mut mesh = Mesh { name: "terrain".into(), positions: Vec::new(), colours: Vec::new(), indices: Vec::new() };
+    for j in 0..n {
+        for i in 0..n {
+            let (ii, jj) = (i as isize, j as isize);
+            let here = at(ii, jj);
+            let y = here.map_or(0.0, |h| h - base);
+            mesh.positions.push([
+                (i as f64 * STEP_M - size_m / 2.0) as f32,
+                y as f32,
+                (j as f64 * STEP_M - size_m / 2.0) as f32,
+            ]);
+            mesh.colours.push(match here {
+                None => [1.0, 0.0, 1.0],
+                Some(h) => {
+                    let near = |di: isize, dj: isize| at(ii + di, jj + dj).unwrap_or(h);
+                    let light = 0.35
+                        + 0.65
+                            * shade(
+                                (near(1, 0) - near(-1, 0)) / (2.0 * STEP_M),
+                                (near(0, 1) - near(0, -1)) / (2.0 * STEP_M),
+                            );
+                    [0.8 * light as f32, 0.84 * light as f32, 0.75 * light as f32]
+                }
+            });
+        }
+    }
+    for j in 0..n - 1 {
+        for i in 0..n - 1 {
+            // Counter-clockwise seen from above: a, its south neighbour, its east neighbour.
+            let a = (j * n + i) as u32;
+            let (east, south, both) = (a + 1, a + n as u32, a + n as u32 + 1);
+            mesh.indices.extend([a, south, east, east, south, both]);
+        }
+    }
+    mesh
+}
+
+/// The bytes of a binary glTF that holds the meshes.
+pub fn glb(meshes: &[Mesh]) -> Vec {
+    let mut bin: Vec = Vec::new();
+    let (mut views, mut accessors, mut nodes, mut gltf_meshes) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());
+    let mut view = |bin: &mut Vec, bytes: Vec, target: u32| {
+        let at = bin.len();
+        bin.extend(bytes);
+        while !bin.len().is_multiple_of(4) {
+            bin.push(0);
+        }
+        views.push(json!({"buffer": 0, "byteOffset": at, "byteLength": bin.len() - at, "target": target}));
+        views.len() - 1
+    };
+    for (m, mesh) in meshes.iter().enumerate() {
+        let floats = |v: &[[f32; 3]]| v.iter().flatten().flat_map(|f| f.to_le_bytes()).collect::>();
+        let (lo, hi) = mesh.positions.iter().fold(([f32::MAX; 3], [f32::MIN; 3]), |(lo, hi), p| {
+            (std::array::from_fn(|k| lo[k].min(p[k])), std::array::from_fn(|k| hi[k].max(p[k])))
+        });
+        let positions = view(&mut bin, floats(&mesh.positions), 34962);
+        let colours = view(&mut bin, floats(&mesh.colours), 34962);
+        let indices = view(&mut bin, mesh.indices.iter().flat_map(|i| i.to_le_bytes()).collect(), 34963);
+        let first = accessors.len();
+        accessors.push(json!({"bufferView": positions, "componentType": 5126, "count": mesh.positions.len(), "type": "VEC3", "min": lo, "max": hi}));
+        accessors
+            .push(json!({"bufferView": colours, "componentType": 5126, "count": mesh.colours.len(), "type": "VEC3"}));
+        accessors
+            .push(json!({"bufferView": indices, "componentType": 5125, "count": mesh.indices.len(), "type": "SCALAR"}));
+        gltf_meshes.push(json!({"name": mesh.name, "primitives": [{"attributes": {"POSITION": first, "COLOR_0": first + 1}, "indices": first + 2, "mode": 4}]}));
+        nodes.push(json!({"name": mesh.name, "mesh": m}));
+    }
+    let document = json!({
+        "asset": {"version": "2.0", "generator": "obc-ground-plan debug"},
+        "scene": 0,
+        "scenes": [{"nodes": (0..nodes.len()).collect::>()}],
+        "nodes": nodes,
+        "meshes": gltf_meshes,
+        "buffers": [{"byteLength": bin.len()}],
+        "bufferViews": views,
+        "accessors": accessors,
+    });
+    let mut text = serde_json::to_vec(&document).unwrap();
+    while !text.len().is_multiple_of(4) {
+        text.push(b' ');
+    }
+    let total = 12 + 8 + text.len() + 8 + bin.len();
+    let mut out = Vec::with_capacity(total);
+    out.extend(b"glTF");
+    out.extend(2u32.to_le_bytes());
+    out.extend((total as u32).to_le_bytes());
+    out.extend((text.len() as u32).to_le_bytes());
+    out.extend(b"JSON");
+    out.extend(text);
+    out.extend((bin.len() as u32).to_le_bytes());
+    out.extend(b"BIN\0");
+    out.extend(bin);
+    out
+}
diff --git a/host/obc-ground-plan/examples/debug/graph.rs b/host/obc-ground-plan/examples/debug/graph.rs
new file mode 100644
index 0000000000..b7ff1b2420
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/graph.rs
@@ -0,0 +1,437 @@
+//! The `graph` layer of the debug pictures, the junction census and the build bench of the way graph.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::time::Instant;
+
+use obc_ground_plan::debug as palette;
+use obc_ground_plan::frame::{metres_per_unit, CellKey, GlobalPoint};
+use obc_ground_plan::graph::{build, CrossingKind, Family, Level, SampleKind, WayGraph};
+use obc_ground_plan::sections::Sections;
+use serde_json::{json, Value};
+use tiny_skia::{FillRule, PathBuilder, Rect, Stroke, StrokeDash, Transform};
+
+use crate::draw::{cell_square, paint, path, stroke, Canvas};
+use crate::fixture::{feature_tile, Fixture};
+
+fn rgb((r, g, b): palette::Rgb, a: u8) -> tiny_skia::Paint<'static> {
+    paint(r, g, b, a)
+}
+
+/// 5 × 7 glyphs, a row per byte, the high bit of the 5 at the left.
+const GLYPHS: [(CrossingKind, char, [u8; 7]); 9] = [
+    (CrossingKind::Deck, 'D', [0x1e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1e]),
+    (CrossingKind::Culvert, 'C', [0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e]),
+    (CrossingKind::Ford, 'F', [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10]),
+    (CrossingKind::PipeInStones, 'P', [0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10]),
+    (CrossingKind::SteppingStones, 'S', [0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e]),
+    (CrossingKind::Footbridge, 'B', [0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e]),
+    (CrossingKind::LevelCrossing, 'L', [0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f]),
+    (CrossingKind::Stacked, 'X', [0x11, 0x11, 0x0a, 0x04, 0x0a, 0x11, 0x11]),
+    (CrossingKind::Bore, 'T', [0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04]),
+];
+
+/// The levels of each cell, under the cell's mask: the runs of each way with a state by colour (DECK
+/// blue, BORE violet, OPEN grey, HIDDEN red); the end lines black (A), white (portal) or red (closed).
+pub fn levels(canvas: &mut Canvas, graphs: &BTreeMap) {
+    use obc_ground_plan::graph::{EndKind, State};
+    for (&key, g) in graphs {
+        let Some(mask) = canvas.mask(cell_square(key)) else { continue };
+        let o = key.origin();
+        let global = |p: [i32; 2]| GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) };
+        for r in &g.levels.runs {
+            let way = &g.ways[r.way as usize];
+            let inside = |s: &&obc_ground_plan::graph::Sample| {
+                (s.span, s.u) >= (r.from.span, r.from.u) && (s.span, s.u) <= (r.to.span, r.to.u)
+            };
+            let samples = &g.samples[way.samples.start as usize..way.samples.end as usize];
+            let points: Vec = samples.iter().filter(inside).map(|s| global(s.pos)).collect();
+            let colour = match r.state {
+                State::Deck => paint(30, 90, 230, 200),
+                State::Bore => paint(140, 40, 200, 200),
+                State::Open => paint(120, 120, 120, 200),
+                State::Hidden => paint(230, 30, 30, 200),
+            };
+            if let Some(p) = path(canvas, &points, false) {
+                canvas.pixmap.stroke_path(&p, &colour, &stroke(6.0, false), Transform::identity(), Some(&mask));
+            }
+        }
+        for l in &g.levels.end_lines {
+            let colour = match l.kind {
+                EndKind::A => paint(0, 0, 0, 255),
+                EndKind::Portal => paint(255, 255, 255, 255),
+                EndKind::Closed => paint(230, 30, 30, 255),
+            };
+            let width = 2.0;
+            if let Some(p) = path(canvas, &[global(l.ends[0]), global(l.ends[1])], false) {
+                canvas.pixmap.stroke_path(&p, &colour, &stroke(width, false), Transform::identity(), Some(&mask));
+            }
+        }
+    }
+}
+
+/// The graph of each cell, drawn under the cell's mask: samples by family (dashed on a deck, dotted in
+/// a tunnel, a tick at a cell line), links red, synthetic decks orange, host arms thick and guest arms
+/// thin for 8 m, joints as dots, ends as rings, a crossing as its letter.
+pub fn layer(canvas: &mut Canvas, graphs: &BTreeMap) {
+    for (&key, g) in graphs {
+        let Some(mask) = canvas.mask(cell_square(key)) else { continue };
+        let o = key.origin();
+        let global = |p: [i32; 2]| GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) };
+        let synthetic: BTreeSet = g.decks.iter().filter(|d| d.synthetic).flat_map(|d| d.ways.clone()).collect();
+        for way in &g.ways {
+            let samples = &g.samples[way.samples.start as usize..way.samples.end as usize];
+            let points: Vec = samples.iter().map(|s| global(s.pos)).collect();
+            let (r, gr, b) = match (way.link, synthetic.contains(&way.id)) {
+                (Some(_), _) => palette::LINK,
+                (_, true) => palette::SYNTHETIC_DECK,
+                _ => palette::family_colour(way.family),
+            };
+            let mut line = Stroke { width: 2.5, ..stroke(2.5, false) };
+            line.dash = match way.level {
+                Level::Deck => StrokeDash::new(vec![7.0, 4.0], 0.0),
+                Level::Tunnel => StrokeDash::new(vec![1.5, 3.5], 0.0),
+                Level::Ground => None,
+            };
+            if let Some(p) = path(canvas, &points, false) {
+                canvas.pixmap.stroke_path(&p, &paint(r, gr, b, 230), &line, Transform::identity(), Some(&mask));
+            }
+            for s in samples.iter().filter(|s| s.kind == SampleKind::CellLine) {
+                let (x, y) = canvas.px(global(s.pos));
+                let (nx, ny) = (-s.tangent[1] as f32 * 6.0, s.tangent[0] as f32 * 6.0);
+                let mut tick = PathBuilder::new();
+                tick.move_to(x - nx, y - ny);
+                tick.line_to(x + nx, y + ny);
+                if let Some(t) = tick.finish() {
+                    canvas.pixmap.stroke_path(
+                        &t,
+                        &paint(0, 0, 0, 255),
+                        &stroke(1.5, false),
+                        Transform::identity(),
+                        Some(&mask),
+                    );
+                }
+            }
+        }
+        let arm_m = canvas.metres(8.0);
+        for j in &g.junctions {
+            let (x, y) = canvas.px(global(j.pos));
+            for arm in &j.arms {
+                let mut a = PathBuilder::new();
+                a.move_to(x, y);
+                a.line_to(x + arm.heading[0] as f32 * arm_m, y + arm.heading[1] as f32 * arm_m);
+                let Some(a) = a.finish() else { continue };
+                let (width, colour) =
+                    if arm.host { (7.0, rgb(palette::JUNCTION, 170)) } else { (3.0, rgb(palette::GUEST_ARM, 200)) };
+                canvas.pixmap.stroke_path(&a, &colour, &stroke(width, false), Transform::identity(), Some(&mask));
+            }
+            if let Some(dot) = PathBuilder::from_circle(x, y, 4.0) {
+                canvas.pixmap.fill_path(
+                    &dot,
+                    &rgb(palette::JUNCTION, 255),
+                    FillRule::Winding,
+                    Transform::identity(),
+                    Some(&mask),
+                );
+            }
+        }
+        for j in &g.joints {
+            let (x, y) = canvas.px(global(j.pos));
+            if let Some(dot) = PathBuilder::from_circle(x, y, 3.0) {
+                canvas.pixmap.fill_path(
+                    &dot,
+                    &rgb(palette::JOINT, 255),
+                    FillRule::Winding,
+                    Transform::identity(),
+                    Some(&mask),
+                );
+            }
+        }
+        for e in &g.ends {
+            let (x, y) = canvas.px(global(e.pos));
+            if let Some(ring) = PathBuilder::from_circle(x, y, 6.0) {
+                canvas.pixmap.stroke_path(
+                    &ring,
+                    &rgb(palette::END, 255),
+                    &stroke(2.0, false),
+                    Transform::identity(),
+                    Some(&mask),
+                );
+            }
+        }
+        for c in &g.crossings {
+            let (x, y) = canvas.px(global(c.pos));
+            let glyph = GLYPHS.iter().find(|(k, ..)| *k == c.kind).map(|g| g.2).unwrap_or([0; 7]);
+            let cell = 3.0;
+            if let Some(back) = Rect::from_xywh(x - 3.5 * cell, y - 4.5 * cell, 7.0 * cell, 9.0 * cell) {
+                canvas.pixmap.fill_rect(back, &rgb(palette::CROSSING, 230), Transform::identity(), Some(&mask));
+            }
+            for (row, bits) in glyph.iter().enumerate() {
+                for col in 0..5 {
+                    if bits >> (4 - col) & 1 == 1 {
+                        let px = x - 2.5 * cell + col as f32 * cell;
+                        let py = y - 3.5 * cell + row as f32 * cell;
+                        if let Some(r) = Rect::from_xywh(px, py, cell, cell) {
+                            canvas.pixmap.fill_rect(r, &paint(0, 0, 0, 255), Transform::identity(), Some(&mask));
+                        }
+                    }
+                }
+            }
+        }
+    }
+}
+
+/// The fixture's cells whose feature tiles it holds.
+pub fn fixture_cells(fixture: &Fixture, dir: &std::path::Path) -> Vec {
+    (fixture.cells().into_iter())
+        .filter(|k| k.feature_tiles().iter().all(|&(c, r)| feature_tile(dir, c, r).is_some()))
+        .collect()
+}
+
+/// The distance of q outside the convex hull of the points: 0 inside.
+fn outside_hull(points: &[[f64; 2]], q: [f64; 2]) -> f64 {
+    let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
+    let mut sorted = points.to_vec();
+    sorted.sort_by(|a, b| a[0].total_cmp(&b[0]).then(a[1].total_cmp(&b[1])));
+    let mut hull: Vec<[f64; 2]> = Vec::new();
+    for order in [sorted.clone(), sorted.iter().rev().copied().collect()] {
+        let start = hull.len();
+        for p in order {
+            while hull.len() >= start + 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {
+                hull.pop();
+            }
+            hull.push(p);
+        }
+        hull.pop();
+    }
+    let n = hull.len();
+    if n >= 3 && (0..n).all(|i| cross(hull[i], hull[(i + 1) % n], q) >= 0.0) {
+        return 0.0;
+    }
+    let distance = |a: [f64; 2], b: [f64; 2]| {
+        let (d, v) = ([b[0] - a[0], b[1] - a[1]], [q[0] - a[0], q[1] - a[1]]);
+        let length2 = d[0] * d[0] + d[1] * d[1];
+        let t = if length2 > 0.0 { ((v[0] * d[0] + v[1] * d[1]) / length2).clamp(0.0, 1.0) } else { 0.0 };
+        ((v[0] - t * d[0]) * (v[0] - t * d[0]) + (v[1] - t * d[1]) * (v[1] - t * d[1])).sqrt()
+    };
+    (0..n).map(|i| distance(hull[i], hull[(i + 1) % n])).fold(f64::INFINITY, f64::min)
+}
+
+/// Per water span that starts in its cell: how far, in metres, its curve leaves the convex hull of
+/// its chord and the chords before and after it; how far it runs past its chord's ends; and its
+/// largest distance from its chord over the chord's length.
+fn water_overshoot(g: &WayGraph) -> Vec<([f64; 3], GlobalPoint)> {
+    let mut out = Vec::new();
+    for way in g.ways.iter().filter(|w| w.family == Family::Water) {
+        let part = &g.parts[way.part as usize];
+        let v = &part.vertices;
+        let last = if way.to.u > 0.0 { way.to.span + 1 } else { way.to.span };
+        for k in way.from.span as usize..last as usize {
+            let p0 = v[k].pos;
+            if !g.cell.contains(GlobalPoint { x: p0[0], y: p0[1] }) {
+                continue;
+            }
+            let rel = |i: usize| [(v[i].pos[0] - p0[0]) as f64, (v[i].pos[1] - p0[1]) as f64];
+            let near: Vec<[f64; 2]> = (k.saturating_sub(1)..=(k + 2).min(v.len() - 1)).map(rel).collect();
+            let chord = rel(k + 1);
+            let c = (chord[0] * chord[0] + chord[1] * chord[1]).sqrt();
+            let unit = [chord[0] / c, chord[1] / c];
+            let mpu = metres_per_unit(p0[1]);
+            let mut worst = [0.0f64; 3];
+            for j in 0..=64 {
+                let q = obc_ground_plan::graph::point(part, k, j as f64 / 64.0).d;
+                let along = q[0] * unit[0] + q[1] * unit[1];
+                let side = (unit[0] * q[1] - unit[1] * q[0]).abs();
+                worst[0] = worst[0].max(outside_hull(&near, q) * mpu);
+                worst[1] = worst[1].max((-along).max(along - c).max(0.0) * mpu);
+                worst[2] = worst[2].max(side / c);
+            }
+            out.push((worst, GlobalPoint { x: p0[0], y: p0[1] }));
+        }
+    }
+    out
+}
+
+/// Every owned junction of the fixture by (host classes, guest class), the host rules, junction
+/// pairs closer than 2 m and 10 m, and the counters of `GraphStats` summed over the cells.
+pub fn census(graphs: &BTreeMap, sections: &Sections) -> Value {
+    let name = |g: &WayGraph, way: u32| {
+        let w = &g.ways[way as usize];
+        sections.rank_name(w.family == Family::Water, w.class as usize).to_string()
+    };
+    let mut kinds: BTreeMap<(String, String), u32> = BTreeMap::new();
+    let mut rules: BTreeMap = BTreeMap::new();
+    let (mut close_2, mut close_10, mut implicit, mut owned) = (0, 0, 0, 0);
+    let mut stats: BTreeMap = BTreeMap::new();
+    let mut crossings: BTreeMap = BTreeMap::new();
+    let mut owned_points = [0usize; 2];
+    let mut overshoot: Vec<([f64; 3], GlobalPoint)> = Vec::new();
+    for g in graphs.values() {
+        for j in g.junctions.iter().filter(|j| j.owned) {
+            owned += 1;
+            implicit += u32::from(j.implicit);
+            *rules.entry(format!("{:?}", j.host_rule)).or_default() += 1;
+            let mut hosts: Vec = j.arms.iter().filter(|a| a.host).map(|a| name(g, a.way)).collect();
+            hosts.sort();
+            for arm in j.arms.iter().filter(|a| !a.host) {
+                *kinds.entry((hosts.join("+"), name(g, arm.way))).or_default() += 1;
+            }
+        }
+        for (i, a) in g.junctions.iter().enumerate() {
+            for b in &g.junctions[i + 1..] {
+                let lower = if a.pos <= b.pos { a } else { b };
+                let (dx, dy) = ((a.pos[0] - b.pos[0]) as f64, (a.pos[1] - b.pos[1]) as f64);
+                let d = (dx * dx + dy * dy).sqrt() * metres_per_unit(g.cell.origin().y);
+                if lower.owned && d < 10.0 {
+                    close_10 += 1;
+                    close_2 += u32::from(d < 2.0);
+                }
+            }
+        }
+        for (key, value) in g.stats.counters() {
+            *stats.entry(key.to_string()).or_default() += u64::from(value);
+        }
+        for (&(kind, source), &n) in &g.stats.crossings {
+            *stats.entry(format!("crossings {kind:?} {source:?}")).or_default() += u64::from(n);
+        }
+        for c in g.crossings.iter().filter(|c| c.owned) {
+            *crossings.entry(format!("{:?} {:?}", c.kind, c.source)).or_default() += 1;
+        }
+        overshoot.extend(water_overshoot(g));
+        owned_points[0] += g.joints.iter().filter(|j| j.owned).count();
+        owned_points[1] += g.ends.iter().filter(|e| e.owned).count();
+    }
+    let worst_hull = overshoot.iter().max_by(|a, b| a.0[0].total_cmp(&b.0[0])).map(|o| crate::lon_lat(o.1));
+    let spread = |n: usize| {
+        let mut sorted: Vec = overshoot.iter().map(|o| o.0[n]).collect();
+        sorted.sort_by(f64::total_cmp);
+        let at = |q: f64| sorted.get(((sorted.len().max(1) - 1) as f64 * q) as usize).copied().unwrap_or(0.0);
+        json!({"max": at(1.0), "p99": at(0.99), "over_0_5_m": sorted.iter().filter(|&&d| d > 0.5).count()})
+    };
+    let mut rows: Vec<_> = kinds.into_iter().collect();
+    rows.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
+    json!({
+        "cells": graphs.len(),
+        "water_spans": overshoot.len(),
+        "water_outside_hull_worst_lon_lat": worst_hull,
+        "water_outside_hull_m": spread(0),
+        "water_past_ends_m": spread(1),
+        "water_bulge_per_chord": spread(2),
+        "owned_junctions": owned,
+        "owned_joints": owned_points[0],
+        "owned_ends": owned_points[1],
+        "owned_crossings": crossings,
+        "implicit_junctions": implicit,
+        "host_rules": rules,
+        "junction_pairs_under_2_m": close_2,
+        "junction_pairs_under_10_m": close_10,
+        "by_hosts_and_guest": rows.iter().map(|((h, g), n)| json!({"hosts": h, "guest": g, "count": n})).collect::>(),
+        "stats_summed_over_cells_each_its_work_area": stats,
+    })
+}
+
+/// The heap that a graph holds, in bytes.
+fn heap(g: &WayGraph) -> usize {
+    use obc_ground_plan::graph::{Arm, Crossing, Deck, End, Joint, Junction, Part, Sample, Span, Vertex, Way};
+    use std::mem::size_of;
+    let arms: usize = g.junctions.iter().map(|j| j.arms.capacity()).sum::() * size_of::();
+    let parts: usize = (g.parts.iter())
+        .map(|p| p.vertices.capacity() * size_of::() + p.spans.capacity() * size_of::())
+        .sum();
+    let decks: usize = g.decks.iter().map(|d| d.ways.capacity() * 4).sum();
+    arms + parts
+        + decks
+        + g.parts.capacity() * size_of::()
+        + g.ways.capacity() * size_of::()
+        + g.samples.capacity() * size_of::()
+        + g.junctions.capacity() * size_of::()
+        + g.joints.capacity() * size_of::()
+        + g.ends.capacity() * size_of::()
+        + g.crossings.capacity() * size_of::()
+        + g.decks.capacity() * size_of::()
+}
+
+/// The build time of stages 1 to 6 per fixture cell (the median of `runs`, and the first run, cold
+/// for that cell's data), and over the cells the median, p95 and max of both, with the samples,
+/// junctions, crossings and heap of each graph.
+pub fn bench(fixture: &mut Fixture, cells: &[CellKey], sections: &Sections, runs: usize) -> Value {
+    let mut rows = Vec::new();
+    let mut times = Vec::new();
+    let mut firsts = Vec::new();
+    let mut heaps = Vec::new();
+    for &key in cells {
+        let input = fixture.cell(key);
+        let mut ms: Vec = (0..runs)
+            .map(|_| {
+                let start = Instant::now();
+                std::hint::black_box(build(key, &input, sections));
+                start.elapsed().as_secs_f64() * 1e3
+            })
+            .collect();
+        firsts.push(ms[0]);
+        let first = ms[0];
+        ms.sort_by(f64::total_cmp);
+        let g = build(key, &input, sections);
+        let median = ms[ms.len() / 2];
+        times.push(median);
+        heaps.push(heap(&g));
+        rows.push(json!({
+            "cell": [key.x, key.y],
+            "ms": median,
+            "first_ms": first,
+            "samples": g.samples.len(),
+            "junctions": g.junctions.len(),
+            "crossings": g.crossings.len(),
+            "heap_bytes": heap(&g),
+        }));
+    }
+    let quantiles = |mut values: Vec| {
+        values.sort_by(f64::total_cmp);
+        let at = |q: f64| values[((values.len() - 1) as f64 * q).round() as usize];
+        json!({"median": at(0.5), "p95": at(0.95), "max": at(1.0)})
+    };
+    json!({
+        "cells": cells.len(),
+        "runs_per_cell": runs,
+        "ms": quantiles(times),
+        "first_ms": quantiles(firsts),
+        "heap_bytes_max": heaps.iter().max(),
+        "per_cell": rows,
+    })
+}
+
+/// The owned points and crossings of the graphs inside the picture, at their pixels, with the class,
+/// level, direction, host and room of each arm: what the picture shows, as text.
+pub fn points(canvas: &Canvas, graphs: &BTreeMap, sections: &Sections) -> Value {
+    let size = canvas.pixmap.width() as f32;
+    let mut out = Vec::new();
+    for g in graphs.values() {
+        let o = g.cell.origin();
+        let px = |p: [i32; 2]| canvas.px(GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) });
+        let seen = |(x, y): (f32, f32)| (0.0..size).contains(&x) && (0.0..size).contains(&y);
+        let arm = |a: &obc_ground_plan::graph::Arm| {
+            let w = &g.ways[a.way as usize];
+            let class = sections.rank_name(w.family == Family::Water, w.class as usize);
+            let link = w.link.map_or(String::new(), |l| format!(" {l:?}"));
+            format!("{class}{link} {:?} dir {} host {} room {:.1}", w.level, a.dir, a.host, a.room_m)
+        };
+        let at = |p: (f32, f32)| [p.0.round(), p.1.round()];
+        for j in g.junctions.iter().filter(|j| j.owned && seen(px(j.pos))) {
+            let arms: Vec = j.arms.iter().map(arm).collect();
+            out.push(json!({"junction": at(px(j.pos)), "rule": format!("{:?}", j.host_rule), "implicit": j.implicit, "arms": arms}));
+        }
+        for j in g.joints.iter().filter(|j| j.owned && seen(px(j.pos))) {
+            let arms: Vec = j.arms.iter().map(arm).collect();
+            out.push(
+                json!({"joint": at(px(j.pos)), "turn_deg": j.turn_rad.to_degrees(), "stroke": j.stroke, "arms": arms}),
+            );
+        }
+        for e in g.ends.iter().filter(|e| e.owned && seen(px(e.pos))) {
+            out.push(json!({"end": at(px(e.pos)), "arm": arm(&e.arm)}));
+        }
+        for c in g.crossings.iter().filter(|c| c.owned && seen(px(c.pos))) {
+            let kind = format!("{:?} {:?}", c.kind, c.source);
+            out.push(json!({"crossing": at(px(c.pos)), "kind": kind, "angle_deg": c.angle_rad.to_degrees()}));
+        }
+    }
+    Value::Array(out)
+}
diff --git a/host/obc-ground-plan/examples/debug/heights.rs b/host/obc-ground-plan/examples/debug/heights.rs
new file mode 100644
index 0000000000..c280f1d019
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/heights.rs
@@ -0,0 +1,561 @@
+//! `heights --fixture-steps --out DIR [--grid M] [--cells X,Y;...]`: the step scan of
+//! `faces::heights::check` over the fixture cells, with the cell borders, and the steps at label edges
+//! (`check::edge_steps`, on a grid of `EDGE_GRID_M`), and the slopes steeper than a rock face. Writes
+//! `fixture-steps.json`.
+//! `heights --cost DIR`: the cost of the heights per fixture cell on one thread (`cost.json`).
+//! `heights --gpu-check --out DIR --places A,B [--at NAME=LAT,LON]`: the blocks of the places' cells
+//! (`blocks.bin`) and Rust's heights at their paved and slope points (`points.json`) for
+//! `tests/browser/trailview/model-probe.mjs`, which compares the viewer's `heights.wgsl` with them, and
+//! `find`'s labels at whole-unit points (`labels.json`): the grid, every candidate edge's vertices, the
+//! points one unit beside them and the edges' whole midpoints, for its `model.wgsl` check.
+
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+use obc_ground_plan::faces::heights::check::{
+    border, edge_steps, scan, side_name, BorderKey, BorderValue, Class, Step, EDGE_GRID_M,
+};
+use obc_ground_plan::faces::records::{self, label};
+use obc_ground_plan::faces::Rules;
+use obc_ground_plan::frame::{CellKey, GlobalPoint};
+use obc_ground_plan::graph;
+use serde_json::{json, Value};
+
+use crate::fixture::{default_dir, Fixture};
+
+/// The sides, whether on a face edge, and the rule of a group of steps.
+type ClassKey = (String, String, bool, String);
+
+/// A vertex of the cost proxy: its point, label and terrain.
+type ProxyPoint = ([f64; 2], Option, f64);
+
+/// Border points every this many units along each cell line.
+const BORDER_STEP: i64 = 512;
+
+struct Cell {
+    key: CellKey,
+    points: u64,
+    steps: Vec<(Step, [String; 2], String)>,
+    border: Vec<(BorderKey, BorderValue)>,
+    ripple: [Vec; 2],
+    /// Grid points with a full cap, and with the host missing.
+    audit: [Vec; 2],
+    /// The steps at label edges with no rule, with their sides.
+    edges: Vec<(Step, [String; 2])>,
+    /// The slope pairs steeper than a rock face (`Scan::steep`): where, the climb per metre.
+    steep: Vec<(Value, f64)>,
+}
+
+fn round(v: f64, k: f64) -> f64 {
+    (v * k).round() / k
+}
+
+fn at_json(key: CellKey, q: [f64; 2]) -> Value {
+    let o = key.origin();
+    let (lon, lat) = crate::lon_lat(GlobalPoint { x: o.x + q[0] as i64, y: o.y + q[1] as i64 });
+    json!([round(lat, 1e7), round(lon, 1e7)])
+}
+
+/// A label as surface, height rule and owner kind, for a report.
+fn label_name(words: &[u32], id: Option) -> String {
+    id.map_or("terrain".into(), |id| {
+        let w = label(words, id)[0];
+        format!("surface {} rule {} owner {}", w & 0xff, w >> 24, (w >> 8) & 0xff)
+    })
+}
+
+pub fn run() -> Result<(), String> {
+    let (mut out, mut grid, mut only) = (None::, 0.5f64, None::>);
+    let (mut gpu, mut scan_all, mut names, mut at) = (false, false, Vec::new(), Vec::new());
+    let (mut size_m, mut px, mut sections) = (64.0, 1280u32, Vec::new());
+    let mut args = std::env::args().skip(2);
+    while let Some(arg) = args.next() {
+        let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value"));
+        match arg.as_str() {
+            "--fixture-steps" => scan_all = true,
+            "--size-m" => size_m = value()?.parse().map_err(|_| "--size-m: metres")?,
+            "--px" => px = value()?.parse().map_err(|_| "--px: a count")?,
+            "--sections" => {
+                sections = value()?
+                    .split(',')
+                    .map(|h| h.parse().map_err(|_| "--sections: headings"))
+                    .collect::>()?
+            }
+            "--gpu-check" => gpu = true,
+            "--cost" => {
+                let out = args.next().ok_or("--cost DIR")?;
+                return cost(std::path::Path::new(&out));
+            }
+            "--why-g" => {
+                for at in value()?.split(';') {
+                    let (x, y) = at.split_once(',').ok_or("--why-g X,Y;...")?;
+                    why_global([x.parse().map_err(|_| "--why-g: x")?, y.parse().map_err(|_| "--why-g: y")?])?;
+                }
+                return Ok(());
+            }
+            "--why" => {
+                for at in value()?.split(';') {
+                    let (lat, lon) = at.split_once(',').ok_or("--why LAT,LON;...")?;
+                    why(lat.parse().map_err(|_| "--why: a latitude")?, lon.parse().map_err(|_| "--why: a longitude")?)?;
+                }
+                return Ok(());
+            }
+            "--places" => names = value()?.split(',').map(String::from).collect(),
+            "--at" => {
+                let text = value()?;
+                let parse = || -> Option<(String, f64, f64)> {
+                    let (name, ll) = text.split_once('=')?;
+                    let (lat, lon) = ll.split_once(',')?;
+                    Some((name.to_string(), lat.parse().ok()?, lon.parse().ok()?))
+                };
+                at.push(parse().ok_or("--at NAME=LAT,LON")?);
+            }
+            "--out" => out = Some(value()?.into()),
+            "--grid" => grid = value()?.parse().map_err(|_| "--grid: metres")?,
+            "--cells" => {
+                let cells = value()?;
+                let parse = |c: &str| -> Option<(u32, u32)> {
+                    let (x, y) = c.split_once(',')?;
+                    Some((x.parse().ok()?, y.parse().ok()?))
+                };
+                only = Some(cells.split(';').map(|c| parse(c).ok_or("--cells X,Y;...")).collect::>()?);
+            }
+            _ => return Err(format!("heights: unknown option {arg}")),
+        }
+    }
+    let out =
+        out.ok_or("heights --out DIR (--fixture-steps | --gpu-check | --why LAT,LON | --places A,B --at N=LAT,LON)")?;
+    std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
+    if !scan_all {
+        let views = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+            .join("../../builder/web/tests/browser/trailview/road-views-top.json");
+        let mut places = crate::named_places(&views, &names)?;
+        places.extend(at);
+        return if gpu {
+            gpu_check(&out, &places)
+        } else {
+            crate::heights_view::run(&out, &places, size_m, px, §ions)
+        };
+    }
+    let dir = default_dir();
+    let mut fix = Fixture::open(&dir);
+    let mut cells = crate::graph::fixture_cells(&fix, &dir);
+    if let Some(only) = &only {
+        cells.retain(|k| only.contains(&(k.x, k.y)));
+    }
+    let rules = Rules::embedded();
+    let scans: Vec = fix.map(&cells, |key, input| {
+        let graph = graph::build(key, &input, &rules.sections);
+        let words = records::build(&graph, &input, rules, key, 0, true).near.words;
+        let s = scan(&words, &input.terrain, key, grid);
+        let steps = (s.steps.into_iter())
+            .map(|st| {
+                let mut sides = st.sides.map(|h| side_name(&words, &h));
+                sides.sort();
+                let lab = format!("{} | {}", label_name(&words, st.labels[0]), label_name(&words, st.labels[1]));
+                (st, sides, lab)
+            })
+            .collect();
+        let border = border(&words, &input.terrain, key, BORDER_STEP);
+        let missing = s
+            .host_missing
+            .iter()
+            .map(|(q, l)| json!({"at": at_json(key, *q), "label": label_name(&words, *l)}))
+            .collect();
+        let full = s.slots_full.iter().map(|q| at_json(key, *q)).collect();
+        let edges = (edge_steps(&words, &input.terrain, key, EDGE_GRID_M).into_iter())
+            .map(|st| {
+                let mut sides = st.sides.map(|h| side_name(&words, &h));
+                sides.sort();
+                (st, sides)
+            })
+            .collect();
+        let steep = s.steep.iter().map(|&(q, c)| (at_json(key, q), c)).collect();
+        Cell { key, points: s.points, steps, border, ripple: s.ripple, audit: [full, missing], edges, steep }
+    });
+    let mut by: BTreeMap = BTreeMap::new();
+    let mut by_rule: BTreeMap = BTreeMap::new();
+    let mut unnamed = Vec::new();
+    let mut inside_by: BTreeMap = BTreeMap::new();
+    let mut inside = Vec::new();
+    let (mut points, mut total, mut on_edges) = (0u64, 0u64, 0u64);
+    for c in &scans {
+        points += c.points;
+        for (st, sides, lab) in &c.steps {
+            total += 1;
+            let edge = st.class != Class::Inside;
+            on_edges += u64::from(edge);
+            let rule = match st.class {
+                Class::Named(r) => format!("{r:?}"),
+                c => format!("{c:?}"),
+            };
+            let r = by_rule.entry(rule.clone()).or_default();
+            (r.0, r.1) = (r.0 + 1, r.1.max(st.dh.abs()));
+            if st.class == Class::Unnamed {
+                let o = c.key.origin();
+                let g = [st.a, st.b].map(|q| [o.x as f64 + q[0], o.y as f64 + q[1]]);
+                unnamed.push(json!({"at": at_json(c.key, st.a), "dh": round(st.dh, 1e3), "sides": sides, "h": [st.sides[0].h, st.sides[1].h], "label": lab, "g": g}));
+            }
+            let e = by.entry((sides[0].clone(), sides[1].clone(), edge, rule)).or_insert((0, 0.0, Value::Null));
+            e.0 += 1;
+            if st.dh.abs() > e.1 {
+                (e.1, e.2) = (st.dh.abs(), at_json(c.key, st.a));
+            }
+            if !edge {
+                *inside_by.entry(lab.clone()).or_default() += 1;
+                inside.push(json!({"at": at_json(c.key, st.a), "dh": round(st.dh, 1e3), "label": lab, "cell": [c.key.x, c.key.y], "q": st.a}));
+            }
+        }
+    }
+    let classes: Vec = (by.iter())
+        .map(|((a, b, e, r), (n, m, at))| json!({"sides": [a, b], "edge": e, "rule": r, "count": n, "max_m": round(*m, 1e3), "worst_at": at}))
+        .collect();
+    let mut pairs: BTreeMap> = BTreeMap::new();
+    for c in &scans {
+        for (k, v) in &c.border {
+            pairs.entry(*k).or_default().push(v);
+        }
+    }
+    let (mut both, mut equal, mut t_equal, mut over, mut max_dh) = (0u64, 0u64, 0u64, 0u64, 0.0f64);
+    let (mut worst, mut differ) = (Vec::new(), Vec::new());
+    for (k, v) in pairs.iter().filter(|(_, v)| v.len() == 2) {
+        both += 1;
+        equal += u64::from(v[0].h == v[1].h);
+        if v[0].h != v[1].h {
+            let g = if k.0 == 0 { [k.1, k.2] } else { [k.2, k.1] };
+            let d = f64::from_bits(v[0].h) - f64::from_bits(v[1].h);
+            differ.push(json!({"g": g, "dh": d, "sides": [v[0].name, v[1].name]}));
+        }
+        t_equal += u64::from(v[0].t == v[1].t);
+        let d = (f64::from_bits(v[0].h) - f64::from_bits(v[1].h)).abs();
+        max_dh = max_dh.max(d);
+        if d > 0.005 {
+            over += 1;
+            let g = if k.0 == 0 { GlobalPoint { x: k.1, y: k.2 } } else { GlobalPoint { x: k.2, y: k.1 } };
+            let (lon, lat) = crate::lon_lat(g);
+            worst.push(
+                json!({"at": [round(lat, 1e7), round(lon, 1e7)], "dh": round(d, 1e4), "sides": [v[0].name, v[1].name]}),
+            );
+        }
+    }
+    let ripple: [Value; 2] = [0, 1].map(|a| {
+        let v: Vec = scans.iter().flat_map(|c| c.ripple[a].iter().copied()).filter(|x| !x.is_nan()).collect();
+        ripple_stats(v)
+    });
+    let audit = [0, 1].map(|k| scans.iter().map(|c| c.audit[k].len()).sum::());
+    // The steps at label edges: counts by class and size, and each one.
+    let mut edge_by: BTreeMap = BTreeMap::new();
+    let mut edge_list = Vec::new();
+    for c in &scans {
+        for (st, sides) in &c.edges {
+            let size = match st.dh.abs() {
+                d if d < 0.05 => "a: 1-5 cm",
+                d if d < 0.2 => "b: 5-20 cm",
+                d if d < 0.5 => "c: 20-50 cm",
+                _ => "d: over 50 cm",
+            };
+            for k in [format!("{:?}", st.class), format!("{:?} {size}", st.class)] {
+                let e = edge_by.entry(k).or_default();
+                (e.0, e.1) = (e.0 + 1, e.1.max(st.dh.abs()));
+            }
+            edge_list.push(json!({"at": at_json(c.key, st.a), "dh": round(st.dh, 1e3), "class": format!("{:?}", st.class), "sides": sides}));
+        }
+    }
+    let edges = json!({
+        "grid_m": EDGE_GRID_M,
+        "no_rule": edge_list.len(),
+        "by_class": edge_by.iter().map(|(k, (n, m))| (k.clone(), json!({"count": n, "max_m": round(*m, 1e3)}))).collect::>(),
+    });
+    // The slope pairs steeper than a rock face: counts over a climb per metre, and the steepest.
+    let mut steep: Vec<&(Value, f64)> = scans.iter().flat_map(|c| c.steep.iter()).collect();
+    steep.sort_by(|a, b| b.1.total_cmp(&a.1));
+    let past = |m: f64| steep.iter().filter(|s| s.1 > m).count();
+    let steep = json!({"count": steep.len(), "over_3": past(3.0), "over_6": past(6.0), "over_12": past(12.0),
+        "worst": steep.iter().take(10).map(|s| json!({"at": s.0, "per_m": round(s.1, 1e2)})).collect::>()});
+    let lists: [Value; 2] =
+        [0, 1].map(|k| Value::Array(scans.iter().flat_map(|c| c.audit[k].iter().cloned()).collect()));
+    let report = json!({
+        "slots_full": audit[0], "host_missing": audit[1],
+        "ripple_mm": {"along": ripple[0], "across": ripple[1]},
+        "cells": scans.len(), "grid_m": grid, "points": points,
+        "steps": total, "on_edges": on_edges, "inside": total - on_edges,
+        "inside_by_label": inside_by,
+        "by_rule": by_rule.iter().map(|(k, (n, m))| (k.clone(), json!({"count": n, "max_m": round(*m, 1e3)}))).collect::>(),
+        "border": {"points": both, "bit_equal": equal, "terrain_bit_equal": t_equal, "over_5mm": over, "max_dh_m": max_dh, "worst": worst},
+        "edges": edges,
+        "steep": steep,
+        "classes": classes,
+    });
+    let write = |name: &str, v: &Value| {
+        std::fs::write(out.join(name), serde_json::to_string_pretty(v).unwrap()).map_err(|e| e.to_string())
+    };
+    write("fixture-steps.json", &report)?;
+    write("inside.json", &Value::Array(inside))?;
+    write("unnamed.json", &Value::Array(unnamed))?;
+    write("slots-full.json", &lists[0])?;
+    write("border-differ.json", &Value::Array(differ))?;
+    write("host-missing.json", &lists[1])?;
+    write("edge-steps.json", &Value::Array(edge_list))?;
+    println!(
+        "{}",
+        serde_json::to_string_pretty(&json!({"slots_full": audit[0], "host_missing": audit[1], "ripple_mm": report["ripple_mm"], "steps": total, "on_edges": on_edges, "inside": total - on_edges, "by_rule": report["by_rule"], "inside_by_label": report["inside_by_label"], "border": {"points": both, "bit_equal": equal, "terrain_bit_equal": t_equal, "over_5mm": over, "max_dh_m": max_dh}, "edges": report["edges"], "steep": report["steep"]})).unwrap()
+    );
+    Ok(())
+}
+
+/// Points per side of a place's square for the GPU check, and the square's side.
+const GPU_SIDE: usize = 160;
+const GPU_SIZE_M: f64 = 60.0;
+
+fn gpu_check(out: &std::path::Path, places: &[(String, f64, f64)]) -> Result<(), String> {
+    let dir = default_dir();
+    let mut fix = Fixture::open(&dir);
+    let rules = Rules::embedded();
+    let mut blocks: Vec = Vec::new();
+    let mut at: BTreeMap = BTreeMap::new();
+    let mut points = Vec::new();
+    let mut labels = Vec::new();
+    for (name, lat, lon) in places {
+        let centre = obc_ground_plan::frame::from_lon_lat(*lon, *lat);
+        let upm = 1.0 / obc_ground_plan::frame::metres_per_unit(centre.y);
+        let mut n = [0u32; 3];
+        for j in 0..GPU_SIDE {
+            for i in 0..GPU_SIDE {
+                let off = |k: usize| (k as f64 / (GPU_SIDE - 1) as f64 - 0.5) * GPU_SIZE_M * upm;
+                let g = [centre.x as f64 + off(i) + 0.37, centre.y as f64 + off(j) + 0.21];
+                let key = CellKey::of(GlobalPoint { x: g[0].floor() as i64, y: g[1].floor() as i64 });
+                if let std::collections::btree_map::Entry::Vacant(e) = at.entry(key) {
+                    let Ok(input) = fix.try_cell(key) else { continue };
+                    let graph = graph::build(key, &input, &rules.sections);
+                    let words = records::build(&graph, &input, rules, key, 0, true).near.words;
+                    e.insert((blocks.len(), input));
+                    blocks.extend(words);
+                }
+                let (offset, input) = &at[&key];
+                let o = key.origin();
+                let q = [g[0] - o.x as f64, g[1] - o.y as f64];
+                let words = &blocks[*offset..];
+                let whole = [q[0].round(), q[1].round()];
+                labels.push(json!([offset, whole[0], whole[1], records::find(words, whole).unwrap_or(u32::MAX)]));
+                let Some((h, label)) = obc_ground_plan::faces::heights::check::at(words, &input.terrain, key, q) else {
+                    continue;
+                };
+                let t = obc_ground_plan::faces::heights::check::terrain_at(&input.terrain, key, q).unwrap_or(0.0);
+                let kind = h.kind as u32;
+                n[kind as usize] += 1;
+                if kind > 0 {
+                    points.push(json!([offset, q[0], q[1], label.unwrap_or(u32::MAX), t, h.h, kind, name]));
+                }
+            }
+        }
+        println!("{name}: terrain {} slope {} paved {}", n[0], n[1], n[2]);
+    }
+    // On and beside the candidates' edges in the places' cells.
+    for (offset, _) in at.values() {
+        let words = &blocks[*offset..];
+        for v in edge_points(words) {
+            let q = [f64::from(v[0]), f64::from(v[1])];
+            if (0.0..=f64::from(1 << 18)).contains(&q[0]) && (0.0..=f64::from(1 << 18)).contains(&q[1]) {
+                labels.push(json!([offset, q[0], q[1], records::find(words, q).unwrap_or(u32::MAX)]));
+            }
+        }
+    }
+    let bytes: Vec = blocks.iter().flat_map(|w| w.to_le_bytes()).collect();
+    std::fs::write(out.join("blocks.bin"), bytes).map_err(|e| e.to_string())?;
+    std::fs::write(out.join("points.json"), serde_json::to_string(&points).unwrap()).map_err(|e| e.to_string())?;
+    std::fs::write(out.join("labels.json"), serde_json::to_string(&labels).unwrap()).map_err(|e| e.to_string())?;
+    println!("{} label points", labels.len());
+    println!("{} points in {} cells", points.len(), at.len());
+    Ok(())
+}
+
+/// The vertices of every candidate edge that a block's bins list, the points one unit beside each and the
+/// edges' whole midpoints, each once.
+fn edge_points(words: &[u32]) -> std::collections::BTreeSet<[i32; 2]> {
+    let mut out = std::collections::BTreeSet::new();
+    for b in 0..(records::BINS * records::BINS) as usize {
+        let head = words[9] as usize + records::HEADER * b;
+        let mut at = words[head] as usize;
+        if at == 0 {
+            continue;
+        }
+        for _ in 0..words[head + 1] >> 16 {
+            let runs = words[at + 1];
+            at += 2;
+            for _ in 0..runs {
+                let n = words[at] as usize;
+                let v = |k: usize| [words[at + 1 + 2 * k] as i32, words[at + 2 + 2 * k] as i32];
+                for k in 0..n {
+                    let p = v(k);
+                    out.extend([p, [p[0] + 1, p[1]], [p[0], p[1] + 1], [p[0] - 1, p[1] - 1]]);
+                    if k + 1 < n && (p[0] + v(k + 1)[0]) % 2 == 0 && (p[1] + v(k + 1)[1]) % 2 == 0 {
+                        out.insert([(p[0] + v(k + 1)[0]) / 2, (p[1] + v(k + 1)[1]) / 2]);
+                    }
+                }
+                at += 1 + 2 * n;
+            }
+        }
+    }
+    out
+}
+
+/// The records and both sides' causes at a point and at the points 2 units about it along x and y.
+fn why(lat: f64, lon: f64) -> Result<(), String> {
+    use obc_ground_plan::faces::heights::check::{explain, terrain_at};
+    use obc_ground_plan::faces::records::find;
+    let g = obc_ground_plan::frame::from_lon_lat(lon, lat);
+    let key = CellKey::of(g);
+    let mut fix = Fixture::open(&default_dir());
+    let input = fix.try_cell(key).map_err(|e| format!("{key:?}: {e:?}"))?;
+    let rules = Rules::embedded();
+    let graph = graph::build(key, &input, &rules.sections);
+    let words = records::build(&graph, &input, rules, key, 0, true).near.words;
+    let o = key.origin();
+    let q = [(g.x - o.x) as f64, (g.y - o.y) as f64];
+    println!("{lat},{lon}: cell {key:?}");
+    // The nearest face edge along x or y within 32 units: explained at its first point.
+    let edge = (1..=32).flat_map(|k| [[k, 0], [0, k]]).find_map(|[dx, dy]| {
+        let (a, b) = ([q[0] - f64::from(dx), q[1] - f64::from(dy)], [q[0] + f64::from(dx), q[1] + f64::from(dy)]);
+        let labels = [find(&words, a), find(&words, b)];
+        (labels[0] != labels[1]).then_some((a, labels))
+    });
+    let (a, labels) = edge.unwrap_or((q, [find(&words, q); 2]));
+    println!("{} | {}", label_name(&words, labels[0]), label_name(&words, labels[1]));
+    print!("{}", explain(&words, a, labels, terrain_at(&input.terrain, key, a).unwrap_or(f64::NAN)));
+    Ok(())
+}
+
+/// Quantiles of second differences, in mm.
+pub fn ripple_stats(v: Vec) -> Value {
+    let mut v: Vec = v.into_iter().map(|x| x.abs() * 1000.0).collect();
+    if v.is_empty() {
+        return Value::Null;
+    }
+    v.sort_by(f64::total_cmp);
+    let q = |f: f64| round(v[((v.len() - 1) as f64 * f).round() as usize], 100.0);
+    json!({"n": v.len(), "p50": q(0.5), "p95": q(0.95), "p99": q(0.99), "max": q(1.0)})
+}
+
+/// The records at a global frame point in every cell whose closed square holds it, with the label of
+/// each cell there.
+fn why_global(g: [f64; 2]) -> Result<(), String> {
+    use obc_ground_plan::faces::heights::check::{explain, terrain_at};
+    use obc_ground_plan::faces::records::find;
+    use obc_ground_plan::frame::CELL_UNITS;
+    let mut fix = Fixture::open(&default_dir());
+    let rules = Rules::embedded();
+    let base = CellKey::of(GlobalPoint { x: g[0].floor() as i64, y: g[1].floor() as i64 });
+    for key in [base, CellKey { x: base.x - 1, ..base }, CellKey { y: base.y - 1, ..base }] {
+        let o = key.origin();
+        let q = [g[0] - o.x as f64, g[1] - o.y as f64];
+        if !(0.0..=CELL_UNITS as f64).contains(&q[0]) || !(0.0..=CELL_UNITS as f64).contains(&q[1]) {
+            continue;
+        }
+        let Ok(input) = fix.try_cell(key) else { continue };
+        let graph = graph::build(key, &input, &rules.sections);
+        let words = records::build(&graph, &input, rules, key, 0, true).near.words;
+        let l = find(&words, q);
+        println!("cell {key:?} q {q:?} label {}", label_name(&words, l));
+        print!("{}", explain(&words, q, [l, l], terrain_at(&input.terrain, key, q).unwrap_or(f64::NAN)));
+    }
+    Ok(())
+}
+
+/// The vertex proxy of the near mesh: a grid on paved labels and a coarser one (level 18) on slope
+/// labels, and every vertex of the cell's faces that are no terrain, which takes both sides.
+const PAVED_GRID_M: f64 = 0.8;
+const SLOPE_GRID_M: f64 = 1.63;
+/// The least time of this many passes.
+const COST_RUNS: usize = 2;
+
+/// The cost of the heights per fixture cell on one thread: labels and terrain first, then the
+/// heights alone over the vertex proxy, the least of `COST_RUNS` passes.
+fn cost(out: &std::path::Path) -> Result<(), String> {
+    use obc_ground_plan::faces::heights::check::terrain_at;
+    use obc_ground_plan::faces::heights::{height_at, height_at_sides};
+    use obc_ground_plan::faces::records::find;
+    use obc_ground_plan::frame::{metres_per_unit, CELL_UNITS};
+    use std::time::Instant;
+    std::fs::create_dir_all(out).map_err(|e| e.to_string())?;
+    let dir = default_dir();
+    let mut fix = Fixture::open(&dir);
+    let cells = crate::graph::fixture_cells(&fix, &dir);
+    let rules = Rules::embedded();
+    let mut rows = Vec::new();
+    for key in cells {
+        let input = fix.cell(key);
+        let graph = graph::build(key, &input, &rules.sections);
+        let words = records::build(&graph, &input, rules, key, 0, true).near.words;
+        let plan = obc_ground_plan::faces::build(&graph, &input, rules, key, 0, true);
+        let mpu = metres_per_unit(key.origin().y + CELL_UNITS / 2);
+        let mut grid: [Vec; 2] = [Vec::new(), Vec::new()];
+        for (k, step_m) in [(0, PAVED_GRID_M), (1, SLOPE_GRID_M)] {
+            let step = step_m / mpu;
+            let n = (CELL_UNITS as f64 / step) as usize;
+            for j in 0..n {
+                for i in 0..n {
+                    let q = [(i as f64 + 0.5) * step, (j as f64 + 0.5) * step];
+                    let l = find(&words, q);
+                    let rule = l.map_or(0, |id| label(&words, id)[0] >> 24);
+                    let Some(t) = terrain_at(&input.terrain, key, q) else { continue };
+                    if (k == 0 && rule >= 2) || (k == 1 && rule == 1) {
+                        grid[k].push((q, l, t));
+                    }
+                }
+            }
+        }
+        let mut sides: Vec<([f64; 2], [Option; 2], f64)> = Vec::new();
+        for f in plan.faces.iter().filter(|f| f.surface != obc_ground_plan::faces::Surface::Terrain) {
+            for ring in &f.rings {
+                for &v in ring {
+                    let p = plan.vertices[v as usize];
+                    let q = [f64::from(p[0]) / 2.0, f64::from(p[1]) / 2.0];
+                    if !(0.0..CELL_UNITS as f64).contains(&q[0]) || !(0.0..CELL_UNITS as f64).contains(&q[1]) {
+                        continue;
+                    }
+                    let Some(t) = terrain_at(&input.terrain, key, q) else { continue };
+                    sides.push((q, [find(&words, q), find(&words, [q[0] + 0.5, q[1] + 0.5])], t));
+                }
+            }
+        }
+        let best = |f: &dyn Fn() -> f64| {
+            (0..COST_RUNS)
+                .map(|_| {
+                    let t0 = Instant::now();
+                    std::hint::black_box(f());
+                    t0.elapsed().as_secs_f64() * 1e3
+                })
+                .fold(f64::INFINITY, f64::min)
+        };
+        let ms: [f64; 2] =
+            [0, 1].map(|k| best(&|| grid[k].iter().map(|&(q, l, t)| height_at(&words, q, l, t).h).sum()));
+        let ms_sides = best(&|| sides.iter().map(|&(q, l, t)| height_at_sides(&words, q, l, t)[0].h).sum());
+        let ms_two = best(&|| {
+            sides.iter().map(|&(q, l, t)| height_at(&words, q, l[0], t).h + height_at(&words, q, l[1], t).h).sum()
+        });
+        let ns = |ms: f64, n: usize| if n == 0 { 0.0 } else { ms * 1e6 / n as f64 };
+        rows.push(json!({"cell": [key.x, key.y], "ms": ms[0] + ms[1] + ms_sides, "paved": [grid[0].len(), ns(ms[0], grid[0].len())],
+            "slope": [grid[1].len(), ns(ms[1], grid[1].len())], "vertices": [sides.len(), ns(ms_sides, sides.len()), ns(ms_two, sides.len())]}));
+    }
+    let q = |f: &dyn Fn(&Value) -> f64| {
+        let mut v: Vec = rows.iter().map(f).filter(|x| *x > 0.0).collect();
+        v.sort_by(f64::total_cmp);
+        let at = |p: f64| round(v[((v.len() - 1) as f64 * p).round() as usize], 1000.0);
+        json!({"median": at(0.5), "p95": at(0.95), "max": at(1.0)})
+    };
+    let load = std::fs::read_to_string("/proc/loadavg").unwrap_or_default();
+    let report = json!({
+        "cells": rows.len(), "load": load.trim(),
+        "cell_ms": q(&|r| r["ms"].as_f64().unwrap()),
+        "ns_paved": q(&|r| r["paved"][1].as_f64().unwrap()),
+        "ns_slope": q(&|r| r["slope"][1].as_f64().unwrap()),
+        "ns_sides": q(&|r| r["vertices"][1].as_f64().unwrap()),
+        "sides_vs_two_calls": q(&|r| r["vertices"][1].as_f64().unwrap() / r["vertices"][2].as_f64().unwrap().max(1e-9)),
+        "rows": rows,
+    });
+    std::fs::write(out.join("cost.json"), serde_json::to_string_pretty(&report).unwrap()).map_err(|e| e.to_string())?;
+    let mut summary = report.clone();
+    summary.as_object_mut().unwrap().remove("rows");
+    println!("{}", serde_json::to_string_pretty(&summary).unwrap());
+    Ok(())
+}
diff --git a/host/obc-ground-plan/examples/debug/heights_view.rs b/host/obc-ground-plan/examples/debug/heights_view.rs
new file mode 100644
index 0000000000..627f310f9e
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/heights_view.rs
@@ -0,0 +1,359 @@
+//! `heights --out DIR (--places A,B | --at NAME=LAT,LON) [--size-m M] [--px N] [--sections H,...]`: per
+//! place, a hillshade with contours every 0.1 m, the face edges and the steps by class
+//! (`NAME-steps.png`), the ripple of the carriageways (`NAME-ripple.png`), cross-sections along
+//! headings through the place (`NAME-section-H.png`) and `heights-view.json` with the counts.
+
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use obc_ground_plan::faces::heights::check::{at, ripple, terrain_at, Class, STEP_M};
+use obc_ground_plan::faces::heights::{height_at_sides, Height, Kind, Step};
+use obc_ground_plan::faces::records::{self, label};
+use obc_ground_plan::faces::Rules;
+use obc_ground_plan::frame::{from_lon_lat, metres_per_unit, CellKey, GlobalPoint};
+use obc_ground_plan::graph;
+use obc_ground_plan::CellInput;
+use serde_json::{json, Value};
+
+use crate::fixture::{default_dir, Fixture};
+use crate::heights::ripple_stats;
+
+const THREADS: usize = 4;
+
+struct Place {
+    cells: BTreeMap, CellInput)>,
+}
+
+/// A point of a place: its height, its label in its cell and its cell.
+#[derive(Clone, Copy)]
+struct Sample {
+    h: Height,
+    label: Option,
+    cell: CellKey,
+    t: f64,
+}
+
+impl Place {
+    fn new(fix: &mut Fixture, lat: f64, lon: f64, size_m: f64) -> Place {
+        let rules = Rules::embedded();
+        let mut cells = BTreeMap::new();
+        for key in crate::square_cells(lat, lon, size_m + 2.0) {
+            let Ok(input) = fix.try_cell(key) else { continue };
+            let graph = graph::build(key, &input, &rules.sections);
+            cells.insert(key, (records::build(&graph, &input, rules, key, 0, true).near.words, input));
+        }
+        Place { cells }
+    }
+
+    fn local(&self, g: [f64; 2]) -> Option<(CellKey, [f64; 2])> {
+        let key = CellKey::of(GlobalPoint { x: g[0].floor() as i64, y: g[1].floor() as i64 });
+        let o = key.origin();
+        self.cells.contains_key(&key).then_some((key, [g[0] - o.x as f64, g[1] - o.y as f64]))
+    }
+
+    fn at(&self, g: [f64; 2]) -> Option {
+        let (cell, q) = self.local(g)?;
+        let (words, input) = &self.cells[&cell];
+        let (h, label) = at(words, &input.terrain, cell, q)?;
+        Some(Sample { h, label, cell, t: terrain_at(&input.terrain, cell, q)? })
+    }
+
+    /// The class of the jump from a to b, found down to one frame unit, or None for no step.
+    fn step(&self, a: [f64; 2], b: [f64; 2], sa: Sample, sb: Sample) -> Option {
+        let (mut a, mut b, mut va, mut vb) = (a, b, sa, sb);
+        loop {
+            let d = (vb.h.h - va.h.h).abs();
+            if d <= STEP_M {
+                return None;
+            }
+            if libm::hypot(b[0] - a[0], b[1] - a[1]) <= 1.0 {
+                break;
+            }
+            let m = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
+            let vm = self.at(m)?;
+            let (d1, d2) = ((vm.h.h - va.h.h).abs(), (vb.h.h - vm.h.h).abs());
+            if d1.max(d2) < 0.75 * d {
+                return None;
+            }
+            if d1 >= d2 {
+                (b, vb) = (m, vm);
+            } else {
+                (a, va) = (m, vm);
+            }
+        }
+        if va.label == vb.label && va.cell == vb.cell && sa.label == sb.label {
+            return Some(Class::Inside);
+        }
+        let (cell, q) = self.local(a)?;
+        let words = &self.cells[&cell].0;
+        let apart = |id: Option| {
+            id.is_some_and(|id| {
+                let l = label(words, id);
+                (l[0] >> 8) & 0xff == 3 || (l[0] >> 24 >= 2 && l[2] == u32::MAX)
+            })
+        };
+        if va.cell != vb.cell {
+            return Some(Class::Unnamed);
+        }
+        let sides = height_at_sides(words, q, [va.label, vb.label], va.t);
+        let same = ((sides[1].h - sides[0].h) - (vb.h.h - va.h.h)).abs() <= STEP_M;
+        Some(if same && sides[0].step != Step::None {
+            Class::Named(sides[0].step)
+        } else if apart(va.label) || apart(vb.label) {
+            Class::Apart
+        } else {
+            Class::Unnamed
+        })
+    }
+}
+
+fn par_map T + Sync>(n: usize, f: F) -> Vec {
+    let chunk = n.div_ceil(THREADS);
+    std::thread::scope(|s| {
+        let handles: Vec<_> = (0..THREADS)
+            .map(|k| {
+                let f = &f;
+                s.spawn(move || (k * chunk..((k + 1) * chunk).min(n)).map(f).collect::>())
+            })
+            .collect();
+        handles.into_iter().flat_map(|h| h.join().unwrap()).collect()
+    })
+}
+
+fn save(path: &Path, w: u32, h: u32, rgb: Vec) -> Result<(), String> {
+    image::RgbImage::from_raw(w, h, rgb).ok_or("image size")?.save(path).map_err(|e| format!("{}: {e}", path.display()))
+}
+
+fn base_colour(words: &[u32], s: &Sample) -> [f64; 3] {
+    let w = s.label.map_or(0, |id| label(words, id)[0]);
+    let junction = (w >> 8) & 0xff == 2;
+    match (w & 0xff, s.h.kind) {
+        (0, _) => [0.80, 0.84, 0.74],
+        (1, _) => [0.86, 0.80, 0.62],
+        (2, _) if junction => [0.62, 0.55, 0.70],
+        (2 | 6, _) => [0.55, 0.55, 0.58],
+        (3, _) => [0.72, 0.70, 0.66],
+        (4, _) => [0.70, 0.80, 0.58],
+        (7, _) => [0.55, 0.45, 0.38],
+        (_, Kind::Paved) => [0.6, 0.6, 0.6],
+        _ => [0.9, 0.6, 0.3],
+    }
+}
+
+fn class_colour(c: Class) -> [u8; 3] {
+    match c {
+        Class::Inside => [255, 0, 0],
+        Class::Unnamed => [255, 140, 0],
+        Class::Apart => [170, 70, 210],
+        Class::Named(_) => [0, 110, 255],
+    }
+}
+
+pub fn run(out: &Path, places: &[(String, f64, f64)], size_m: f64, px: u32, sections: &[f64]) -> Result<(), String> {
+    let mut fix = Fixture::open(&default_dir());
+    let mut report = Vec::new();
+    for (name, lat, lon) in places {
+        let r = picture(&mut fix, out, name, *lat, *lon, size_m, px, sections)?;
+        println!("{r}");
+        report.push(r);
+    }
+    std::fs::write(out.join("heights-view.json"), serde_json::to_string_pretty(&report).unwrap())
+        .map_err(|e| e.to_string())
+}
+
+#[allow(clippy::too_many_arguments)]
+fn picture(
+    fix: &mut Fixture,
+    out: &Path,
+    name: &str,
+    lat: f64,
+    lon: f64,
+    size_m: f64,
+    px: u32,
+    sections: &[f64],
+) -> Result {
+    let place = Place::new(fix, lat, lon, size_m);
+    let centre = from_lon_lat(lon, lat);
+    let mpu = metres_per_unit(centre.y);
+    let (n, pm) = (px as usize, size_m / f64::from(px));
+    let corner = [centre.x as f64 - size_m / 2.0 / mpu, centre.y as f64 - size_m / 2.0 / mpu];
+    let g = |i: usize, j: usize| [corner[0] + (i as f64 + 0.5) * pm / mpu, corner[1] + (j as f64 + 0.5) * pm / mpu];
+    let samples: Vec> = par_map(n * n, |k| place.at(g(k % n, k / n)));
+    let words_of = |s: &Sample| &place.cells[&s.cell].0;
+    // Steps between neighbours, by class.
+    let steps: Vec> = par_map(n * n, |k| {
+        let (i, j) = (k % n, k / n);
+        let mut v = Vec::new();
+        for nb in [(i + 1 < n).then_some(k + 1), (j + 1 < n).then_some(k + n)].into_iter().flatten() {
+            if let (Some(a), Some(b)) = (samples[k], samples[nb]) {
+                if let Some(c) = place.step(g(i, j), g(nb % n, nb / n), a, b) {
+                    v.push(c);
+                }
+            }
+        }
+        v
+    });
+    let mut counts: BTreeMap = BTreeMap::new();
+    for c in steps.iter().flatten() {
+        *counts.entry(format!("{c:?}")).or_default() += 1;
+    }
+    // Hillshade from the north-west, contours every 0.1 m (dark every 1 m), face edges black.
+    let h = |k: usize| samples[k].map(|s| s.h.h);
+    let mut rgb = vec![0u8; n * n * 3];
+    for k in 0..n * n {
+        let (i, j) = (k % n, k / n);
+        let Some(s) = samples[k] else {
+            rgb[3 * k..3 * k + 3].copy_from_slice(&[255, 0, 255]);
+            continue;
+        };
+        let e =
+            h(if i + 1 < n { k + 1 } else { k }).unwrap_or(s.h.h) - h(if i > 0 { k - 1 } else { k }).unwrap_or(s.h.h);
+        let so =
+            h(if j + 1 < n { k + n } else { k }).unwrap_or(s.h.h) - h(if j > 0 { k - n } else { k }).unwrap_or(s.h.h);
+        let nrm = [-e / (2.0 * pm), so / (2.0 * pm), 1.0];
+        let l = [-0.5, 0.5, std::f64::consts::FRAC_1_SQRT_2];
+        let len = (nrm[0] * nrm[0] + nrm[1] * nrm[1] + nrm[2] * nrm[2]).sqrt();
+        let shade = ((nrm[0] * l[0] + nrm[1] * l[1] + nrm[2] * l[2]) / len).clamp(0.0, 1.0);
+        let mut col = base_colour(words_of(&s), &s).map(|v| v * (0.35 + 0.75 * shade));
+        let band = |v: f64, step: f64| (v / step).floor();
+        let mut line = 0;
+        for nb in [(i + 1 < n).then_some(k + 1), (j + 1 < n).then_some(k + n)].into_iter().flatten() {
+            let Some(o) = samples[nb] else { continue };
+            if o.label != s.label || o.cell != s.cell {
+                line = 3;
+            } else if band(o.h.h, 1.0) != band(s.h.h, 1.0) {
+                line = line.max(2);
+            } else if band(o.h.h, 0.1) != band(s.h.h, 0.1) {
+                line = line.max(1);
+            }
+        }
+        col = match line {
+            1 => col.map(|v| v * 0.72),
+            2 => col.map(|v| v * 0.4),
+            3 => [0.0; 3],
+            _ => col,
+        };
+        for (c, v) in col.iter().enumerate() {
+            rgb[3 * k + c] = (v.clamp(0.0, 1.0) * 255.0) as u8;
+        }
+        if let Some(c) = steps[k].iter().max_by_key(|c| match c {
+            Class::Inside => 3,
+            Class::Unnamed => 2,
+            Class::Apart => 0,
+            Class::Named(_) => 1,
+        }) {
+            rgb[3 * k..3 * k + 3].copy_from_slice(&class_colour(*c));
+        }
+    }
+    save(&out.join(format!("{name}-steps.png")), px, px, rgb)?;
+    // The ripple of the carriageways: grey paved, green slope; yellow from 0.5 mm, red at 5 mm.
+    let ripples: Vec> = par_map(n * n, |k| {
+        let s = samples[k]?;
+        let (cell, q) = place.local(g(k % n, k / n))?;
+        let (words, input) = &place.cells[&cell];
+        ripple(words, &input.terrain, cell, q, (s.h, s.label))
+    });
+    let mut rgb = Vec::with_capacity(n * n * 3);
+    for (s, r) in samples.iter().zip(&ripples) {
+        let base: [f64; 3] = match s.map(|s| s.h.kind) {
+            Some(Kind::Paved) => [150.0, 150.0, 155.0],
+            Some(Kind::Slope) => [140.0, 170.0, 110.0],
+            Some(Kind::Terrain) => [90.0, 110.0, 80.0],
+            None => [40.0, 40.0, 40.0],
+        };
+        let d = r.map_or(0.0, |r| r[0].abs().max(r[1].abs()) * 1000.0);
+        let d = if d.is_nan() { 0.0 } else { d };
+        let t = ((d - 0.5) / 4.5).clamp(0.0, 1.0);
+        let c = if d < 0.5 { base } else { [255.0, 255.0 * (1.0 - t), 0.0] };
+        rgb.extend(c.map(|v| v as u8));
+    }
+    save(&out.join(format!("{name}-ripple.png")), px, px, rgb)?;
+    // The ripple's statistics on its own grid.
+    let rn = (size_m / 0.25) as usize;
+    let grid: Vec> = par_map(rn * rn, |k| {
+        let gp = [corner[0] + (k % rn) as f64 * 0.25 / mpu, corner[1] + (k / rn) as f64 * 0.25 / mpu];
+        let (cell, q) = place.local(gp)?;
+        let (words, input) = &place.cells[&cell];
+        let (h, l) = at(words, &input.terrain, cell, q)?;
+        ripple(words, &input.terrain, cell, q, (h, l))
+    });
+    let stats = [0, 1].map(|a| ripple_stats(grid.iter().flatten().map(|r| r[a]).filter(|x| !x.is_nan()).collect()));
+    // Sections along headings through the place's centre.
+    for &hd in sections {
+        let (sn, cs) = (libm::sin(hd.to_radians()), libm::cos(hd.to_radians()));
+        let half = size_m * 0.45;
+        let m = 1600usize;
+        let pts: Vec<(f64, Option)> = (0..m)
+            .map(|k| {
+                let f = k as f64 / (m - 1) as f64;
+                let off = [(-sn + 2.0 * f * sn) * half, (cs - 2.0 * f * cs) * half];
+                (f * 2.0 * half, place.at([centre.x as f64 + off[0] / mpu, centre.y as f64 + off[1] / mpu]))
+            })
+            .collect();
+        section_png(&out.join(format!("{name}-section-{:03}.png", hd as i32)), &pts, 2.0 * half)?;
+    }
+    Ok(
+        json!({"name": name, "lat": lat, "lon": lon, "px_m": pm, "steps": counts, "ripple_mm": {"along": stats[0], "across": stats[1]}}),
+    )
+}
+
+/// A cross-section: the height (dark: paved, brown: slope, green: terrain) and the plain terrain
+/// (light green) along a line, true scale where it fits.
+fn section_png(path: &Path, pts: &[(f64, Option)], len_m: f64) -> Result<(), String> {
+    let (w, h) = (1600u32, 560u32);
+    let mut rgb = vec![255u8; (w * h * 3) as usize];
+    let hs: Vec = pts
+        .iter()
+        .filter_map(|(_, s)| s.map(|s| s.h.h))
+        .chain(pts.iter().filter_map(|(_, s)| s.map(|s| s.t)))
+        .collect();
+    if hs.is_empty() {
+        return Ok(());
+    }
+    let lo = hs.iter().copied().fold(f64::INFINITY, f64::min);
+    let hi = hs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
+    let scale_x = f64::from(w) / len_m;
+    let scale_y = (f64::from(h - 60) / (hi - lo).max(0.5)).min(scale_x * 4.0);
+    let y_of = |z: f64| f64::from(h - 40) - (z - lo) * scale_y;
+    let mut put = |x: i64, y: i64, c: [u8; 3]| {
+        if x >= 0 && y >= 0 && x < i64::from(w) && y < i64::from(h) {
+            let k = ((y as u32 * w + x as u32) * 3) as usize;
+            rgb[k..k + 3].copy_from_slice(&c);
+        }
+    };
+    let mut z = lo.floor();
+    while z <= hi {
+        for x in 0..i64::from(w) {
+            put(x, y_of(z) as i64, [225, 225, 225]);
+        }
+        z += 1.0;
+    }
+    let mut prev: [Option<(i64, i64)>; 2] = [None, None];
+    for (along, s) in pts {
+        let x = (along * scale_x) as i64;
+        let Some(s) = s else {
+            prev = [None, None];
+            continue;
+        };
+        let col = match s.h.kind {
+            Kind::Terrain => [60, 140, 60],
+            Kind::Slope => [190, 140, 40],
+            Kind::Paved => [40, 40, 40],
+        };
+        for (k, (v, c)) in [(s.t, [120, 200, 120]), (s.h.h, col)].into_iter().enumerate() {
+            let y = y_of(v) as i64;
+            if let Some((px0, py0)) = prev[k] {
+                for yv in py0.min(y)..=py0.max(y) {
+                    put(px0, yv, c);
+                }
+            }
+            put(x, y, c);
+            put(x, y + 1, c);
+            prev[k] = Some((x, y));
+        }
+        for yv in (i64::from(h) - 30)..(i64::from(h) - 20) {
+            put(x, yv, col);
+        }
+    }
+    save(path, w, h, rgb)
+}
diff --git a/host/obc-ground-plan/examples/debug/main.rs b/host/obc-ground-plan/examples/debug/main.rs
new file mode 100644
index 0000000000..b260811979
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/main.rs
@@ -0,0 +1,504 @@
+//! The debug tool of the ground plan: top-down pictures, stats, a glTF height field and probe points
+//! of the cells about a list of places of the TrailView fixture.
+
+#[path = "../../tests/fixture/mod.rs"]
+mod fixture;
+
+mod draw;
+mod faces;
+mod gltf;
+mod graph;
+mod heights;
+mod heights_view;
+mod mesh;
+mod model;
+mod requests;
+mod storeys;
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+use core::f64::consts::PI;
+
+use obc_ground_plan::frame::{from_lon_lat, metres_per_unit, CellKey, GlobalPoint, FRAME_BITS};
+use obc_ground_plan::sections::{leading_number, Sections, HALF_MAX_M};
+use obc_ground_plan::terrain::Terrain;
+use obc_ground_plan::tile::{features, Geometry};
+use obc_ground_plan::CellInput;
+use serde_json::{json, Value};
+
+use draw::Canvas;
+
+const SQUARE: f64 = (1u64 << FRAME_BITS) as f64;
+/// A probe point lies on a level-18 grid vertex: 64 world units.
+const PROBE_GRID: i64 = 64 * 16;
+/// The snap of a stamp past a way's slopes, and the clearance of a probe point from an area.
+const SNAP_M: f64 = 2.0;
+const AREA_CLEAR_M: f64 = 5.0;
+/// The kinds that carry a carriageway, and the waterways.
+pub const WAYS: [&str; 6] = ["main-road", "road", "path", "railway", "tunnel", "gallery"];
+pub const WATERS: [&str; 2] = ["river", "stream"];
+
+struct Options {
+    places: Option>,
+    views: PathBuf,
+    at: Vec<(String, f64, f64)>,
+    fixture: PathBuf,
+    out: PathBuf,
+    size_m: f64,
+    px: u32,
+    layers: Vec,
+    gltf: bool,
+    probe: usize,
+    census: bool,
+    bench: bool,
+    faces_bench: bool,
+    runs: usize,
+    storeys: bool,
+    oblique: (f64, f64),
+}
+
+fn options() -> Result {
+    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+    let mut o = Options {
+        places: None,
+        views: root.join("builder/web/tests/browser/trailview/road-views-top.json"),
+        at: Vec::new(),
+        fixture: fixture::default_dir(),
+        out: root.join(".artifacts/ground-plan/debug"),
+        size_m: 128.0,
+        px: 1600,
+        layers: ["terrain", "inputs", "cells"].map(String::from).to_vec(),
+        gltf: false,
+        probe: 0,
+        census: false,
+        bench: false,
+        faces_bench: false,
+        runs: 1,
+        storeys: false,
+        oblique: (30.0, 35.0),
+    };
+    let mut args = std::env::args().skip(1);
+    while let Some(arg) = args.next() {
+        let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value"));
+        match arg.as_str() {
+            "--places" => o.places = Some(value()?.split(',').map(String::from).collect()),
+            "--views" => o.views = value()?.into(),
+            "--at" => {
+                let text = value()?;
+                let (name, at) = text.split_once('=').ok_or("--at NAME=LAT,LON")?;
+                let (lat, lon) = at.split_once(',').ok_or("--at NAME=LAT,LON")?;
+                o.at.push((
+                    name.into(),
+                    lat.parse().map_err(|_| "--at: a latitude")?,
+                    lon.parse().map_err(|_| "--at: a longitude")?,
+                ));
+            }
+            "--fixture" => o.fixture = value()?.into(),
+            "--out" => o.out = value()?.into(),
+            "--size-m" => o.size_m = value()?.parse().map_err(|_| "--size-m: a number")?,
+            "--px" => o.px = value()?.parse().map_err(|_| "--px: a number")?,
+            "--layers" => o.layers = value()?.split(',').map(String::from).collect(),
+            "--gltf" => o.gltf = true,
+            "--census" => o.census = true,
+            "--bench" => o.bench = true,
+            "--faces-bench" => o.faces_bench = true,
+            "--storeys" => o.storeys = true,
+            "--oblique" => {
+                let text = value()?;
+                let (h, p) = text.split_once(',').ok_or("--oblique HEADING,PITCH")?;
+                o.oblique =
+                    (h.parse().map_err(|_| "--oblique: a heading")?, p.parse().map_err(|_| "--oblique: a pitch")?);
+            }
+            "--runs" => o.runs = value()?.parse().map_err(|_| "--runs: a count")?,
+            "--probe" => o.probe = value()?.parse().map_err(|_| "--probe: a count")?,
+            _ => return Err(format!("unknown option {arg}")),
+        }
+    }
+    if let Some(layer) =
+        o.layers.iter().find(|l| !["terrain", "inputs", "cells", "graph", "faces", "levels"].contains(&l.as_str()))
+    {
+        return Err(format!("unknown layer {layer}: the layers are terrain, inputs, cells, graph, faces, levels"));
+    }
+    Ok(o)
+}
+
+/// The places: each `-top` view of the views file by its name without `-top`, at the `lat` and `lon`
+/// of its query, and those of `--at`.
+fn places(o: &Options) -> Result, String> {
+    let mut chosen = named_places(&o.views, o.places.as_deref().unwrap_or_default())?;
+    chosen.extend(o.at.iter().cloned());
+    if chosen.is_empty() {
+        return Err("no place: give --places or --at".into());
+    }
+    Ok(chosen)
+}
+
+/// The places of `wanted`, from the `-top` views of the views file.
+pub fn named_places(views: &Path, wanted: &[String]) -> Result, String> {
+    let mut all = Vec::new();
+    if !wanted.is_empty() {
+        let text = std::fs::read_to_string(views).map_err(|e| format!("{}: {e}", views.display()))?;
+        let views: Value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", views.display()))?;
+        for view in views.as_array().into_iter().flatten() {
+            let (Some(name), Some(query)) = (view["name"].as_str(), view["view"].as_str()) else { continue };
+            let Some(name) = name.strip_suffix("-top") else { continue };
+            let field = |key: &str| {
+                query
+                    .trim_start_matches('?')
+                    .split('&')
+                    .find_map(|pair| pair.strip_prefix(key)?.strip_prefix('='))?
+                    .parse()
+                    .ok()
+            };
+            if let (Some(lat), Some(lon)) = (field("lat"), field("lon")) {
+                all.push((name.to_string(), lat, lon));
+            }
+        }
+    }
+    let mut chosen = Vec::new();
+    for wanted in wanted {
+        let found: Vec<_> =
+            all.iter().filter(|(n, ..)| n == wanted || n.starts_with(&format!("{wanted}-"))).cloned().collect();
+        if found.is_empty() {
+            let names: Vec<&str> = all.iter().map(|(n, ..)| n.as_str()).collect();
+            return Err(format!("no place {wanted}: the places are {}", names.join(", ")));
+        }
+        chosen.extend(found);
+    }
+    Ok(chosen)
+}
+
+/// The cells of the square of `size_m` about a place.
+pub fn square_cells(lat: f64, lon: f64, size_m: f64) -> Vec {
+    let centre = from_lon_lat(lon, lat);
+    let half = size_m / 2.0 / metres_per_unit(centre.y);
+    let corner = |x: f64, y: f64| CellKey::of(GlobalPoint { x: x as i64, y: y as i64 });
+    let (a, b) = (
+        corner(centre.x as f64 - half, centre.y as f64 - half),
+        corner(centre.x as f64 + half, centre.y as f64 + half),
+    );
+    (a.y..=b.y).flat_map(|y| (a.x..=b.x).map(move |x| CellKey { x, y })).collect()
+}
+
+/// Longitude and latitude of a frame point, for the probe file.
+pub fn lon_lat(p: GlobalPoint) -> (f64, f64) {
+    let lat = libm::atan(libm::sinh(PI * (1.0 - 2.0 * p.y as f64 / SQUARE)));
+    (p.x as f64 / SQUARE * 360.0 - 180.0, lat.to_degrees())
+}
+
+fn main() {
+    let result = match std::env::args().nth(1).as_deref() {
+        Some("requests") => requests::run(),
+        Some("model") => model::run(),
+        Some("heights") => heights::run(),
+        Some("mesh") => mesh::run(),
+        _ => run(),
+    };
+    if let Err(e) = result {
+        eprintln!("debug: {e}");
+        std::process::exit(1);
+    }
+}
+
+fn run() -> Result<(), String> {
+    let args: Vec = std::env::args().collect();
+    if args.len() == 3 && args[1] == "--sheet" {
+        return sheet(&args[2]);
+    }
+    let o = options()?;
+    std::fs::create_dir_all(&o.out).map_err(|e| format!("{}: {e}", o.out.display()))?;
+    let mut fix = fixture::Fixture::open(&o.fixture);
+    let sections = Sections::embedded();
+    if o.census || o.bench || o.faces_bench {
+        let cells = graph::fixture_cells(&fix, &o.fixture);
+        let rules = obc_ground_plan::faces::Rules::embedded();
+        if o.faces_bench {
+            let path = o.out.join("faces-bench.json");
+            let bench = faces::bench(&mut fix, &cells, rules, o.runs);
+            write(&path, serde_json::to_string_pretty(&bench).unwrap().as_bytes())?;
+            println!("faces bench of {} cells -> {}", cells.len(), path.display());
+        }
+        if o.census {
+            let structures = &obc_ground_plan::faces::Rules::embedded().structures;
+            let mut levels = serde_json::Map::new();
+            let mut graphs: BTreeMap = BTreeMap::new();
+            for &k in &cells {
+                let input = fix.cell(k);
+                let g = obc_ground_plan::graph::build(k, &input, sections);
+                let mut lv = g.clone();
+                obc_ground_plan::graph::levels(&mut lv, &input, sections, structures);
+                levels.insert(format!("{}/{}", k.x, k.y), fixture::levels_detail(&lv, &input.terrain));
+                graphs.insert(k, g);
+            }
+            let path = o.out.join("junctions.json");
+            write(&path, serde_json::to_string_pretty(&graph::census(&graphs, sections)).unwrap().as_bytes())?;
+            write(&o.out.join("levels.json"), serde_json::to_string(&levels).unwrap().as_bytes())?;
+            println!("census of {} cells -> {}", cells.len(), path.display());
+        }
+        if o.bench {
+            let path = o.out.join("graph-bench.json");
+            let bench = graph::bench(&mut fix, &cells, sections, 5);
+            write(&path, serde_json::to_string_pretty(&bench).unwrap().as_bytes())?;
+            println!(
+                "bench of {} cells: {}, first {} -> {}",
+                cells.len(),
+                bench["ms"],
+                bench["first_ms"],
+                path.display()
+            );
+        }
+        if o.places.is_none() && o.at.is_empty() {
+            return Ok(());
+        }
+    }
+    let places = places(&o)?;
+    for (name, lat, lon) in places {
+        let centre = from_lon_lat(lon, lat);
+        let mpu = metres_per_unit(centre.y);
+        let half = o.size_m / 2.0 / mpu;
+        let square = [centre.x as f64 - half, centre.y as f64 - half, centre.x as f64 + half, centre.y as f64 + half];
+        let keys = square_cells(lat, lon, o.size_m);
+        let mut tiles = BTreeSet::new();
+        let mut cells = BTreeMap::new();
+        let mut terrain_ms = serde_json::Map::new();
+        for &key in &keys {
+            tiles.extend(key.feature_tiles());
+            let pages = fix.pages(&Terrain::wanted(key));
+            let start = Instant::now();
+            drop(Terrain::new(key, pages));
+            terrain_ms.insert(format!("{}/{}", key.x, key.y), json!(start.elapsed().as_secs_f64() * 1e3));
+            let cell = fix.try_cell(key).map_err(|e| format!("{name}: a tile of cell {}/{}: {e}", key.x, key.y))?;
+            cells.insert(key, cell);
+        }
+        // The decode of each tile read, once more for its time; and the counts of its features.
+        let mut decode_ms = serde_json::Map::new();
+        let mut counts: BTreeMap = BTreeMap::new();
+        let mut aligned = 0;
+        for &(column, row) in &tiles {
+            let Some(bytes) = fix.tile(column, row) else { continue };
+            let start = Instant::now();
+            let decoded = features(&bytes, column, row).map_err(|e| format!("{name}: tile 13/{column}/{row}: {e}"))?;
+            decode_ms.insert(format!("13/{column}/{row}"), json!(start.elapsed().as_secs_f64() * 1e3));
+            for f in &decoded {
+                let count = counts.entry(format!("{} {:?}", f.kind, f.geometry)).or_default();
+                count[0] += 1;
+                count[1] += f.parts.len();
+                count[2] += f.parts.iter().map(|p| p.points.len()).sum::();
+                aligned += f.parts.iter().filter(|p| p.plan.is_some()).count();
+            }
+        }
+        let mut canvas = Canvas::new(o.px, square[0], square[1], 2.0 * half / f64::from(o.px), mpu);
+        let heights = draw::heights(&canvas, &cells);
+        if o.layers.iter().any(|l| l == "terrain") {
+            draw::terrain(&mut canvas, &heights.values);
+        }
+        if o.layers.iter().any(|l| l == "inputs") {
+            draw::inputs(&mut canvas, &cells, sections);
+        }
+        if o.layers.iter().any(|l| l == "cells") {
+            draw::cells(&mut canvas, &keys, centre);
+        }
+        // Under the graph, so that the centre lines show over the faces.
+        let mut corners = Value::Null;
+        if o.layers.iter().any(|l| l == "faces") {
+            let rules = obc_ground_plan::faces::Rules::embedded();
+            let plans = faces::plans(&cells, rules);
+            faces::layer(&mut canvas, &plans, &cells, rules);
+            corners = faces::corners(&canvas, &plans);
+        }
+        // Over the cells' marks, so that a crossing's letter at the centre shows.
+        let mut points = Value::Null;
+        if o.layers.iter().any(|l| l == "graph" || l == "levels") {
+            let structures = &obc_ground_plan::faces::Rules::embedded().structures;
+            let graphs: BTreeMap = (cells.iter())
+                .map(|(&k, input)| {
+                    let mut g = obc_ground_plan::graph::build(k, input, sections);
+                    obc_ground_plan::graph::levels(&mut g, input, sections, structures);
+                    (k, g)
+                })
+                .collect();
+            if o.layers.iter().any(|l| l == "levels") {
+                graph::levels(&mut canvas, &graphs);
+            }
+            if o.layers.iter().any(|l| l == "graph") {
+                graph::layer(&mut canvas, &graphs);
+                points = graph::points(&canvas, &graphs, sections);
+            }
+        }
+        let png = o.out.join(format!("{name}.png"));
+        // The background is opaque, so the premultiplied pixels are the straight ones.
+        let (w, h) = (canvas.pixmap.width(), canvas.pixmap.height());
+        image::save_buffer(&png, canvas.pixmap.data(), w, h, image::ColorType::Rgba8)
+            .map_err(|e| format!("{}: {e}", png.display()))?;
+        let capped: BTreeSet = (cells.values().flat_map(|c| &c.features))
+            .filter(|f| {
+                f.geometry == Geometry::Line && (WAYS.contains(&f.kind.as_str()) || WATERS.contains(&f.kind.as_str()))
+            })
+            .filter(|f| f.tags.get("width").and_then(|w| leading_number(w)).is_some_and(|w| w / 2.0 > HALF_MAX_M))
+            .map(|f| format!("{} {:?}", f.kind, f.tags))
+            .collect();
+        let stats = json!({
+            "place": name,
+            "lat": lat,
+            "lon": lon,
+            "size_m": o.size_m,
+            "cells": keys.iter().map(|k| [k.x, k.y]).collect::>(),
+            "tiles": tiles.iter().map(|&(c, r)| [c, r]).collect::>(),
+            "counts": counts.iter().map(|(k, [f, p, v])| (k.clone(), json!({"features": f, "parts": p, "vertices": v}))).collect::>(),
+            "aligned_parts": aligned,
+            "unknown_px": heights.unknown,
+            "height_range_m": heights.range,
+            "capped_widths": capped,
+            "times": {"decode_ms": decode_ms, "terrain_build_ms": terrain_ms, "height_ns": heights.ns},
+            "graph": points,
+            "corners": corners,
+        });
+        write(&o.out.join(format!("{name}.json")), serde_json::to_string_pretty(&stats).unwrap().as_bytes())?;
+        if o.gltf {
+            let mesh = gltf::terrain(&cells, centre, o.size_m);
+            write(&o.out.join(format!("{name}.glb")), &gltf::glb(&[mesh]))?;
+        }
+        if o.storeys {
+            let rules = obc_ground_plan::faces::Rules::embedded();
+            let built = storeys::cells(&mut fix, &keys, rules)?;
+            let mut top = Canvas::new(o.px, square[0], square[1], 2.0 * half / f64::from(o.px), mpu);
+            draw::terrain(&mut top, &heights.values);
+            storeys::top(&mut top, &built);
+            if o.layers.iter().any(|l| l == "inputs") {
+                draw::inputs(&mut top, &cells, sections);
+            }
+            draw::cells(&mut top, &keys, centre);
+            let path = o.out.join(format!("{name}-storeys.png"));
+            storeys::save(&top.pixmap, &path)?;
+            storeys::oblique(&o.out.join(format!("{name}-oblique.png")), &built, &cells, centre, o.size_m, o.oblique)?;
+            let stats = storeys::stats(&built, square);
+            write(
+                &o.out.join(format!("{name}-storeys.json")),
+                serde_json::to_string_pretty(&stats).unwrap().as_bytes(),
+            )?;
+            if o.gltf {
+                write(
+                    &o.out.join(format!("{name}-storeys.glb")),
+                    &gltf::glb(&storeys::gltf_meshes(&built, &cells, centre, o.size_m)),
+                )?;
+            }
+            println!("{name}: storeys {}", serde_json::to_string(&stats["in_square"]).unwrap());
+        }
+        if o.probe > 0 {
+            let (points, free) = probe(&cells, sections, square, o.probe);
+            let json = json!({"place": name, "wanted": o.probe, "free": free, "points": points});
+            write(&o.out.join(format!("{name}.probe.json")), serde_json::to_string_pretty(&json).unwrap().as_bytes())?;
+        }
+        println!(
+            "{name}: {} cells, {} tiles, {} px unknown -> {}",
+            keys.len(),
+            tiles.len(),
+            heights.unknown,
+            png.display()
+        );
+    }
+    Ok(())
+}
+
+fn write(path: &Path, bytes: &[u8]) -> Result<(), String> {
+    std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// Distance in frame units from p to the segment a–b.
+fn distance(p: GlobalPoint, a: GlobalPoint, b: GlobalPoint) -> f64 {
+    let (dx, dy) = ((b.x - a.x) as f64, (b.y - a.y) as f64);
+    let (px, py) = ((p.x - a.x) as f64, (p.y - a.y) as f64);
+    let length = dx * dx + dy * dy;
+    let t = if length > 0.0 { ((px * dx + py * dy) / length).clamp(0.0, 1.0) } else { 0.0 };
+    let (ex, ey) = (px - t * dx, py - t * dy);
+    (ex * ex + ey * ey).sqrt()
+}
+
+/// Up to `count` points [lon, lat, height] on level-18 grid vertices of the square, free of every
+/// stamp: past each way's or water's half-width, shoulder or sidewalk, reach and the snap, and
+/// `AREA_CLEAR_M` outside every area. Evenly picked from the free ones, row by row; and the count of
+/// the free ones.
+fn probe(
+    cells: &BTreeMap,
+    sections: &Sections,
+    square: [f64; 4],
+    count: usize,
+) -> (Vec<[f64; 3]>, usize) {
+    let grid = |v: f64| (v / PROBE_GRID as f64).ceil() as i64 * PROBE_GRID;
+    let mut free = Vec::new();
+    let mut y = grid(square[1]);
+    while (y as f64) < square[3] {
+        let mut x = grid(square[0]);
+        while (x as f64) < square[2] {
+            let p = GlobalPoint { x, y };
+            let cell = &cells[&CellKey::of(p)];
+            let mpu = metres_per_unit(y);
+            if let Some(h) = cell.terrain.height(p).filter(|_| clear(cell, sections, p, mpu)) {
+                free.push((p, h));
+            }
+            x += PROBE_GRID;
+        }
+        y += PROBE_GRID;
+    }
+    let picked = count.min(free.len());
+    let points = (0..picked)
+        .map(|k| {
+            let (p, h) = free[k * free.len() / picked];
+            let (lon, lat) = lon_lat(p);
+            [lon, lat, h]
+        })
+        .collect();
+    (points, free.len())
+}
+
+fn clear(cell: &CellInput, sections: &Sections, p: GlobalPoint, mpu: f64) -> bool {
+    for f in &cell.features {
+        let reach_m = match (f.geometry, f.kind.as_str()) {
+            (Geometry::Line, kind) if WAYS.contains(&kind) => {
+                let s = sections.way(kind, &f.tags, false);
+                s.half_m + s.shoulder_m.max(s.sidewalk_m) + s.reach_m + SNAP_M
+            }
+            (Geometry::Line, kind) if WATERS.contains(&kind) => {
+                let s = sections.water(kind, &f.tags);
+                s.half_m + s.reach_m + SNAP_M
+            }
+            (Geometry::Line, _) => AREA_CLEAR_M,
+            (Geometry::Area, _) => AREA_CLEAR_M,
+            (Geometry::Point, _) => continue,
+        };
+        let reach = reach_m / mpu;
+        // An area's copy from the tile that owns the point: the joins of the other copies' cuts are not its edges.
+        for part in f.parts.iter().filter(|part| f.geometry != Geometry::Area || draw::holds(part.tile, p)) {
+            let n = part.points.len();
+            let edges = if f.geometry == Geometry::Area { n } else { n.saturating_sub(1) };
+            if (0..edges).any(|i| distance(p, part.points[i], part.points[(i + 1) % n]) < reach) {
+                return false;
+            }
+        }
+        if f.geometry == Geometry::Area && draw::inside(f, p) {
+            return false;
+        }
+    }
+    true
+}
+
+/// `--sheet COLUMNS,out.png,a.png,b.png,...`: the pictures in rows of COLUMNS, with white gaps.
+fn sheet(names: &str) -> Result<(), String> {
+    let names: Vec<&str> = names.split(',').collect();
+    let (Some(cols), Some(out)) = (names.first().and_then(|c| c.parse::().ok()), names.get(1)) else {
+        return Err("--sheet COLUMNS,out.png,a.png,...".into());
+    };
+    let open = |n: &&str| image::open(n).map(|i| i.to_rgba8()).map_err(|e| format!("{n}: {e}"));
+    let pics = names[2..].iter().map(open).collect::, _>>()?;
+    let (w, h) =
+        (pics.iter().map(|p| p.width()).max().unwrap_or(0), pics.iter().map(|p| p.height()).max().unwrap_or(0));
+    let (cols, rows) = (cols.max(1) as u32, pics.len().div_ceil(cols.max(1)) as u32);
+    let mut img = image::RgbaImage::from_pixel(cols * (w + 12) - 12, rows * (h + 12) - 12, image::Rgba([255; 4]));
+    for (k, p) in pics.iter().enumerate() {
+        let (c, r) = (k as u32 % cols, k as u32 / cols);
+        image::imageops::overlay(&mut img, p, i64::from(c * (w + 12)), i64::from(r * (h + 12)));
+    }
+    img.save(out).map_err(|e| format!("{out}: {e}"))
+}
diff --git a/host/obc-ground-plan/examples/debug/mesh.rs b/host/obc-ground-plan/examples/debug/mesh.rs
new file mode 100644
index 0000000000..7c42ce6a02
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/mesh.rs
@@ -0,0 +1,367 @@
+//! `debug mesh`: the near mesh over fixture cells on one thread, with each stage's time, the counts,
+//! the jump of each view, the checks and wireframes.
+//!
+//! `debug mesh [--cells all | --places NAME,... [--size-m M]] [--out DIR] [--check]`
+
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+use std::time::Instant;
+
+use obc_ground_plan::faces::{records, FacePlan};
+use obc_ground_plan::frame::{from_lon_lat, metres_per_unit, CellKey, GlobalPoint, CELL_UNITS};
+use obc_ground_plan::mesh::{self, check, CellMesh, Reads, Rim, NO_LABEL, STAGES};
+use obc_ground_plan::terrain::Terrain;
+use serde_json::{json, Value};
+
+use crate::draw::{self, Canvas};
+use crate::fixture::{default_dir, Fixture};
+
+/// The view radius of the jump: the mesh range.
+const JUMP_M: f64 = 600.0;
+/// Develop's road triangles per view (median, max) and road job (ms, median).
+const DEVELOP: &str = "develop: 156k / 409k road triangles per view, road job 72-84 ms median";
+
+struct Cell {
+    plan: FacePlan,
+    words: Vec,
+    terrain: Terrain,
+    rim: Rim,
+    /// Input, graph, faces and records, rim (ms).
+    times: [f64; 4],
+}
+
+fn quantiles(mut v: Vec) -> Value {
+    if v.is_empty() {
+        return Value::Null;
+    }
+    v.sort_by(f64::total_cmp);
+    let q = |p: f64| v[((v.len() - 1) as f64 * p).round() as usize];
+    json!({"median": q(0.5), "p95": q(0.95), "max": q(1.0), "sum": v.iter().sum::(), "n": v.len()})
+}
+
+/// The fill of a label's surface: grey carriageway, light grey shoulder, tan slope, green terrain.
+fn colour(words: &[u32], l: u32) -> (u8, u8, u8) {
+    if l == NO_LABEL {
+        return (190, 215, 170);
+    }
+    match records::label(words, l)[0] & 0xff {
+        1 => (222, 200, 150),
+        2 => (150, 150, 150),
+        3 => (185, 185, 175),
+        4 => (170, 200, 140),
+        5 => (150, 160, 200),
+        6 => (110, 110, 140),
+        7 => (150, 120, 90),
+        8 => (190, 160, 160),
+        _ => (214, 226, 200),
+    }
+}
+
+/// The triangles about a place: filled by the label of their first corner, the strip blue, edges
+/// dark; the step slots' pieces orange; the terrain vertices as red dots.
+fn picture(
+    png: &std::path::Path,
+    centre: GlobalPoint,
+    size_m: f64,
+    meshes: &[(CellKey, CellMesh)],
+    cells: &BTreeMap,
+) -> Result<(), String> {
+    let mpu = metres_per_unit(centre.y);
+    let half = size_m / 2.0 / mpu;
+    let mut canvas = Canvas::new(1600, centre.x as f64 - half, centre.y as f64 - half, 2.0 * half / 1600.0, mpu);
+    let edge = draw::paint(40, 40, 40, 200);
+    let thin = draw::stroke(0.6, false);
+    let near = |g: &[GlobalPoint]| {
+        g.iter().any(|q| (q.x - centre.x).abs() as f64 <= half && (q.y - centre.y).abs() as f64 <= half)
+    };
+    for (key, m) in meshes {
+        let words = &cells[key].words;
+        let o = key.origin();
+        let at = |k: u32| {
+            let p = m.corner(k as usize).0;
+            GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) }
+        };
+        let first_strip = m.triangles.len() - m.strip_triangles as usize;
+        for (k, t) in m.triangles.iter().enumerate() {
+            let g = t.map(at);
+            if !near(&g) {
+                continue;
+            }
+            let (r, gr, b) = if k >= first_strip { (160, 190, 225) } else { colour(words, m.corner(t[0] as usize).1) };
+            let Some(path) = draw::path(&canvas, &g, true) else { continue };
+            canvas.pixmap.fill_path(
+                &path,
+                &draw::paint(r, gr, b, 255),
+                tiny_skia::FillRule::Winding,
+                tiny_skia::Transform::identity(),
+                None,
+            );
+            canvas.pixmap.stroke_path(&path, &edge, &thin, tiny_skia::Transform::identity(), None);
+        }
+        let step = draw::stroke(2.0, false);
+        for s in &m.steps {
+            let g = [at(s[0]), at(s[1])];
+            if let Some(path) = draw::path(&canvas, &g, false).filter(|_| near(&g)) {
+                canvas.pixmap.stroke_path(
+                    &path,
+                    &draw::paint(240, 130, 20, 255),
+                    &step,
+                    tiny_skia::Transform::identity(),
+                    None,
+                );
+            }
+        }
+        for k in 0..m.corners.len() {
+            let (p, _, terrain) = m.corner(k);
+            let g = GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) };
+            if terrain && near(&[g]) {
+                let (x, y) = canvas.px(g);
+                if let Some(dot) = tiny_skia::PathBuilder::from_circle(x, y, 2.5) {
+                    canvas.pixmap.fill_path(
+                        &dot,
+                        &draw::paint(200, 40, 40, 255),
+                        tiny_skia::FillRule::Winding,
+                        tiny_skia::Transform::identity(),
+                        None,
+                    );
+                }
+            }
+        }
+    }
+    let (w, h) = (canvas.pixmap.width(), canvas.pixmap.height());
+    image::save_buffer(png, canvas.pixmap.data(), w, h, image::ColorType::Rgba8)
+        .map_err(|e| format!("{}: {e}", png.display()))
+}
+
+/// The bytes of a mesh on the GPU: corners, triangles, step slots and sunk bits.
+fn bytes(m: &CellMesh) -> usize {
+    m.to_bytes().len()
+}
+
+pub fn run() -> Result<(), String> {
+    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+    let mut args = std::env::args().skip(2);
+    let (mut all, mut places, mut size_m, mut out, mut checks) =
+        (false, Vec::new(), 64.0, root.join(".artifacts/ground-plan/mesh"), false);
+    while let Some(arg) = args.next() {
+        let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value"));
+        match arg.as_str() {
+            "--cells" => all = value()? == "all",
+            "--places" => places = value()?.split(',').map(String::from).collect(),
+            "--size-m" => size_m = value()?.parse().map_err(|_| "--size-m: a number")?,
+            "--out" => out = PathBuf::from(value()?),
+            "--check" => checks = true,
+            _ => return Err(format!("unknown option {arg}")),
+        }
+    }
+    std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
+    let dir = default_dir();
+    let mut fixture = Fixture::open(&dir);
+    let known = crate::graph::fixture_cells(&fixture, &dir);
+    let wanted: Vec = if all {
+        known.clone()
+    } else {
+        let views = root.join("builder/web/tests/browser/trailview/road-views-top.json");
+        let chosen = crate::named_places(&views, &places)?;
+        let mut keys: Vec =
+            chosen.iter().flat_map(|(_, lat, lon)| crate::square_cells(*lat, *lon, size_m)).collect();
+        keys.sort();
+        keys.dedup();
+        keys.retain(|k| known.contains(k));
+        keys
+    };
+    let mut needed: Vec = wanted
+        .iter()
+        .flat_map(|k| (-1..=1).flat_map(move |dy| (-1..=1).map(move |dx| (k.x as i64 + dx, k.y as i64 + dy))))
+        .map(|(x, y)| CellKey { x: x as u32, y: y as u32 })
+        .filter(|k| known.contains(k))
+        .collect();
+    needed.sort();
+    needed.dedup();
+    let rules = obc_ground_plan::faces::Rules::embedded();
+    let mut cells: BTreeMap = BTreeMap::new();
+    let clock = Instant::now();
+    let now = || clock.elapsed().as_secs_f64() * 1e3;
+    for &key in &needed {
+        let t0 = now();
+        let input = fixture.try_cell(key).map_err(|e| format!("{key:?}: {e}"))?;
+        let t1 = now();
+        let graph = obc_ground_plan::graph::build(key, &input, &rules.sections);
+        let t2 = now();
+        let built = records::build(&graph, &input, rules, key, 0, true);
+        let t3 = now();
+        let rim = Rim::of(&built.faces);
+        let t4 = now();
+        cells.insert(
+            key,
+            Cell {
+                plan: built.faces,
+                words: built.near.words,
+                terrain: input.terrain,
+                rim,
+                times: [t1 - t0, t2 - t1, t3 - t2, t4 - t3],
+            },
+        );
+    }
+    let mut rows = Vec::new();
+    let mut per_stage: BTreeMap<&str, Vec> = BTreeMap::new();
+    let (mut totals, mut mesh_ms, mut sizes) = (BTreeMap::new(), BTreeMap::new(), BTreeMap::new());
+    let mut meshes: Vec<(CellKey, CellMesh)> = Vec::new();
+    let (mut faults, mut labels) = (Vec::new(), check::Labels::default());
+    for &key in &wanted {
+        let cell = &cells[&key];
+        let rims: Vec = (-1..=1i64)
+            .flat_map(|dy| {
+                (-1..=1i64).map(move |dx| CellKey { x: (key.x as i64 + dx) as u32, y: (key.y as i64 + dy) as u32 })
+            })
+            .filter_map(|k| cells.get(&k).map(|c| c.rim.clone()))
+            .collect();
+        let t0 = now();
+        let reads = Reads::of(&cell.plan, &rims);
+        let region_ms = now() - t0;
+        let mut clock = now;
+        let built = mesh::mesh_cell(&cell.plan, &cell.words, &reads, &mut clock);
+        let mut row = json!({"cell": [key.x, key.y]});
+        for (name, t) in ["input", "graph", "faces+records", "rim"].iter().zip(cell.times) {
+            per_stage.entry(name).or_default().push(t);
+        }
+        let mut total = cell.times.iter().sum::();
+        match built {
+            Err(e) => row["error"] = json!(format!("{e:?}")),
+            Ok(m) => {
+                let t = region_ms + m.times.iter().sum::();
+                total += t;
+                mesh_ms.insert(key, t);
+                per_stage.entry("mesh").or_default().push(t);
+                per_stage.entry("region").or_default().push(region_ms);
+                for (name, &t) in STAGES.iter().zip(&m.times) {
+                    per_stage.entry(name).or_default().push(t);
+                }
+                let s = &m.stats;
+                sizes.insert(key, (s.triangles + 2 * s.steps, s.corners, bytes(&m)));
+                row["stats"] = json!({
+                    "cells_r_s_d": s.cells, "points": s.points, "grid_points": s.grid_points, "corners": s.corners,
+                    "triangles": s.triangles, "strip_triangles": s.strip_triangles, "steps": s.steps,
+                    "outside_d": s.outside_d, "unlabelled": s.unlabelled, "split_edges": s.split_edges, "bytes": bytes(&m),
+                    "runs": [m.triangle_runs.len(), m.step_runs.len()],
+                    "level18_triangles": s.level18_triangles,
+                });
+                row["times"] = json!(STAGES
+                    .iter()
+                    .zip(&m.times)
+                    .map(|(n, t)| (n.to_string(), json!(t)))
+                    .collect::>());
+                if checks {
+                    faults.extend(check::validity(&m).into_iter().map(|f| format!("{key:?}: {f}")));
+                    let l = check::labels(&m, &cell.words);
+                    labels.sharp_wrong += l.sharp_wrong;
+                    labels.ground_wrong += l.ground_wrong;
+                    labels.ground_other += l.ground_other;
+                    labels.first.extend(l.first.into_iter().take(4).map(|f| format!("{key:?} {f}")));
+                }
+                meshes.push((key, m));
+            }
+        }
+        row["total_ms"] = json!(total);
+        totals.insert(key, total);
+        rows.push(row);
+    }
+    let (mut borders, mut sub_mm) = (0, 0);
+    if checks {
+        let by: BTreeMap = meshes.iter().map(|(k, m)| (*k, m)).collect();
+        for (&key, a) in &by {
+            for (east, other) in
+                [(true, CellKey { x: key.x + 1, y: key.y }), (false, CellKey { x: key.x, y: key.y + 1 })]
+            {
+                let Some(b) = by.get(&other) else { continue };
+                let cell = |k: CellKey, m| check::Cell {
+                    key: k,
+                    mesh: m,
+                    words: &cells[&k].words,
+                    terrain: &cells[&k].terrain,
+                };
+                let (f, s) = check::border(&cell(key, a), &cell(other, b), east);
+                faults.extend(f);
+                borders += 1;
+                sub_mm += s;
+            }
+        }
+    }
+    // The jump: every cell within 600 m of a view, where all of them were meshed.
+    let views = std::fs::read_to_string(root.join("builder/web/tests/browser/trailview/road-views.json"))
+        .map_err(|e| e.to_string())?;
+    let views: Value = serde_json::from_str(&views).map_err(|e| e.to_string())?;
+    let (mut jumps, mut jump_total, mut jump_mesh, mut view_tris, mut view_corners, mut view_bytes) =
+        (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
+    for view in views.as_array().into_iter().flatten() {
+        let (Some(name), Some(q)) = (view["name"].as_str(), view["view"].as_str()) else { continue };
+        let field = |k: &str| {
+            q.trim_start_matches('?').split('&').find_map(|p| p.strip_prefix(k)?.strip_prefix('='))?.parse::().ok()
+        };
+        let (Some(lat), Some(lon)) = (field("lat"), field("lon")) else { continue };
+        let c = from_lon_lat(lon, lat);
+        let reach = (JUMP_M / metres_per_unit(c.y)) as i64;
+        let (lo, hi) = (
+            CellKey::of(GlobalPoint { x: c.x - reach, y: c.y - reach }),
+            CellKey::of(GlobalPoint { x: c.x + reach, y: c.y + reach }),
+        );
+        let (mut sum, mut mesh_sum, mut tris, mut corners, mut size, mut n, mut missing) = (0.0, 0.0, 0, 0, 0, 0, 0);
+        let mut within = Vec::new();
+        for y in lo.y..=hi.y {
+            for x in lo.x..=hi.x {
+                let k = CellKey { x, y };
+                let o = k.origin();
+                let (dx, dy) =
+                    ((c.x - c.x.clamp(o.x, o.x + CELL_UNITS)) as f64, (c.y - c.y.clamp(o.y, o.y + CELL_UNITS)) as f64);
+                if libm::hypot(dx, dy) > reach as f64 {
+                    continue;
+                }
+                match (totals.get(&k), mesh_ms.get(&k), sizes.get(&k)) {
+                    (Some(t), Some(m), Some(&(tr, co, by))) => {
+                        (sum, mesh_sum, tris, corners, size, n) =
+                            (sum + t, mesh_sum + m, tris + tr, corners + co, size + by, n + 1);
+                        within.push([x, y]);
+                    }
+                    _ => missing += 1,
+                }
+            }
+        }
+        if n > 0 && missing == 0 {
+            jumps.push(json!({"view": name, "cells": within, "native_ms": sum, "mesh_ms": mesh_sum, "triangles": tris, "corners": corners, "bytes": size}));
+            jump_total.push(sum);
+            jump_mesh.push(mesh_sum);
+            view_tris.push(f64::from(tris));
+            view_corners.push(f64::from(corners));
+            view_bytes.push(size as f64);
+        }
+    }
+    let summary = json!({
+        "cells": wanted.len(),
+        "meshed": meshes.len(),
+        "stages": per_stage.iter().map(|(k, v)| (k.to_string(), quantiles(v.clone()))).collect::>(),
+        "total": quantiles(totals.values().copied().collect()),
+        "jump_views": jumps.len(),
+        "jump_native_ms": quantiles(jump_total),
+        "jump_mesh_ms": quantiles(jump_mesh),
+        "view_triangles_with_steps": quantiles(view_tris),
+        "view_corners": quantiles(view_corners),
+        "view_bytes": quantiles(view_bytes),
+        "reference": DEVELOP,
+        "checks": checks.then(|| json!({"faults": faults.len(), "borders": borders, "sub_mm": sub_mm, "labels": format!("{labels:?}"), "first": faults.iter().take(20).collect::>()})),
+    });
+    if !all {
+        let views = root.join("builder/web/tests/browser/trailview/road-views-top.json");
+        for (name, lat, lon) in crate::named_places(&views, &places)? {
+            picture(&out.join(format!("{name}.png")), from_lon_lat(lon, lat), size_m, &meshes, &cells)?;
+        }
+    }
+    let path = out.join("mesh-timing.json");
+    std::fs::write(
+        &path,
+        serde_json::to_string_pretty(&json!({"summary": summary, "cells": rows, "jumps": jumps})).unwrap(),
+    )
+    .map_err(|e| format!("{}: {e}", path.display()))?;
+    println!("{}", serde_json::to_string_pretty(&summary).unwrap());
+    println!("-> {}", path.display());
+    Ok(())
+}
diff --git a/host/obc-ground-plan/examples/debug/model.rs b/host/obc-ground-plan/examples/debug/model.rs
new file mode 100644
index 0000000000..0871a5c07b
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/model.rs
@@ -0,0 +1,198 @@
+//! `model --out DIR [--runs N] [--samples N]`: the records of every fixture cell. Writes
+//! `model.bin` (a table of the cells, then their near blocks) and `model-bench.json`: build times
+//! and sizes by profile, and the checks of `faces::records::check`.
+
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+use std::time::Instant;
+
+use obc_ground_plan::faces::check::feature_names;
+use obc_ground_plan::faces::records::check::{agreement, border, far_agreement, Miss, Overlay};
+use obc_ground_plan::faces::records::{self, BINS, HEADER};
+use obc_ground_plan::faces::{self, Rules};
+use obc_ground_plan::frame::{CellKey, GlobalPoint};
+use obc_ground_plan::graph::{self, WayGraph};
+use serde_json::{json, Value};
+
+use crate::faces::{quantiles, TOWN_JUNCTIONS};
+use crate::fixture::{default_dir, Fixture};
+
+/// The file's magic: a table of cells, then their blocks.
+const FILE_MAGIC: u32 = 0x4f42_5246;
+/// A miss of a label this near an edge between two labels is the slice's precision, in units.
+const EDGE_UNITS: f64 = 8.0;
+
+struct Cell {
+    key: CellKey,
+    words: Vec,
+    far_records: Vec,
+    graph: WayGraph,
+    names: Vec<[u32; 3]>,
+    town: bool,
+    /// Graph, the cell's build (faces, near and far records) and the faces alone, in ms: the least of
+    /// the runs.
+    ms: [f64; 3],
+    agree: [u64; 5],
+    area: Vec,
+    far_agree: [u64; 2],
+}
+
+fn time(f: impl FnOnce() -> T) -> (T, f64) {
+    let t = Instant::now();
+    let v = f();
+    (v, t.elapsed().as_secs_f64() * 1e3)
+}
+
+/// Words per part of a block, from its head's offsets.
+fn parts(w: &[u32]) -> [u64; 10] {
+    let bins = w[9] as usize + HEADER * (BINS * BINS) as usize;
+    let at = [0, w[4], w[5], w[6], w[7], w[8], w[12], w[11], w[14], w[9], bins as u32, w.len() as u32];
+    std::array::from_fn(|k| u64::from(at[k + 1] - at[k]))
+}
+
+const PARTS: [&str; 10] = [
+    "head",
+    "candidates",
+    "labels",
+    "lines",
+    "samples",
+    "extras",
+    "junctions",
+    "blend edges",
+    "outline edges",
+    "bin headers",
+];
+
+pub fn run() -> Result<(), String> {
+    let (mut out, mut runs, mut n) = (None::, 1usize, 10i32);
+    let mut args = std::env::args().skip(2);
+    while let Some(arg) = args.next() {
+        let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value"));
+        match arg.as_str() {
+            "--out" => out = Some(value()?.into()),
+            "--runs" => runs = value()?.parse().map_err(|_| "--runs: a count")?,
+            "--samples" => n = value()?.parse().map_err(|_| "--samples: a count")?,
+            _ => return Err(format!("model: unknown option {arg}")),
+        }
+    }
+    let out = out.ok_or("model --out DIR [--runs N] [--samples N]")?;
+    std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
+    let dir = default_dir();
+    let mut fix = Fixture::open(&dir);
+    let cells = crate::graph::fixture_cells(&fix, &dir);
+    let rules = Rules::embedded();
+    let built: Vec = fix.map(&cells, |key, input| {
+        let mut ms = [f64::INFINITY; 3];
+        let mut last = None;
+        for _ in 0..runs {
+            let (graph, g) = time(|| graph::build(key, &input, &rules.sections));
+            let (built, b) = time(|| records::build(&graph, &input, rules, key, 0, true));
+            let (_, p) = time(|| faces::build(&graph, &input, rules, key, 0, true));
+            ms = [ms[0].min(g), ms[1].min(b), ms[2].min(p)];
+            last = Some((graph, built));
+        }
+        let (graph, records::Built { faces: plan, near, far_records, .. }) = last.unwrap();
+        let a = agreement(&near.words, &plan, &Overlay::new(&graph, &input, rules, key, true), n, EDGE_UNITS);
+        let far_agree = far_agreement(&near.words, &far_records.words, n);
+        eprintln!(
+            "cell {} {}: build {:.1} ms, {} words, area misses {}",
+            key.x,
+            key.y,
+            ms[1],
+            near.words.len(),
+            a.area.len()
+        );
+        Cell {
+            key,
+            town: plan.stats.junctions >= TOWN_JUNCTIONS,
+            words: near.words,
+            far_records: far_records.words,
+            graph,
+            names: feature_names(&input),
+            ms,
+            agree: [a.points, a.edge, a.arc, a.patch, a.rail],
+            area: a.area,
+            far_agree,
+        }
+    });
+    let by_key: BTreeMap = built.iter().map(|c| (c.key, c)).collect();
+    let (mut border_points, mut border_blend, mut border_differ, mut border_places) = (0u64, 0u64, 0usize, Vec::new());
+    for (&key, a) in &by_key {
+        for (east, other) in [(true, CellKey { x: key.x + 1, y: key.y }), (false, CellKey { x: key.x, y: key.y + 1 })] {
+            let Some(b) = by_key.get(&other) else { continue };
+            let (points, blend, differ) =
+                border((&a.words, &a.graph, &a.names), (&b.words, &b.graph, &b.names), east, 64);
+            border_points += points;
+            border_blend += blend;
+            border_differ += differ.len();
+            border_places.extend(differ.into_iter().take(4).map(|d| json!({"cells": [[key.x, key.y], [other.x, other.y]], "along": d.0, "west_or_north": d.1, "east_or_south": d.2})));
+        }
+    }
+    let x0 = built.iter().map(|c| c.key.x).min().unwrap_or(0);
+    let y0 = built.iter().map(|c| c.key.y).min().unwrap_or(0);
+    let w = built.iter().map(|c| c.key.x).max().unwrap_or(0) - x0 + 1;
+    let h = built.iter().map(|c| c.key.y).max().unwrap_or(0) - y0 + 1;
+    let mut file = vec![FILE_MAGIC, x0, y0, w, h];
+    file.resize(5 + (w * h) as usize, 0);
+    for c in &built {
+        file[5 + ((c.key.y - y0) * w + c.key.x - x0) as usize] = file.len() as u32;
+        file.extend(&c.words);
+    }
+    let bytes: Vec = file.iter().flat_map(|w| w.to_le_bytes()).collect();
+    std::fs::write(out.join("model.bin"), &bytes).map_err(|e| e.to_string())?;
+    let mut profiles: BTreeMap<&str, BTreeMap<&str, Vec>> = BTreeMap::new();
+    let mut words: BTreeMap = BTreeMap::new();
+    for c in &built {
+        let p = profiles.entry(if c.town { "town" } else { "rural" }).or_default();
+        for (k, v) in ["graph_ms", "build_ms", "faces_ms"].iter().zip(c.ms) {
+            p.entry(k).or_default().push(v);
+        }
+        p.entry("kB").or_default().push(c.words.len() as f64 / 256.0);
+        p.entry("far_records_kB").or_default().push(c.far_records.len() as f64 / 256.0);
+        let total = c.words.len() as u64;
+        let listed = parts(&c.words);
+        for (name, v) in PARTS.iter().zip(listed) {
+            *words.entry(name.to_string()).or_default() += v;
+        }
+        *words.entry("bin items".into()).or_default() += total - listed.iter().sum::();
+    }
+    let all: u64 = words.values().sum();
+    let shares: BTreeMap =
+        words.iter().map(|(k, &v)| (k.clone(), format!("{:.1} %", 100.0 * v as f64 / all.max(1) as f64))).collect();
+    let sum = |f: &dyn Fn(&Cell) -> u64| built.iter().map(f).sum::();
+    let area: Vec = (built.iter())
+        .flat_map(|c| c.area.iter().take(8).map(move |m| (c.key, m)))
+        .take(60)
+        .map(|(k, m)| {
+            let o = k.origin();
+            let (lon, lat) = crate::lon_lat(GlobalPoint { x: o.x + m.q[0] as i64, y: o.y + m.q[1] as i64 });
+            json!({"cell": [k.x, k.y], "q": m.q, "lat": lat, "lon": lon, "face": m.face, "records": m.records, "edge_units": m.edge})
+        })
+        .collect();
+    let report = json!({
+        "cells": built.len(),
+        "file_bytes": bytes.len(),
+        "far_records_bytes": 4 * built.iter().map(|c| c.far_records.len()).sum::(),
+        "profiles": profiles.into_iter().map(|(k, v)| (k, v.into_iter().map(|(n, x)| (n, quantiles(x))).collect::>())).collect::>(),
+        "words": shares,
+        "agreement": {
+            "samples per bin side": n,
+            "points": sum(&|c| c.agree[0]),
+            "near an edge": sum(&|c| c.agree[1]),
+            "edge_units": EDGE_UNITS,
+            "on an arc": sum(&|c| c.agree[2]),
+            "patch rules": sum(&|c| c.agree[3]),
+            "patch rules, rail bed": sum(&|c| c.agree[4]),
+            "patch rules by cell": built.iter().filter(|c| c.agree[3] > 0).map(|c| json!([[c.key.x, c.key.y], c.agree[3]])).collect::>(),
+            "other": sum(&|c| c.area.len() as u64),
+            "other by cell": built.iter().filter(|c| !c.area.is_empty()).map(|c| json!([[c.key.x, c.key.y], c.area.len()])).collect::>(),
+            "places": area,
+        },
+        "far": {"points": sum(&|c| c.far_agree[0]), "differ": sum(&|c| c.far_agree[1])},
+        "border": {"points": border_points, "with a blend edge near": border_blend, "differ": border_differ, "places": border_places},
+    });
+    let text = serde_json::to_string_pretty(&report).unwrap();
+    std::fs::write(out.join("model-bench.json"), &text).map_err(|e| e.to_string())?;
+    println!("{text}");
+    Ok(())
+}
diff --git a/host/obc-ground-plan/examples/debug/requests.rs b/host/obc-ground-plan/examples/debug/requests.rs
new file mode 100644
index 0000000000..07f745acef
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/requests.rs
@@ -0,0 +1,161 @@
+//! `requests`: the request bytes of fixture cells, with their native digests (with the storeys, as the bridge
+//! builds them) and build times, for check 7 (`builder/ground-plan-wasm/check.mjs`) and the timing page. A cell whose far-only build
+//! gives another far block than its full build, or whose far block breaks `far_matches_near`, is an
+//! error; a cell whose far block the crate refuses is noted and counted.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::time::Instant;
+
+use obc_ground_plan::cell::{build_cell, build_storeys, far_request, CellBuild, STAGES};
+use obc_ground_plan::faces::records::check::far_matches_near;
+use obc_ground_plan::frame::CellKey;
+use obc_ground_plan::terrain::Terrain;
+use obc_ground_plan::tile::TileCache;
+use obc_ground_plan::transport::{fnv, Flat, Request};
+use serde_json::{json, Value};
+
+use crate::fixture::{self, Fixture};
+
+/// The side of the square about a place whose cells a place names.
+const PLACE_M: f64 = 128.0;
+
+/// The fixture files of a cell's inputs as the viewer loads them: feature tiles (gzip) and terrain
+/// tiles (WebP), for the timing page's `prepare`.
+fn sources(dir: &Path, key: CellKey) -> Value {
+    let path = |p: PathBuf| p.is_file().then(|| p.display().to_string());
+    let tiles: Vec = (key.feature_tiles().into_iter())
+        .filter_map(|(c, r)| Some(json!([c, r, path(dir.join(format!("features/13/{c}/{r}.bin")))?])))
+        .collect();
+    let mut stored: Vec<(u32, u32, u32)> =
+        Terrain::wanted(key).into_iter().map(|p| (p.tile().0, p.tile().1, p.tile().2)).collect();
+    stored.sort();
+    stored.dedup();
+    let terrain: Vec = (stored.into_iter())
+        .filter_map(|(z, x, y)| Some(json!([z, x, y, path(dir.join(format!("terrain/{z}/{x}/{y}.webp")))?])))
+        .collect();
+    json!({"tiles": tiles, "terrain": terrain})
+}
+
+fn median(mut values: Vec) -> f64 {
+    values.sort_by(f64::total_cmp);
+    values[values.len() / 2]
+}
+
+pub fn run() -> Result<(), String> {
+    let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
+    let (mut out, mut places, mut all, mut runs) = (None::, Vec::new(), false, 5usize);
+    let mut views = root.join("builder/web/tests/browser/trailview/road-views-top.json");
+    let mut dir = fixture::default_dir();
+    let mut args = std::env::args().skip(2);
+    while let Some(arg) = args.next() {
+        let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value"));
+        match arg.as_str() {
+            "--out" => out = Some(value()?.into()),
+            "--places" => places = value()?.split(',').map(String::from).collect(),
+            "--all" => all = true,
+            "--runs" => runs = value()?.parse().map_err(|_| "--runs: a count")?,
+            "--views" => views = value()?.into(),
+            "--fixture" => dir = value()?.into(),
+            _ => return Err(format!("requests: unknown option {arg}")),
+        }
+    }
+    let out = out.ok_or("requests --out DIR (--places NAMES | --all) [--runs N]")?;
+    if all == !places.is_empty() || runs == 0 {
+        return Err("requests: give --places or --all, and --runs of 1 or more".into());
+    }
+    let mut fix = Fixture::open(&dir);
+    let mut cells: BTreeMap> = BTreeMap::new();
+    if all {
+        cells.extend(fix.cells().into_iter().map(|k| (k, Vec::new())));
+    }
+    for (name, lat, lon) in crate::named_places(&views, &places)? {
+        for key in crate::square_cells(lat, lon, PLACE_M) {
+            cells.entry(key).or_default().push(name.clone());
+        }
+    }
+    std::fs::create_dir_all(&out).map_err(|e| format!("{}: {e}", out.display()))?;
+    let rules = obc_ground_plan::faces::Rules::embedded();
+    let start = Instant::now();
+    let mut clock = || start.elapsed().as_secs_f64() * 1e3;
+    let fixture_dir = std::fs::canonicalize(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+    let (mut index, mut refused, mut seen) = (Vec::new(), 0, BTreeMap::<&str, usize>::new());
+    for (key, names) in cells {
+        let bytes = fix.request(key).encode();
+        let file = format!("{}-{}.bin", key.x, key.y);
+        crate::write(&out.join(&file), &bytes)?;
+        let builds = (0..runs)
+            .map(|_| build_cell(&bytes, rules, &mut clock).map_err(|e| format!("cell {}/{}: {e}", key.x, key.y)))
+            .collect::, _>>()?;
+        let last = &builds[runs - 1];
+        let fail = |e: String| format!("cell {}/{}: {e}", key.x, key.y);
+        let flat = Flat::of(last);
+        // The bridge's digest: with the storeys, of the build with them.
+        let digest = if cfg!(feature = "storeys") {
+            let request = Request::decode(&bytes).map_err(fail)?;
+            let with = build_storeys(request, &mut TileCache::new(4), rules, &mut clock).map_err(fail)?;
+            let with = CellBuild { request: Some(fnv(&bytes)), ..with };
+            Flat::of(&with).digest(&with).map_err(fail)?
+        } else {
+            flat.digest(last).map_err(fail)?
+        };
+        // What the GPU reads, without the graph: the near records and the faces that the mesh builds on.
+        let le = |words: &mut dyn Iterator| -> Vec { words.flat_map(u32::to_le_bytes).collect() };
+        let records = fnv(&le(&mut last.records.iter().copied()));
+        let f = &flat.faces;
+        let faces = fnv(&le(&mut (f.vertices.iter().map(|&v| v as u32))
+            .chain(f.faces.iter().copied())
+            .chain(f.rings.iter().copied())
+            .chain(f.ring_vertices.iter().copied())
+            .chain(f.edges.iter().copied())
+            .chain(f.corners.iter().copied())
+            .chain(f.corner_points.iter().map(|&v| v as u32))));
+        // The far-only build as `build_cell` does a full one: from the bytes, with a new tile cache.
+        let mut far_ms = Vec::with_capacity(runs);
+        for _ in 0..runs {
+            let start = clock();
+            let alone = far_request(Request::decode(&bytes).map_err(fail)?, &mut TileCache::new(4), rules);
+            far_ms.push(clock() - start);
+            if alone != last.far {
+                return Err(fail("the far-only build gives another far block".into()));
+            }
+        }
+        let (far, far_bytes, counts) = match &last.far {
+            Ok(words) => {
+                let (faults, counts) = far_matches_near(&last.records, words, key);
+                if !faults.is_empty() {
+                    return Err(fail(format!(
+                        "{} far block faults: {:?}",
+                        faults.len(),
+                        &faults[..faults.len().min(4)]
+                    )));
+                }
+                counts.iter().for_each(|(&case, &n)| *seen.entry(case).or_default() += n);
+                let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect();
+                (fnv(&bytes), bytes.len(), json!(counts))
+            }
+            Err(e) => {
+                refused += 1;
+                eprintln!("cell {}/{}: the far block is refused: {e}", key.x, key.y);
+                (format!("refused: {e}"), 0, Value::Null)
+            }
+        };
+        let times: Vec<&Vec> = builds.iter().map(|b| &b.times).collect();
+        let mut native: serde_json::Map = (STAGES.iter().enumerate())
+            .map(|(i, stage)| (stage.to_string(), json!(median(times.iter().map(|t| t[i]).collect()))))
+            .collect();
+        native.insert("total".into(), json!(median(times.iter().map(|t| t.iter().sum()).collect())));
+        native.insert("far".into(), json!(median(far_ms)));
+        index.push(json!({
+            "cell": [key.x, key.y], "file": file, "places": names, "request": fnv(&bytes), "digest": digest,
+            "records": records, "faces": faces,
+            "far": far, "far_bytes": far_bytes, "far_check": counts, "native": native, "sources": sources(&fixture_dir, key),
+        }));
+    }
+    crate::write(&out.join("index.json"), serde_json::to_string_pretty(&index).unwrap().as_bytes())?;
+    let folder = std::fs::canonicalize(&out).map_err(|e| format!("{}: {e}", out.display()))?;
+    println!("{} requests -> {}", index.len(), out.join("index.json").display());
+    println!("far blocks: {refused} refused; the check saw {seen:?}");
+    println!("timing page: http://:5173/plan-timing.html?requests=/@fs{}/", folder.display());
+    Ok(())
+}
diff --git a/host/obc-ground-plan/examples/debug/storeys.rs b/host/obc-ground-plan/examples/debug/storeys.rs
new file mode 100644
index 0000000000..047089e3b9
--- /dev/null
+++ b/host/obc-ground-plan/examples/debug/storeys.rs
@@ -0,0 +1,403 @@
+//! `--storeys`: per place the storeys over the ground from above (`-storeys.png`: the sheets' faces, their
+//! free outline, the open lines, the parapets, railings and piers) and seen obliquely (`-oblique.png`: the
+//! cell meshes of storey 0 with every storey's mesh and shell, heights by the crate's height function, flat-shaded,
+//! the storeys' triangles culled from behind), with `--gltf` the same meshes as `-storeys.glb`.
+
+use std::collections::BTreeMap;
+
+use obc_ground_plan::cell::{build_storeys, CellBuild};
+use obc_ground_plan::faces::heights::height_at;
+use obc_ground_plan::faces::records;
+use obc_ground_plan::faces::{Rules, Surface};
+use obc_ground_plan::frame::{metres_per_unit, CellKey, GlobalPoint};
+use obc_ground_plan::mesh::params::{CELLS, COARSE};
+use obc_ground_plan::mesh::shell::{closure, mesh_storeys, on_paved, StoreyMesh, PARTS};
+use obc_ground_plan::mesh::{mesh_cell, CellMesh, Reads, Rim, NO_LABEL};
+use obc_ground_plan::tile::TileCache;
+use obc_ground_plan::CellInput;
+use serde_json::{json, Value};
+use tiny_skia::{FillRule, Pixmap, Transform};
+
+use crate::draw::{self, cell_square, Canvas};
+use crate::fixture::Fixture;
+use crate::gltf;
+
+pub struct Cell {
+    pub build: CellBuild,
+    pub mesh: Option,
+    pub storeys: StoreyMesh,
+}
+
+/// The cells with their storeys, storey 0's mesh (with the rims of the cells about them) and the storeys' meshes.
+pub fn cells(fix: &mut Fixture, keys: &[CellKey], rules: &Rules) -> Result, String> {
+    let mut cache = TileCache::new(16);
+    let mut built = BTreeMap::new();
+    for &key in keys {
+        let b = build_storeys(fix.request(key), &mut cache, rules, &mut || 0.0)?;
+        built.insert(key, b);
+    }
+    let rims: BTreeMap = built.iter().map(|(&k, b)| (k, Rim::of(&b.faces))).collect();
+    let mut out = BTreeMap::new();
+    for (key, b) in built {
+        let around: Vec = (-1..=1i64)
+            .flat_map(|dy| {
+                (-1..=1i64).map(move |dx| CellKey { x: (key.x as i64 + dx) as u32, y: (key.y as i64 + dy) as u32 })
+            })
+            .filter_map(|k| rims.get(&k).cloned())
+            .collect();
+        let mesh = mesh_cell(&b.faces, &b.records, &Reads::of(&b.faces, &around), &mut || 0.0).ok();
+        let storeys = mesh_storeys(key, &b.storeys, &b.records, &rules.structures).map_err(|e| format!("{e:?}"))?;
+        out.insert(key, Cell { build: b, mesh, storeys });
+    }
+    Ok(out)
+}
+
+/// The counts and checks of the place's cells; the triangles and corners of the storeys' meshes in the square
+/// [x0, y0, x1, y1] (global frame units, every corner inside).
+pub fn stats(cells: &BTreeMap, square: [f64; 4]) -> Value {
+    let inside = |key: CellKey, p: [i32; 2]| {
+        let g = global(key, p);
+        (square[0]..=square[2]).contains(&(g.x as f64)) && (square[1]..=square[3]).contains(&(g.y as f64))
+    };
+    let mut near = [0u32; PARTS.len()];
+    let mut near_corners = std::collections::BTreeSet::new();
+    for (&key, c) in cells {
+        let m = &c.storeys;
+        for (k, n) in near.iter_mut().enumerate() {
+            for t in &m.triangles[m.part(k)] {
+                if t.iter().all(|&i| inside(key, m.corner(i as usize).0)) {
+                    *n += 1;
+                    near_corners.extend(t.iter().map(|&i| (key, i)));
+                }
+            }
+        }
+    }
+    let mut parts = [0u32; PARTS.len()];
+    let (mut closure_faults, mut paved, mut bytes, mut piers, mut left_out) = (Vec::new(), Vec::new(), 0, 0, 0);
+    for c in cells.values() {
+        for (k, n) in c.storeys.parts.iter().enumerate() {
+            parts[k] += n;
+        }
+        closure_faults.extend(closure(&c.storeys));
+        paved.extend(on_paved(&c.storeys, &c.build.storeys, &c.build.records));
+        bytes += if c.storeys.corners.is_empty() { 0 } else { c.storeys.to_bytes().len() };
+        piers += c.storeys.stats.piers;
+        left_out += c.storeys.stats.piers_left_out;
+    }
+    let by_part = |v: [u32; PARTS.len()]| {
+        PARTS.iter().zip(v).map(|(n, k)| (n.to_string(), json!(k))).collect::>()
+    };
+    json!({"triangles": by_part(parts), "in_square": {"triangles": by_part(near), "corners": near_corners.len()},
+        "piers": piers, "piers_left_out": left_out, "storey_mesh_bytes": bytes,
+        "closure_faults": closure_faults, "on_paved": paved})
+}
+
+fn global(key: CellKey, p: [i32; 2]) -> GlobalPoint {
+    let o = key.origin();
+    GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) }
+}
+
+/// The sheets from above: faces by surface, the free outline dark blue, the open lines green, parapets red,
+/// railings orange, piers black.
+pub fn top(canvas: &mut Canvas, cells: &BTreeMap) {
+    for (&key, c) in cells {
+        let mask = canvas.mask(cell_square(key));
+        for plan in &c.build.storeys.plans {
+            for f in plan.faces.iter().filter(|f| f.surface != Surface::Terrain) {
+                let Some((r, g, b, _)) = obc_ground_plan::debug::face_colour(f.surface, false) else { continue };
+                for ring in f.rings.iter().take(1) {
+                    let pts: Vec = ring.iter().map(|&v| global(key, plan.vertices[v as usize])).collect();
+                    if let Some(p) = draw::path(canvas, &pts, true) {
+                        canvas.pixmap.fill_path(
+                            &p,
+                            &draw::paint(r, g, b, 230),
+                            FillRule::EvenOdd,
+                            Transform::identity(),
+                            mask.as_ref(),
+                        );
+                    }
+                }
+            }
+        }
+        let m = &c.storeys;
+        let fill = |canvas: &mut Canvas, part: usize, rgb: (u8, u8, u8)| {
+            for t in &m.triangles[m.part(part)] {
+                let pts: Vec = t.iter().map(|&k| global(key, m.corner(k as usize).0)).collect();
+                if let Some(p) = draw::path(canvas, &pts, true) {
+                    canvas.pixmap.fill_path(
+                        &p,
+                        &draw::paint(rgb.0, rgb.1, rgb.2, 255),
+                        FillRule::Winding,
+                        Transform::identity(),
+                        mask.as_ref(),
+                    );
+                }
+            }
+        };
+        fill(canvas, 3, (210, 40, 40));
+        fill(canvas, 4, (240, 150, 0));
+        fill(canvas, 5, (240, 150, 0));
+        fill(canvas, 6, (20, 20, 20));
+        for t in &m.triangles[m.part(2)] {
+            let pts: Vec = t.iter().map(|&k| global(key, m.corner(k as usize).0)).collect();
+            if let Some(p) = draw::path(canvas, &pts, true) {
+                canvas.pixmap.stroke_path(
+                    &p,
+                    &draw::paint(20, 40, 160, 255),
+                    &draw::stroke(2.0, false),
+                    Transform::identity(),
+                    mask.as_ref(),
+                );
+            }
+        }
+        for o in &m.open {
+            if let Some(p) = draw::path(canvas, &[global(key, o[0]), global(key, o[1])], false) {
+                canvas.pixmap.stroke_path(
+                    &p,
+                    &draw::paint(0, 170, 60, 255),
+                    &draw::stroke(3.0, false),
+                    Transform::identity(),
+                    mask.as_ref(),
+                );
+            }
+        }
+    }
+}
+
+/// A triangle in metres about the centre (east, north, up), its colour, and whether it shows from behind.
+type Tri = ([[f64; 3]; 3], [f32; 3], bool);
+
+fn rgb(c: (u8, u8, u8)) -> [f32; 3] {
+    [f32::from(c.0) / 255.0, f32::from(c.1) / 255.0, f32::from(c.2) / 255.0]
+}
+
+/// Every triangle of the place's meshes with its heights.
+fn triangles(
+    cells: &BTreeMap,
+    inputs: &BTreeMap,
+    centre: GlobalPoint,
+    base: f64,
+    half_m: f64,
+) -> Vec {
+    let mpu = metres_per_unit(centre.y);
+    let at = |key: CellKey, p: [i32; 2], z: f64| {
+        let g = global(key, p);
+        [(g.x - centre.x) as f64 * mpu, -((g.y - centre.y) as f64) * mpu, z - base]
+    };
+    let mut out = Vec::new();
+    // The terrain under everything, a hair low: the GPU sinks it where a cell's mesh draws.
+    let step = (half_m / 60.0).max(0.25);
+    let n = (2.0 * half_m / step) as i64;
+    let ground = |i: i64, j: i64| {
+        let (e, s) = (-half_m + i as f64 * step, -half_m + j as f64 * step);
+        let g = GlobalPoint { x: centre.x + (e / mpu) as i64, y: centre.y + (s / mpu) as i64 };
+        inputs.get(&CellKey::of(g)).and_then(|c| c.terrain.height(g)).map(|h| [e, -s, h - base - 0.05])
+    };
+    // A point in R of its cell's mesh: the terrain is sunk there.
+    let in_r = |e: f64, n: f64| {
+        let g = GlobalPoint { x: centre.x + (e / mpu) as i64, y: centre.y - (n / mpu) as i64 };
+        let key = CellKey::of(g);
+        let Some(m) = cells.get(&key).and_then(|c| c.mesh.as_ref()) else { return false };
+        let o = key.origin();
+        let (cx, cy) = ((g.x - o.x) / i64::from(COARSE), (g.y - o.y) / i64::from(COARSE));
+        let bit = ((cy + 1) * i64::from(CELLS + 2) + cx + 1) as usize;
+        m.region.get(bit / 32).is_some_and(|w| w >> (bit % 32) & 1 == 1)
+    };
+    for j in 0..n {
+        for i in 0..n {
+            if let (Some(a), Some(b), Some(c), Some(d)) =
+                (ground(i, j), ground(i + 1, j), ground(i, j + 1), ground(i + 1, j + 1))
+            {
+                if in_r((a[0] + d[0]) / 2.0, (a[1] + d[1]) / 2.0) {
+                    continue;
+                }
+                out.push(([a, c, b], rgb((150, 175, 120)), true));
+                out.push(([b, c, d], rgb((150, 175, 120)), true));
+            }
+        }
+    }
+    for (&key, c) in cells {
+        let words = &c.build.records;
+        let terrain = |p: [i32; 2]| inputs.get(&key).and_then(|i| i.terrain.height(global(key, p))).unwrap_or(base);
+        let near = |p: [f64; 3]| p[0].abs() <= half_m && p[1].abs() <= half_m;
+        if let Some(m) = &c.mesh {
+            let z = |k: u32| {
+                let (p, l, flag) = m.corner(k as usize);
+                let t = terrain(p);
+                let h = if flag || l == NO_LABEL {
+                    t
+                } else {
+                    height_at(words, [f64::from(p[0]), f64::from(p[1])], Some(l), t).h
+                };
+                (at(key, p, h), l)
+            };
+            let colour = |l: u32| match if l == NO_LABEL { 0 } else { records::label(words, l)[0] & 0xff } {
+                2 | 6 => (120, 120, 125),
+                3 => (175, 170, 150),
+                7 => (130, 105, 85),
+                9 => (60, 110, 200),
+                _ => (130, 165, 100),
+            };
+            let strip = m.triangles.len() - m.strip_triangles as usize;
+            for (i, t) in m.triangles.iter().enumerate() {
+                let v = t.map(z);
+                if v.iter().all(|x| near(x.0)) {
+                    let col = if i >= strip { (130, 165, 100) } else { colour(v[0].1) };
+                    out.push((v.map(|x| x.0), rgb(col), true));
+                }
+            }
+            for s in &m.steps {
+                let v = s.map(z);
+                if v.iter().all(|x| near(x.0)) {
+                    out.push(([v[0].0, v[1].0, v[2].0], rgb((150, 140, 125)), true));
+                    out.push(([v[0].0, v[2].0, v[3].0], rgb((150, 140, 125)), true));
+                }
+            }
+        }
+        let m = &c.storeys;
+        let z = |k: u32| {
+            let (p, l, off) = m.corner(k as usize);
+            let t = terrain(p);
+            let h = if l == NO_LABEL { t } else { height_at(words, [f64::from(p[0]), f64::from(p[1])], Some(l), t).h };
+            at(key, p, h + off)
+        };
+        let colours = [
+            (150, 150, 152),
+            (95, 93, 88),
+            (165, 162, 152),
+            (200, 196, 186),
+            (70, 74, 78),
+            (70, 74, 78),
+            (170, 166, 156),
+        ];
+        // The top in its surface's colour: carriageway grey, rail bed brown, shoulder pale, band blue-grey.
+        let top = |l: u32| match records::label(words, l)[0] & 0xff {
+            2 | 6 => (115, 115, 120),
+            3 => (185, 180, 160),
+            7 => (125, 100, 80),
+            12 => (150, 170, 190),
+            _ => (150, 150, 152),
+        };
+        for (k, colour) in colours.iter().enumerate() {
+            for t in &m.triangles[m.part(k)] {
+                let v = t.map(z);
+                let colour = if k == 0 { top(m.corner(t[0] as usize).1) } else { *colour };
+                if v.iter().all(|&x| near(x)) {
+                    out.push((v, rgb(colour), false));
+                }
+            }
+        }
+        for (i, s) in m.slots.iter().enumerate() {
+            let v = s.map(z);
+            let col = rgb(if (i as u32) < m.top_slots { (140, 140, 140) } else { (95, 93, 88) });
+            if v.iter().all(|&x| near(x)) {
+                out.push(([v[0], v[1], v[2]], col, true));
+                out.push(([v[0], v[2], v[3]], col, true));
+            }
+        }
+    }
+    out
+}
+
+/// The place seen obliquely from `heading` (degrees from north) and `pitch` (degrees down), orthographic, about the
+/// height `base`: painter's order, flat shading from the north-west.
+pub fn oblique(
+    path: &std::path::Path,
+    cells: &BTreeMap,
+    inputs: &BTreeMap,
+    centre: GlobalPoint,
+    size_m: f64,
+    (heading, pitch): (f64, f64),
+) -> Result<(), String> {
+    let base = inputs.get(&CellKey::of(centre)).and_then(|i| i.terrain.height(centre)).unwrap_or(0.0);
+    let tris = triangles(cells, inputs, centre, base, size_m / 2.0);
+    let (h, p) = (heading.to_radians(), pitch.to_radians());
+    let fwd = [libm::sin(h), libm::cos(h)];
+    let right = [libm::cos(h), -libm::sin(h)];
+    let view = [fwd[0] * libm::cos(p), fwd[1] * libm::cos(p), -libm::sin(p)];
+    let up = [fwd[0] * libm::sin(p), fwd[1] * libm::sin(p), libm::cos(p)];
+    let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+    let px = 1600u32;
+    let scale = f64::from(px) / size_m;
+    let screen = |v: [f64; 3]| {
+        let x = v[0] * right[0] + v[1] * right[1];
+        ((x * scale + f64::from(px) / 2.0) as f32, (f64::from(px) / 2.0 - dot(v, up) * scale) as f32)
+    };
+    let light = {
+        let l = [-0.5, 0.6, 0.65];
+        let n = libm::sqrt(dot(l, l));
+        [l[0] / n, l[1] / n, l[2] / n]
+    };
+    let mut items: Vec<(f64, &Tri)> =
+        tris.iter().map(|t| ((dot(t.0[0], view) + dot(t.0[1], view) + dot(t.0[2], view)) / 3.0, t)).collect();
+    items.sort_by(|a, b| b.0.total_cmp(&a.0));
+    let mut pixmap = Pixmap::new(px, px).ok_or("a picture")?;
+    pixmap.fill(tiny_skia::Color::from_rgba8(205, 220, 235, 255));
+    for (_, (v, colour, two_sided)) in items {
+        let (a, b) = (
+            [v[1][0] - v[0][0], v[1][1] - v[0][1], v[1][2] - v[0][2]],
+            [v[2][0] - v[0][0], v[2][1] - v[0][1], v[2][2] - v[0][2]],
+        );
+        let mut n = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
+        let len = libm::sqrt(dot(n, n));
+        if len <= 1e-12 {
+            continue;
+        }
+        n = [n[0] / len, n[1] / len, n[2] / len];
+        if dot(n, view) > 0.0 {
+            if !*two_sided {
+                continue;
+            }
+            n = [-n[0], -n[1], -n[2]];
+        }
+        let shade = (0.45 + 0.55 * dot(n, light).max(0.0)) as f32;
+        let c = colour.map(|x| (x * shade * 255.0).clamp(0.0, 255.0) as u8);
+        let mut pb = tiny_skia::PathBuilder::new();
+        let s = v.map(screen);
+        pb.move_to(s[0].0, s[0].1);
+        pb.line_to(s[1].0, s[1].1);
+        pb.line_to(s[2].0, s[2].1);
+        pb.close();
+        if let Some(path) = pb.finish() {
+            let mut paint = draw::paint(c[0], c[1], c[2], 255);
+            paint.anti_alias = false;
+            pixmap.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None);
+            pixmap.stroke_path(&path, &paint, &draw::stroke(0.8, false), Transform::identity(), None);
+        }
+    }
+    save(&pixmap, path)
+}
+
+/// A picture's pixels: its background is opaque, so the premultiplied pixels are the straight ones.
+pub fn save(pixmap: &Pixmap, path: &std::path::Path) -> Result<(), String> {
+    image::save_buffer(path, pixmap.data(), pixmap.width(), pixmap.height(), image::ColorType::Rgba8)
+        .map_err(|e| format!("{}: {e}", path.display()))
+}
+
+/// The place's meshes as a glTF mesh per kind: storey 0, the storeys' tops and their shells.
+pub fn gltf_meshes(
+    cells: &BTreeMap,
+    inputs: &BTreeMap,
+    centre: GlobalPoint,
+    size_m: f64,
+) -> Vec {
+    let base = inputs.get(&CellKey::of(centre)).and_then(|i| i.terrain.height(centre)).unwrap_or(0.0);
+    let mut ground =
+        gltf::Mesh { name: "storey 0".into(), positions: Vec::new(), colours: Vec::new(), indices: Vec::new() };
+    let mut shell = gltf::Mesh {
+        name: "storeys and shells".into(),
+        positions: Vec::new(),
+        colours: Vec::new(),
+        indices: Vec::new(),
+    };
+    for (v, colour, two_sided) in triangles(cells, inputs, centre, base, size_m / 2.0) {
+        let m = if two_sided { &mut ground } else { &mut shell };
+        for p in v {
+            m.indices.push(m.positions.len() as u32);
+            // glTF: x east, y up, z south.
+            m.positions.push([p[0] as f32, p[2] as f32, -p[1] as f32]);
+            m.colours.push(colour);
+        }
+    }
+    vec![ground, shell]
+}
diff --git a/host/obc-ground-plan/src/cell.rs b/host/obc-ground-plan/src/cell.rs
new file mode 100644
index 0000000000..2ba97b658d
--- /dev/null
+++ b/host/obc-ground-plan/src/cell.rs
@@ -0,0 +1,132 @@
+//! The build of one cell from its request bytes, stage by stage, with the time of each stage.
+
+use crate::faces::{records, EdgeKind, FacePlan, Rules, Storeys, OUTSIDE};
+use crate::frame::CellKey;
+use crate::graph::{self, WayGraph};
+use crate::mesh;
+use crate::tile::TileCache;
+use crate::transport::{fnv, Request};
+use crate::CellInput;
+
+/// The stages in their order: `times` holds one time per stage.
+pub const STAGES: [&str; 3] = ["input", "graph", "faces"];
+
+/// A built cell: what its request held, its plan and the time of each stage in milliseconds.
+#[derive(Clone, Debug)]
+pub struct CellBuild {
+    pub key: CellKey,
+    /// The digest of the request bytes, for a build from them.
+    pub request: Option,
+    pub tiles: usize,
+    pub pages: usize,
+    pub graph: WayGraph,
+    /// The faces of level 0.
+    pub faces: FacePlan,
+    /// The near records of the faces (`records::Built::near`): the block that the GPU reads and whose
+    /// labels the mesh's corners name.
+    pub records: Vec,
+    /// The far block of the records' lines (`records::far`), or why it is refused: the records stand
+    /// either way.
+    pub far: Result, String>,
+    pub times: Vec,
+    /// The storeys over the ground, whose records `records` holds after storey 0's; none unless asked
+    /// (`build_storeys`).
+    pub storeys: Storeys,
+    /// With the storeys: the time of the storeys' faces and records (ms).
+    pub storey_time: f64,
+}
+
+/// Builds the cell of a request: `input` decodes the request, the feature tiles and the terrain;
+/// `graph` builds the way graph; `faces` builds the faces of level 0, their records and the far block
+/// in one pass.
+/// `now` gives milliseconds; no output byte depends on it, so a caller that does not time passes
+/// `&mut || 0.0`.
+pub fn build_cell(bytes: &[u8], rules: &Rules, now: &mut dyn FnMut() -> f64) -> Result {
+    build_cell_with(bytes, &mut TileCache::new(4), rules, now)
+}
+
+/// `build_cell` with the tiles that `cache` holds parsed: a caller that keeps one cache from cell to
+/// cell parses each tile once. A cache keys a tile by its column and row, so it serves one feature
+/// archive.
+pub fn build_cell_with(
+    bytes: &[u8],
+    cache: &mut TileCache,
+    rules: &Rules,
+    now: &mut dyn FnMut() -> f64,
+) -> Result {
+    let start = now();
+    let request = Request::decode(bytes)?;
+    Ok(CellBuild { request: Some(fnv(bytes)), ..stages(start, request, cache, rules, now)?.0 })
+}
+
+/// `build_cell_with` of a request that is not encoded, without its digest. A tile that the request
+/// lacks and `cache` does not hold counts as absent.
+pub fn build_request(
+    request: Request,
+    cache: &mut TileCache,
+    rules: &Rules,
+    now: &mut dyn FnMut() -> f64,
+) -> Result {
+    Ok(stages(now(), request, cache, rules, now)?.0)
+}
+
+/// `build_request`, then the storeys over the ground: their faces, their records after storey 0's in the one block
+/// (`records::storeys`) and what their shells read. The graph splits each way at the end lines that the tiles carry
+/// (`graph::level_tags::split`). Storey 0's faces and far block are those of `build_request`.
+pub fn build_storeys(
+    request: Request,
+    cache: &mut TileCache,
+    rules: &Rules,
+    now: &mut dyn FnMut() -> f64,
+) -> Result {
+    let (mut b, input) = stages(now(), request, cache, rules, now)?;
+    let start = now();
+    b.storeys = records::storeys(&b.graph, &input, rules, b.key, &mut b.records);
+    let plan = &b.faces;
+    let sharp = |f: u32| f != OUTSIDE && mesh::params::sharp(plan.faces[f as usize].rule);
+    b.storeys.ground_ends = (plan.edges.iter())
+        .filter(|e| {
+            e.kind == EdgeKind::DeckEdge && e.left != OUTSIDE && e.right != OUTSIDE && (sharp(e.left) || sharp(e.right))
+        })
+        .flat_map(|e| mesh::points::edge_points(plan, e, b.key.origin().y as f64))
+        .collect();
+    b.storey_time = now() - start;
+    Ok(b)
+}
+
+/// The far block of a request's cell alone (`records::far_block`): the stages input and graph of
+/// `build_request`, then the records' lines without their faces. It is the `far` of a full build of
+/// the request.
+pub fn far_request(request: Request, cache: &mut TileCache, rules: &Rules) -> Result, String> {
+    let key = request.key;
+    let input = request.input(cache)?;
+    records::far_block(&cell_graph(key, &input, rules), &input, rules, key)
+}
+
+/// The way graph of a cell: with the storeys, its ways follow the levels that the tiles carry.
+pub fn cell_graph(key: CellKey, input: &CellInput, rules: &Rules) -> WayGraph {
+    if cfg!(feature = "storeys") {
+        graph::build_levelled(key, input, &rules.sections, rules.structures.edge_band_m)
+    } else {
+        graph::build(key, input, &rules.sections)
+    }
+}
+
+fn stages(
+    start: f64,
+    request: Request,
+    cache: &mut TileCache,
+    rules: &Rules,
+    now: &mut dyn FnMut() -> f64,
+) -> Result<(CellBuild, CellInput), String> {
+    let (key, tiles, pages) = (request.key, request.tiles.len(), request.pages.len());
+    let input = request.input(cache)?;
+    let read = now();
+    let graph = cell_graph(key, &input, rules);
+    let built = now();
+    let (faces, records, far) = records::near(&graph, &input, rules, key, 0, true);
+    let times = vec![read - start, built - read, now() - built];
+    let records = records.words;
+    let (storeys, storey_time) = (Storeys::default(), 0.0);
+    Ok((CellBuild { key, request: None, tiles, pages, graph, faces, records, far, times, storeys, storey_time }, input))
+}
diff --git a/host/obc-ground-plan/src/debug.rs b/host/obc-ground-plan/src/debug.rs
new file mode 100644
index 0000000000..d5910ccef9
--- /dev/null
+++ b/host/obc-ground-plan/src/debug.rs
@@ -0,0 +1,103 @@
+//! The palette of the debug pictures: the debug tool and the viewer's debug draw read these colours
+//! through `transport::vocabulary`, so both show one plan in the same colours.
+
+use crate::faces::{EdgeKind, Surface};
+use crate::graph::{CrossingKind, Family};
+
+pub type Rgb = (u8, u8, u8);
+/// A colour with its alpha.
+pub type Rgba = (u8, u8, u8, u8);
+
+/// The families in code order, with their colours.
+pub const FAMILIES: [(Family, &str, Rgb); 4] = [
+    (Family::Road, "road", (150, 100, 20)),
+    (Family::Path, "path", (190, 40, 40)),
+    (Family::Rail, "rail", (30, 30, 30)),
+    (Family::Water, "water", (30, 90, 220)),
+];
+pub const LINK: Rgb = (230, 0, 0);
+pub const SYNTHETIC_DECK: Rgb = (250, 140, 0);
+pub const JUNCTION: Rgb = (20, 120, 40);
+pub const GUEST_ARM: Rgb = (140, 40, 160);
+pub const JOINT: Rgb = (0, 0, 0);
+pub const END: Rgb = (0, 0, 0);
+pub const CROSSING: Rgb = (255, 255, 255);
+
+/// The crossing kinds in code order, with their letters.
+pub const CROSSINGS: [(CrossingKind, char); 9] = [
+    (CrossingKind::Deck, 'D'),
+    (CrossingKind::Culvert, 'C'),
+    (CrossingKind::Ford, 'F'),
+    (CrossingKind::PipeInStones, 'P'),
+    (CrossingKind::SteppingStones, 'S'),
+    (CrossingKind::Footbridge, 'B'),
+    (CrossingKind::LevelCrossing, 'L'),
+    (CrossingKind::Stacked, 'X'),
+    (CrossingKind::Bore, 'T'),
+];
+
+pub fn family_colour(family: Family) -> Rgb {
+    FAMILIES.iter().find(|f| f.0 == family).map_or((0, 0, 0), |f| f.2)
+}
+
+/// `#rrggbbaa`.
+pub fn hex_alpha((r, g, b, a): Rgba) -> String {
+    format!("{}{a:02x}", hex((r, g, b)))
+}
+
+/// `#rrggbb`.
+pub fn hex((r, g, b): Rgb) -> String {
+    format!("#{r:02x}{g:02x}{b:02x}")
+}
+
+/// The surfaces in code order, with their fills; a terrain face gets none.
+pub const SURFACES: [(Surface, &str, Option); 13] = [
+    (Surface::Terrain, "terrain", None),
+    (Surface::Slope, "slope", Some((205, 190, 120, 110))),
+    (Surface::Carriageway, "carriageway", Some((105, 105, 110, 255))),
+    (Surface::Shoulder, "shoulder", Some((190, 182, 160, 255))),
+    (Surface::Verge, "verge", Some((140, 185, 110, 255))),
+    (Surface::CornerFill, "corner_fill", Some((230, 160, 50, 255))),
+    (Surface::Crossing, "crossing", Some((210, 60, 60, 255))),
+    (Surface::RailBed, "rail_bed", Some((125, 95, 75, 255))),
+    (Surface::Platform, "platform", Some((200, 200, 205, 255))),
+    (Surface::Water, "water", Some((40, 110, 220, 255))),
+    (Surface::Bank, "bank", Some((95, 150, 120, 255))),
+    (Surface::Zone, "zone", Some((150, 110, 190, 255))),
+    (Surface::DeckEdge, "deck_edge", Some((120, 175, 215, 255))),
+];
+/// The fill of a junction's face where it differs from its surface's.
+pub const JUNCTION_SURFACES: [(Surface, Rgba); 2] =
+    [(Surface::Carriageway, (150, 90, 190, 255)), (Surface::RailBed, (165, 110, 80, 255))];
+
+/// The edge kinds in code order, with their colours.
+pub const EDGES: [(EdgeKind, &str, Rgb); 7] = [
+    (EdgeKind::Continuous, "continuous", (20, 20, 20)),
+    (EdgeKind::Kerb, "kerb", (255, 255, 255)),
+    (EdgeKind::Wall, "wall", (220, 30, 30)),
+    (EdgeKind::Headwall, "headwall", (255, 140, 0)),
+    (EdgeKind::Portal, "portal", (160, 0, 200)),
+    (EdgeKind::DeckEdge, "deck_edge", (0, 170, 220)),
+    (EdgeKind::CellBorder, "cell_border", (0, 0, 0)),
+];
+
+/// The fill of a face, or None.
+pub fn face_colour(surface: Surface, junction: bool) -> Option {
+    let own = JUNCTION_SURFACES.iter().find(|j| junction && j.0 == surface).map(|j| j.1);
+    own.or(SURFACES[surface as usize].2)
+}
+
+pub fn edge_colour(kind: EdgeKind) -> Rgb {
+    EDGES[kind as usize].2
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn the_tables_are_in_code_order() {
+        assert!(SURFACES.iter().enumerate().all(|(i, s)| s.0 as usize == i));
+        assert!(EDGES.iter().enumerate().all(|(i, e)| e.0 as usize == i));
+    }
+}
diff --git a/host/obc-ground-plan/src/faces/check.rs b/host/obc-ground-plan/src/faces/check.rs
new file mode 100644
index 0000000000..497e4a7139
--- /dev/null
+++ b/host/obc-ground-plan/src/faces/check.rs
@@ -0,0 +1,956 @@
+//! The checks of a face plan: the planar partition (check 1) and the cells' shared borders (check 2).
+
+use std::collections::BTreeMap;
+
+use i_overlay::core::fill_rule::FillRule;
+use i_overlay::core::overlay::{ContourDirection, IntOverlayOptions, Overlay};
+use i_overlay::core::overlay_rule::OverlayRule;
+use i_overlay::core::solver::{Precision, Solver, Strategy};
+use i_overlay::i_float::int::point::IntPoint;
+
+use super::geom::{area2, closest, cross, winding, P};
+use super::types::{Face, FacePlan, Owner, Surface, OUTSIDE};
+use crate::frame::{metres_per_unit, CELL_UNITS};
+use crate::graph::{Level, WayGraph};
+
+/// A broken invariant.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Fault {
+    pub check: &'static str,
+    pub what: String,
+}
+
+fn ring_points(plan: &FacePlan, ring: &[u32]) -> Vec

{ + ring.iter().map(|&v| plan.vertices[v as usize]).collect() +} + +/// Whether segments ab and cd meet anywhere but at a shared end. +fn meet(a: P, b: P, c: P, d: P) -> bool { + let (d1, d2, d3, d4) = (cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b)); + if d1.signum() * d2.signum() < 0 && d3.signum() * d4.signum() < 0 { + return true; + } + let on = |p: P, q: P, x: P| { + cross(p, q, x) == 0 + && x[0] >= p[0].min(q[0]) + && x[0] <= p[0].max(q[0]) + && x[1] >= p[1].min(q[1]) + && x[1] <= p[1].max(q[1]) + }; + let shared = |x: P| x == c || x == d; + (on(c, d, a) && !shared(a)) + || (on(c, d, b) && !shared(b)) + || (on(a, b, c) && c != a && c != b) + || (on(a, b, d) && d != a && d != b) +} + +/// Whether a ring is simple: no repeated vertex and no two segments that meet but at a shared end. +fn simple(ring: &[P]) -> bool { + let n = ring.len(); + let mut sorted = ring.to_vec(); + sorted.sort(); + if sorted.windows(2).any(|w| w[0] == w[1]) { + return false; + } + // Segments by the grid cells of their boxes; each pair meets once in some cell. + const SHIFT: u32 = 10; + let mut cells: Vec<(i64, usize)> = Vec::new(); + for i in 0..n { + let (a, b) = (ring[i], ring[(i + 1) % n]); + for x in (a[0].min(b[0]) >> SHIFT)..=(a[0].max(b[0]) >> SHIFT) { + for y in (a[1].min(b[1]) >> SHIFT)..=(a[1].max(b[1]) >> SHIFT) { + cells.push(((i64::from(x) << 32) ^ i64::from(y as u32), i)); + } + } + } + cells.sort_unstable(); + for group in cells.chunk_by(|x, y| x.0 == y.0) { + for (k, &(_, i)) in group.iter().enumerate() { + for &(_, j) in &group[k + 1..] { + if (i + 1) % n == j || (j + 1) % n == i { + continue; + } + if meet(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n]) { + return false; + } + } + } + } + true +} + +/// Check 1: the faces tile the window exactly, every ring is simple and rightly turned, and every ring +/// segment is an edge with the face on its side. +pub fn partition(plan: &FacePlan, window: [i32; 4]) -> Vec { + let mut faults = Vec::new(); + let mut fault = |what: String| faults.push(Fault { check: "1", what }); + let [x0, y0, x1, y1] = window; + let want = 2 * i128::from(x1 - x0) * i128::from(y1 - y0); + let mut sum = 0i128; + let mut edges: BTreeMap<(u32, u32), (u32, u32)> = BTreeMap::new(); + for e in &plan.edges { + if edges.insert((e.a, e.b), (e.left, e.right)).is_some() || e.a >= e.b || e.left == e.right { + fault(format!("edge {}-{}: twice, unordered or one face on both sides", e.a, e.b)); + } + // Only the window's edge has no face beyond it. + let (a, b) = (plan.vertices[e.a as usize], plan.vertices[e.b as usize]); + let rim = (a[0] == b[0] && (a[0] == x0 || a[0] == x1)) || (a[1] == b[1] && (a[1] == y0 || a[1] == y1)); + if (e.left == OUTSIDE || e.right == OUTSIDE) && !rim { + fault(format!("edge {a:?}-{b:?}: no face on one side inside the window")); + } + } + let mut seen: BTreeMap<(u32, u32), u32> = BTreeMap::new(); + for f in &plan.faces { + for (k, ring) in f.rings.iter().enumerate() { + let pts = ring_points(plan, ring); + let a = area2(&pts); + sum += a; + if (k == 0) != (a > 0) || a == 0 { + fault(format!("face {} ring {k}: area {a}", f.id)); + } + if !simple(&pts) { + fault(format!("face {} ring {k}: not simple", f.id)); + } + for i in 0..ring.len() { + let (u, v) = (ring[i], ring[(i + 1) % ring.len()]); + let side = match edges.get(&(u.min(v), u.max(v))) { + Some(&(left, right)) => { + if u < v { + left + } else { + right + } + } + None => OUTSIDE, + }; + if side != f.id { + fault(format!("face {} ring {k}: segment {u}-{v} is no edge with the face on its side", f.id)); + } + *seen.entry((u.min(v), u.max(v))).or_default() += 1; + } + } + } + for (&(a, b), &(left, right)) in &edges { + let want = if left == OUTSIDE || right == OUTSIDE { 1 } else { 2 }; + if seen.get(&(a, b)).copied().unwrap_or(0) != want { + fault(format!("edge {a}-{b}: in {:?} rings, not {want}", seen.get(&(a, b)))); + } + } + if sum != want { + fault(format!("the faces' areas sum to {sum}, the window's is {want}")); + } + let contours: Vec> = plan + .faces + .iter() + .flat_map(|f| &f.rings) + .map(|r| ring_points(plan, r).into_iter().map(|p| IntPoint::new(p[0], p[1])).collect()) + .collect(); + let options = IntOverlayOptions { + preserve_input_collinear: true, + output_direction: ContourDirection::CounterClockwise, + preserve_output_collinear: true, + min_output_area: 0, + ogc: false, + }; + let solver = Solver { strategy: Strategy::Frag, precision: Precision::ABSOLUTE, multithreading: None }; + let union = Overlay::from_subj_and_clip_custom(&contours, &Vec::>::new(), options, solver) + .overlay(OverlayRule::Subject, FillRule::NonZero); + let union: i128 = union.iter().flatten().map(|c| area2(&c.iter().map(|p| [p.x, p.y]).collect::>())).sum(); + if union != want { + fault(format!("the union of the faces has area {union}, the window {want}")); + } + faults +} + +/// A face part narrower than this many units (about 6 mm) is a numerical leftover: no rule shapes +/// geometry that thin, except toward a taper's tip. +const SLIVER: f64 = 4.0; + +/// A thin place is a taper's tip where the boundary joins its two sides within the walk of a wedge +/// this sharp: two ways that part at a shallow angle, a band that tapers out, a round that runs into +/// an edge. +const TAPER_DEG: f64 = 1.0; + +/// An edge this short between two turns of opposite sense, each sharper than `JOG_DEG`, is a jog. +const JOG: f64 = 2.0; +const JOG_DEG: f64 = 60.0; + +/// The kinds of geometry that no rule shapes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum ArtefactKind { + /// Two places of a face's boundary closer than `SLIVER` that no taper joins. + Sliver, + /// A 1- or 2-unit step in an edge. + Jog, + /// A way's or junction's face that lies across the centreline of an unrelated way of its family + /// and of an equal or a stronger class. + Shard, + /// A way's or junction's face away from the cell's border that holds none of its own ways' + /// centrelines, and is small or borders no face that holds one. + Fragment, + /// A border between related carriageway faces (a junction and its arm, two junctions on a link, + /// two ways that overlap) that is no straight seam. The owner accepts it in the plan: it is no + /// fault of check 1. + BentBorder, +} + +/// One artefact of a face, at a point in cell units. +#[derive(Clone, Debug, PartialEq)] +pub struct Artefact { + pub face: u32, + pub at: [i32; 2], + pub kind: ArtefactKind, +} + +fn len(a: P, b: P) -> f64 { + let (x, y) = (f64::from(b[0] - a[0]), f64::from(b[1] - a[1])); + (x * x + y * y).sqrt() +} + +/// Whether segments ab and cd cross at a point inside both. +fn crosses(a: P, b: P, c: P, d: P) -> bool { + let (d1, d2, d3, d4) = (cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b)); + d1.signum() * d2.signum() < 0 && d3.signum() * d4.signum() < 0 +} + +/// The artefacts of a plan of level 0. Edges on the cell's border are no boundary: the face goes on +/// in the next cell. +pub fn artefacts(plan: &FacePlan, graph: &WayGraph) -> Vec { + let c = CELL_UNITS as i32; + let border = |a: P, b: P| (a[0] == b[0] && (a[0] == 0 || a[0] == c)) || (a[1] == b[1] && (a[1] == 0 || a[1] == c)); + let on_line = |p: P| p[0] == 0 || p[0] == c || p[1] == 0 || p[1] == c; + let sin_taper = libm::sin(TAPER_DEG.to_radians() / 2.0); + let sin_jog = libm::sin(JOG_DEG.to_radians()); + let mut out = Vec::new(); + for f in &plan.faces { + let rings: Vec> = f.rings.iter().map(|r| ring_points(plan, r)).collect(); + // Segments: (ring, index, start along the ring, ring length). + let mut segs: Vec<(usize, usize, f64, f64)> = Vec::new(); + for (k, ring) in rings.iter().enumerate() { + let n = ring.len(); + let total: f64 = (0..n).map(|i| len(ring[i], ring[(i + 1) % n])).sum(); + let mut s = 0.0; + for i in 0..n { + let (prev, a, b, next) = (ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n], ring[(i + 2) % n]); + let l = len(a, b); + if !border(a, b) { + segs.push((k, i, s, total)); + let turn = |o: P, p: P, q: P| cross(o, p, q) as f64 / (len(o, p) * len(p, q)); + let (t0, t1) = (turn(prev, a, b), turn(a, b, next)); + if l <= JOG && !on_line(a) && !on_line(b) && t0 * t1 < 0.0 && t0.abs().min(t1.abs()) > sin_jog { + out.push(Artefact { face: f.id, at: a, kind: ArtefactKind::Jog }); + } + } + s += l; + } + } + // Pairs by a grid of 64 units over the segments' boxes. + let mut grid: BTreeMap<(i32, i32), Vec> = BTreeMap::new(); + for (id, &(k, i, _, _)) in segs.iter().enumerate() { + let (a, b) = (rings[k][i], rings[k][(i + 1) % rings[k].len()]); + let g = |v: i32| v.div_euclid(64); + let pad = SLIVER as i32; + for x in g(a[0].min(b[0]) - pad)..=g(a[0].max(b[0]) + pad) { + for y in g(a[1].min(b[1]) - pad)..=g(a[1].max(b[1]) + pad) { + grid.entry((x, y)).or_default().push(id); + } + } + } + let mut seen = std::collections::BTreeSet::new(); + for list in grid.values() { + for (x, &i) in list.iter().enumerate() { + for &j in &list[x + 1..] { + if !seen.insert((i.min(j), i.max(j))) { + continue; + } + let (ki, ii, si, ti) = segs[i]; + let (kj, ij, sj, _) = segs[j]; + let (ri, rj) = (&rings[ki], &rings[kj]); + let (a, b, cc, d) = (ri[ii], ri[(ii + 1) % ri.len()], rj[ij], rj[(ij + 1) % rj.len()]); + let (dist, s, t) = closest(a, b, cc, d); + if dist >= SLIVER || dist == 0.0 { + continue; + } + if ki == kj { + let walk = (si + s * len(a, b) - (sj + t * len(cc, d))).abs(); + if walk.min(ti - walk) <= dist / sin_taper { + continue; + } + } + // The middle of pq must lie in the face. + let p = + [f64::from(a[0]) + s * f64::from(b[0] - a[0]), f64::from(a[1]) + s * f64::from(b[1] - a[1])]; + let q = [ + f64::from(cc[0]) + t * f64::from(d[0] - cc[0]), + f64::from(cc[1]) + t * f64::from(d[1] - cc[1]), + ]; + let mid = [libm::round(p[0] + q[0]) as i64, libm::round(p[1] + q[1]) as i64]; + if winding(&rings, mid) == 0 { + continue; + } + out.push(Artefact { face: f.id, at: [p[0] as i32, p[1] as i32], kind: ArtefactKind::Sliver }); + } + } + } + } + out.extend(owner_artefacts(plan, graph)); + out.extend(bent_borders(plan, graph)); + out +} + +/// The borders between a way's carriageway and the face of a point where it meets another way, or +/// two such faces, that are no straight seam: one per border chain, on the face of the weaker rank. +/// Two legs of one way meet on their medial line, which bends by design. +fn bent_borders(plan: &FacePlan, graph: &WayGraph) -> Vec { + let carriageway = |f: u32| f != OUTSIDE && plan.faces[f as usize].surface == Surface::Carriageway; + let ways: Vec> = plan.faces.iter().map(|f| own_ways(f, graph)).collect(); + let points = + || graph.junctions.iter().map(|j| j.arms.as_slice()).chain(graph.joints.iter().map(|j| j.arms.as_slice())); + let related = |f: u32, g: u32| { + let (a, b) = (&ways[f as usize], &ways[g as usize]); + a.iter().any(|w| b.contains(w)) + || points().any(|arms| arms.iter().any(|x| a.contains(&x.way)) && arms.iter().any(|x| b.contains(&x.way))) + }; + let mut by_pair: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new(); + for e in plan.edges.iter().filter(|e| carriageway(e.left) && carriageway(e.right)) { + by_pair.entry((e.left.min(e.right), e.left.max(e.right))).or_default().push((e.a, e.b)); + } + let mut out = Vec::new(); + let legs = |f: u32, g: u32| { + let (a, b) = (&plan.faces[f as usize], &plan.faces[g as usize]); + matches!(a.owner, Owner::Way(_)) && a.owner == b.owner && a.legs[0] != b.legs[0] + }; + for ((f, g), mut edges) in by_pair { + if !related(f, g) || legs(f, g) { + continue; + } + // Each chain of edges is one border. + while let Some(first) = edges.pop() { + let mut chain = vec![first.0, first.1]; + let mut grew = true; + while grew { + grew = false; + edges.retain(|&(a, b)| { + let joins = chain.contains(&a) || chain.contains(&b); + if joins { + chain.extend([a, b]); + grew = true; + } + !joins + }); + } + let pts: Vec

= chain.iter().map(|&v| plan.vertices[v as usize]).collect(); + let d2 = |p: P, q: P| (i64::from(q[0] - p[0])).pow(2) + (i64::from(q[1] - p[1])).pow(2); + // The chord: the vertex farthest from the first, and the vertex farthest from that one. + let a = *pts.iter().max_by_key(|&&q| d2(pts[0], q)).unwrap(); + let b = *pts.iter().max_by_key(|&&q| d2(a, q)).unwrap(); + let chord = len(a, b); + if chord == 0.0 { + continue; + } + let at = *pts.iter().max_by_key(|&&q| cross(a, b, q).unsigned_abs()).unwrap(); + // Within the plan's precision a seam's vertices lie up to a grid step off its line. + if cross(a, b, at).unsigned_abs() as f64 / chord > f64::from(2 * super::slice::PRECISION) { + let weak = if plan.faces[f as usize].rank >= plan.faces[g as usize].rank { f } else { g }; + out.push(Artefact { face: weak, at, kind: ArtefactKind::BentBorder }); + } + } + } + out +} + +/// A face of a way or a junction under this area that holds none of its ways' centrelines is a +/// fragment wherever it lies: no rule leaves so small a piece of a way. +const FRAGMENT_M2: f64 = 0.01; + +/// The ways of a way's or a junction's face. A joint's face takes the label of one of its two ways +/// and covers both. +fn own_ways(f: &Face, graph: &WayGraph) -> Vec { + match f.owner { + Owner::Terrain | Owner::Platform(_) => Vec::new(), + Owner::Way(w) => { + let joined = graph.joints.iter().filter(|j| j.arms.iter().any(|a| a.way == w)); + let mut ways: Vec = + std::iter::once(w).chain(joined.flat_map(|j| j.arms.iter().map(|a| a.way))).collect(); + ways.sort_unstable(); + ways.dedup(); + ways + } + Owner::Junction(j) => graph.junctions[j as usize].arms.iter().map(|a| a.way).collect(), + } +} + +/// Where the centreline of way `w` enters the rings: a sample inside them or a segment across an +/// edge. +fn enters(rings: &[Vec

], graph: &WayGraph, w: u32) -> Option

{ + let bbox = rings[0].iter().fold([i32::MAX, i32::MAX, i32::MIN, i32::MIN], |b, p| { + [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])] + }); + let off = |a: P, b: P| { + a[0].max(b[0]) < bbox[0] || a[0].min(b[0]) > bbox[2] || a[1].max(b[1]) < bbox[1] || a[1].min(b[1]) > bbox[3] + }; + let way = &graph.ways[w as usize]; + let line = &graph.samples[way.samples.start as usize..way.samples.end as usize]; + for k in 0..line.len() { + let a = line[k].pos; + if !off(a, a) && winding(rings, [2 * i64::from(a[0]), 2 * i64::from(a[1])]) != 0 { + return Some(a); + } + let Some(b) = line.get(k + 1).map(|s| s.pos) else { break }; + if off(a, b) { + continue; + } + for ring in rings { + for i in 0..ring.len() { + if crosses(a, b, ring[i], ring[(i + 1) % ring.len()]) { + return Some(ring[i]); + } + } + } + } + None +} + +/// The shards and fragments of the ways' and junctions' faces. +fn owner_artefacts(plan: &FacePlan, graph: &WayGraph) -> Vec { + let c = CELL_UNITS as i32; + let mpu = metres_per_unit(plan.cell.origin().y + CELL_UNITS / 2); + let rings: Vec>> = + plan.faces.iter().map(|f| f.rings.iter().map(|r| ring_points(plan, r)).collect()).collect(); + let own: Vec> = plan.faces.iter().map(|f| own_ways(f, graph)).collect(); + let holds: Vec> = (0..plan.faces.len()) + .map(|i| own[i].iter().copied().filter(|&w| enters(&rings[i], graph, w).is_some()).collect()) + .collect(); + let mut next: Vec> = vec![Vec::new(); plan.faces.len()]; + for e in plan.edges.iter().filter(|e| e.left != OUTSIDE && e.right != OUTSIDE) { + next[e.left as usize].push(e.right); + next[e.right as usize].push(e.left); + } + let mut out = Vec::new(); + for f in plan.faces.iter().filter(|f| !own[f.id as usize].is_empty()) { + let i = f.id as usize; + let r = &rings[i]; + let on_border = r[0].iter().any(|p| p[0] == 0 || p[0] == c || p[1] == 0 || p[1] == c); + if holds[i].is_empty() && !on_border { + let small = area2(&r[0]) as f64 / 2.0 * mpu * mpu < FRAGMENT_M2; + let joined = next[i].iter().any(|&n| holds[n as usize].iter().any(|w| own[i].contains(w))); + if small || !joined { + out.push(Artefact { face: f.id, at: r[0][0], kind: ArtefactKind::Fragment }); + } + } + // Ways that meet one of the face's own ways at a junction or a joint. + let Some(look) = f.material.or(own[i].first().copied()).map(|w| &graph.ways[w as usize]) else { continue }; + let mut related: Vec = own[i].clone(); + let points = + graph.junctions.iter().map(|j| j.arms.as_slice()).chain(graph.joints.iter().map(|j| j.arms.as_slice())); + for arms in points { + if arms.iter().any(|a| own[i].contains(&a.way)) { + related.extend(arms.iter().map(|a| a.way)); + } + } + for (w, way) in graph.ways.iter().enumerate() { + let w = w as u32; + if way.level != Level::Ground + || way.family != look.family + || way.class > look.class + || related.contains(&w) + || f.crossing == Some(w) + { + continue; + } + if let Some(at) = enters(r, graph, w) { + out.push(Artefact { face: f.id, at, kind: ArtefactKind::Shard }); + break; + } + } + } + out +} + +/// Per feature of a cell's input, the name that every cell gives it: its first part's tile and its +/// index there. +pub fn feature_names(input: &crate::CellInput) -> Vec<[u32; 3]> { + (input.features.iter()) + .map(|f| { + let (x, y) = f.parts.first().map_or((0, 0), |p| p.tile); + [x, y, f.index] + }) + .collect() +} + +/// A global name of an owner near a point: a way by its class and its sample nearest the point (two +/// cells number ways apart), a junction by its position, a platform by its feature's name +/// (`features`, from `feature_names`). +pub fn owner_name(graph: &WayGraph, features: &[[u32; 3]], owner: Owner, near: [i64; 2]) -> String { + let o = graph.cell.origin(); + let way = |w: u32| { + let way = &graph.ways[w as usize]; + let samples = &graph.samples[way.samples.start as usize..way.samples.end as usize]; + let g = |p: [i32; 2]| [o.x + i64::from(p[0]), o.y + i64::from(p[1])]; + let d = |p: [i64; 2]| (p[0] - near[0]).pow(2) + (p[1] - near[1]).pow(2); + let best = samples.iter().map(|s| g(s.pos)).min_by_key(|&p| (d(p), p)); + format!("way {} {:?}", way.class, best) + }; + match owner { + Owner::Terrain => "terrain".into(), + Owner::Way(w) => way(w), + Owner::Junction(j) => { + let p = graph.junctions[j as usize].pos; + format!("junction {:?}", [o.x + i64::from(p[0]), o.y + i64::from(p[1])]) + } + Owner::Platform(f) => format!("platform {:?}", features[f as usize]), + } +} + +/// The border of a plan on one side of its cell (0 west, 1 north, 2 east, 3 south): its vertices in +/// global positions along the side, and per border segment the attributes of the face inside. +fn border(cell: Cell, side: usize) -> (Vec<[i64; 2]>, Vec<(String, String)>) { + let (plan, graph, features) = cell; + let c = CELL_UNITS as i32; + let o = plan.cell.origin(); + let on = |p: P| match side { + 0 => p[0] == 0 && (0..=c).contains(&p[1]), + 1 => p[1] == 0 && (0..=c).contains(&p[0]), + 2 => p[0] == c && (0..=c).contains(&p[1]), + _ => p[1] == c && (0..=c).contains(&p[0]), + }; + let along = |p: P| if side.is_multiple_of(2) { p[1] } else { p[0] }; + let mut verts: Vec<(i32, u32)> = + (plan.vertices.iter().enumerate()).filter(|(_, &p)| on(p)).map(|(i, &p)| (along(p), i as u32)).collect(); + verts.sort(); + let global = |p: P| [o.x + i64::from(p[0]), o.y + i64::from(p[1])]; + let mut by_pair: BTreeMap<(u32, u32), (u32, u32)> = BTreeMap::new(); + for e in &plan.edges { + by_pair.insert((e.a, e.b), (e.left, e.right)); + } + let mut attrs = Vec::new(); + for w in verts.windows(2) { + let (u, v) = (w[0].1, w[1].1); + let Some(&(left, right)) = by_pair.get(&(u.min(v), u.max(v))) else { + attrs.push(("no edge".into(), String::new())); + continue; + }; + let mid = global(plan.vertices[u as usize]); + let name = |f: u32| { + if f == OUTSIDE { + return "outside".to_string(); + } + let f = &plan.faces[f as usize]; + let way = |x: Option| x.map(|w| owner_name(graph, features, Owner::Way(w), mid)); + format!( + "{:?} {:?} {} {} {:?} {:?}", + f.surface, + f.rule, + f.rank, + owner_name(graph, features, f.owner, mid), + way(f.material), + way(f.crossing) + ) + }; + let inside = |f: u32| f != OUTSIDE && plan.faces[f as usize].inside; + let (i, x) = if inside(left) { (left, right) } else { (right, left) }; + attrs.push((name(i), name(x))); + } + (verts.iter().map(|&(_, i)| global(plan.vertices[i as usize])).collect(), attrs) +} + +/// A cell of check 2: its plan, its graph and its input's `feature_names`. +pub type Cell<'a> = (&'a FacePlan, &'a WayGraph, &'a [[u32; 3]]); + +/// Check 2: cell `b` east of `a` (`east`) or south of it: the same vertices on their shared border, +/// and the same attributes of the faces on each side of each border segment. +pub fn neighbours(a: Cell, b: Cell, east: bool) -> Vec { + let (sa, sb) = if east { (2, 0) } else { (3, 1) }; + let (va, fa) = border(a, sa); + let (vb, fb) = border(b, sb); + let mut faults = Vec::new(); + if va != vb { + let first = va.iter().zip(&vb).position(|(x, y)| x != y); + faults.push(Fault { + check: "2", + what: format!("border vertices differ: {} and {}, first at {first:?}", va.len(), vb.len()), + }); + return faults; + } + // A plan holds its cell square only: the faces on the two sides of the line carry one label. + for (i, (x, y)) in fa.iter().zip(&fb).enumerate() { + if x.0 != y.0 { + faults.push(Fault { check: "2", what: format!("segment {i} at {:?}: {x:?} | {y:?}", va[i]) }); + } + } + faults +} + +/// Concave vertices of one edge closer than this along it form one corner: a polygonal arc or a +/// mapped curve is one corner, not many. +pub const SUPPORT_M: f64 = 1.0; + +/// A corner that turns more than this (radians, one arc step and a half degree) can be a kink: a +/// round's arc meets its edges at less. +pub const CORNER_TURN: f64 = 10.5 * std::f64::consts::PI / 180.0; + +/// A corner whose radius is under this share of the inner radius of the ways that form it is a kink. +pub const KINK_SHARE: f64 = 0.9; + +/// The length of each edge of a ring, from vertex i to i + 1. +fn edge_lengths(ring: &[P]) -> Vec { + let n = ring.len(); + (0..n) + .map(|i| { + let (a, b) = (ring[i], ring[(i + 1) % n]); + libm::hypot(f64::from(b[0] - a[0]), f64::from(b[1] - a[1])) + }) + .collect() +} + +/// The point `dist` from vertex i along the ring (`dir` 1 ahead, n − 1 back), or the last vertex +/// before an edge that is no boundary (a vertex without a turn). +fn along(ring: &[P], edge: &[f64], turn: &[Option], i: usize, dir: usize, dist: f64) -> [f64; 2] { + let n = ring.len(); + let at = |p: P| [f64::from(p[0]), f64::from(p[1])]; + let (mut k, mut d) = (i, 0.0); + loop { + let len = if dir == 1 { edge[k] } else { edge[(k + n - 1) % n] }; + let next = (k + dir) % n; + if d + len >= dist && len > 0.0 { + let t = (dist - d) / len; + let (a, b) = (at(ring[k]), at(ring[next])); + return [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; + } + d += len; + if next == i || turn[next].is_none() { + return at(ring[next]); + } + k = next; + } +} + +/// Whether vertex i of a ring is a place, and the least radius of the corner about it: the +/// concave vertices that turn toward the right past `CORNER_TURN` within the support (`radius`, from +/// `radii`) within `len` along the ring form the corner about i. A place is a concave vertex of it +/// that turns past `CORNER_TURN` by itself, or where none does, the one that turns the most (the +/// first along the ring of equals). Everything reads `len` each way, so a cell decides a place alike +/// wherever its corner runs on. `turn` is None where an edge at the vertex is no boundary. +pub fn place(ring: &[P], turn: &[Option], radius: &[Option], i: usize, len: f64) -> Option { + radius[i]?; + let turn: Vec = turn.iter().map(|t| t.unwrap_or(0.0)).collect(); + if turn[i] >= 0.0 { + return None; + } + let n = ring.len(); + // The corner's vertices within `len` along the ring, each with whether it lies back from i. + let mut about = vec![(i, false)]; + for dir in [n - 1, 1] { + let (mut k, mut s) = (i, 0.0); + for _ in 1..n { + let next = (k + dir) % n; + let (a, b) = (ring[k], ring[next]); + s += libm::hypot(f64::from(b[0] - a[0]), f64::from(b[1] - a[1])); + if s > len || radius[next].is_none() || next == i { + break; + } + about.push((next, dir != 1)); + k = next; + } + } + let r = + (about.iter()).filter(|&&(k, _)| turn[k] < 0.0).filter_map(|&(k, _)| radius[k]).fold(f64::INFINITY, f64::min); + if -turn[i] > CORNER_TURN { + return Some(r); + } + let sharper = |&(k, back): &(usize, bool)| turn[k] < turn[i] || (turn[k] == turn[i] && back); + (!about.iter().any(|a| -turn[a.0] > CORNER_TURN || sharper(a))).then_some(r) +} + +/// The radius at each vertex of a ring that turns toward its right past `CORNER_TURN` within the +/// support about it (None elsewhere): the support over that turn, between the chords from the point +/// half the support back to the vertex and from the vertex to the point half the support ahead. A +/// chord reads a step of the plan's precision as a small change of direction, so a jog at the +/// support's end is no turn. +pub fn radii(ring: &[P], turn: &[Option], support: &dyn Fn(P) -> f64) -> Vec> { + let n = ring.len(); + let edge = edge_lengths(ring); + let at = |p: P| [f64::from(p[0]), f64::from(p[1])]; + let reach = |i: usize, dir: usize| along(ring, &edge, turn, i, dir, support(ring[i]) / 2.0); + (0..n) + .map(|i| { + turn[i]?; + let (p, v, q) = (reach(i, n - 1), at(ring[i]), reach(i, 1)); + let (u, w) = ([v[0] - p[0], v[1] - p[1]], [q[0] - v[0], q[1] - v[1]]); + let t = libm::atan2(u[0] * w[1] - u[1] * w[0], u[0] * w[0] + u[1] * w[1]); + (-t > CORNER_TURN).then(|| support(ring[i]) / -t) + }) + .collect() +} + +/// The signed turn at vertex i of a ring, toward its left positive. +pub fn turn_at(ring: &[P], i: usize) -> f64 { + let n = ring.len(); + let (a, b, c) = (ring[(i + n - 1) % n], ring[i], ring[(i + 1) % n]); + let (x, y) = ([f64::from(b[0] - a[0]), f64::from(b[1] - a[1])], [f64::from(c[0] - b[0]), f64::from(c[1] - b[1])]); + libm::atan2(x[0] * y[1] - x[1] * y[0], x[0] * y[0] + x[1] * y[1]) +} + +/// A corner where a paved face meets land, tighter than the inner radius of the ways that form it, +/// that no round of the plan shaped: its place (its sharpest vertex), and its radius. +#[derive(Clone, Debug, PartialEq)] +pub struct Kink { + pub face: u32, + pub at: [i32; 2], + pub radius_m: f64, +} + +/// One chain of the paved outline: its vertices, the paved face of the edge from each (`OUTSIDE` +/// after the last vertex of an open chain), and whether it closes. +struct Chain { + pts: Vec

, + faces: Vec, + closed: bool, +} + +impl Chain { + /// The paved face at vertex i: of the edge from it, or into it at an open chain's end. + fn face(&self, i: usize) -> u32 { + if self.faces[i] != OUTSIDE { + self.faces[i] + } else { + self.faces[i.saturating_sub(1)] + } + } + + /// The signed turn at each vertex; None at the ends of an open chain. + fn turns(&self) -> Vec> { + let n = self.pts.len(); + (0..n).map(|i| (self.closed || (i > 0 && i + 1 < n)).then(|| turn_at(&self.pts, i))).collect() + } +} + +/// The paved outline of a plan: every edge between a paved face (carriageway, crossing, rail bed) +/// and land, the paved side on its left, walked across the borders of paved faces. Edges on the +/// cell border, to another paved face and to a platform (a wall) are no outline. +fn paved_outline(plan: &FacePlan) -> Vec { + let paved = |f: u32| { + f != OUTSIDE + && matches!(plan.faces[f as usize].surface, Surface::Carriageway | Surface::Crossing | Surface::RailBed) + }; + let land = |f: u32| f != OUTSIDE && !paved(f) && plan.faces[f as usize].surface != Surface::Platform; + // The outline's directed edges from each vertex: (to, the paved face). + let mut from: BTreeMap> = BTreeMap::new(); + let mut into: BTreeMap = BTreeMap::new(); + for e in &plan.edges { + let (a, b, f) = match (paved(e.left) && land(e.right), paved(e.right) && land(e.left)) { + (true, _) => (e.a, e.b, e.left), + (_, true) => (e.b, e.a, e.right), + _ => continue, + }; + from.entry(a).or_default().push((b, f)); + *into.entry(b).or_default() += 1; + } + let pt = |v: u32| plan.vertices[v as usize]; + // At a vertex with more than one way on, the outline takes the first clockwise from the way back. + let next = |prev: u32, v: u32, from: &BTreeMap>| -> Option<(u32, u32)> { + let list = from.get(&v)?; + let (o, back) = (pt(v), pt(prev)); + let ang = |q: P| libm::atan2(f64::from(q[1] - o[1]), f64::from(q[0] - o[0])); + let a0 = ang(back); + let tau = 2.0 * std::f64::consts::PI; + list.iter().copied().min_by(|x, y| { + let dx = (a0 - ang(pt(x.0))).rem_euclid(tau); + let dy = (a0 - ang(pt(y.0))).rem_euclid(tau); + dx.total_cmp(&dy).then(x.0.cmp(&y.0)) + }) + }; + let mut used: std::collections::BTreeSet<(u32, u32)> = Default::default(); + // Chains from the outline's open ends first (at the cell border), then the closed cycles. + let starts: Vec = + (from.keys().copied().filter(|v| !into.contains_key(v))).chain(from.keys().copied()).collect(); + let mut out = Vec::new(); + for s in starts { + let Some(&(b0, f0)) = from[&s].iter().find(|&&(b, _)| !used.contains(&(s, b))) else { continue }; + // The chain: its vertices and the paved face of the edge from each. + let mut chain = vec![(s, f0)]; + let (mut prev, mut v) = (s, b0); + used.insert((s, b0)); + let mut closed = false; + loop { + if v == s { + closed = true; + break; + } + let Some((w, f)) = next(prev, v, &from).filter(|&(w, _)| !used.contains(&(v, w))) else { + chain.push((v, OUTSIDE)); + break; + }; + used.insert((v, w)); + chain.push((v, f)); + (prev, v) = (v, w); + } + if chain.len() >= 3 { + out.push(Chain { + pts: chain.iter().map(|&(v, _)| pt(v)).collect(), + faces: chain.iter().map(|&(_, f)| f).collect(), + closed, + }); + } + } + out +} + +/// The kinks of a plan of level 0. Along the paved outline (`paved_outline`), a place (`place`, as +/// the outline rounds decide it) whose corner's radius is under `KINK_SHARE` of the least +/// `inner_radius_m` of the ways whose carriageway edge runs through it is a kink, unless it lies on +/// the circle of a round of the plan. +pub fn kinks(plan: &FacePlan, graph: &WayGraph, input: &crate::CellInput, rules: &super::Rules) -> Vec { + let mpu = metres_per_unit(plan.cell.origin().y + CELL_UNITS / 2); + let lines = super::level_lines(graph, input, rules, plan.cell, plan.level); + let reach = rules.plan.extent_m / 2.0 / mpu; + // A round shapes a corner whose own place lies on its circle: within the cut that a round may + // make into its arms (`sag_plan_m`) and the plan's precision. + let rounded = |q: P, sag: f64| { + let tol = sag + f64::from(2 * super::slice::PRECISION) * mpu; + plan.corners.iter().any(|c| (len(c.centre, q) * mpu - c.radius_m).abs() <= tol) + }; + let mut out = Vec::new(); + for chain in paved_outline(plan) { + let pts = &chain.pts; + let turn = chain.turns(); + let radius = radii(pts, &turn, &|_| SUPPORT_M / mpu); + for k in 0..pts.len() { + let Some(r) = place(pts, &turn, &radius, k, reach) else { continue }; + let Some((r_in, sag)) = super::outline::at_corner(&lines, pts[k]) else { continue }; + let radius_m = r * mpu; + if radius_m < KINK_SHARE * r_in && !rounded(pts[k], sag) { + out.push(Kink { face: chain.face(k), at: pts[k], radius_m }); + } + } + } + out +} + +/// A vertex of a short feature lies this far off the outline's line before it or after it: more +/// than the plan's precision can bend an edge. +pub const SHORT_M: f64 = 0.02; + +/// A step, a pocket or a needle of the paved outline: a place where the outline turns sharply but +/// runs on in its direction within the support, so the kink measure sees no corner. +#[derive(Clone, Debug, PartialEq)] +pub struct ShortFeature { + pub face: u32, + pub at: [i32; 2], + /// The greatest distance of its vertices from the outline's lines on either side. + pub size_m: f64, + /// The signed turn at its place, toward the paved side positive (a convex vertex). + pub turn: f64, +} + +/// The short features of a plan of level 0. Along the paved outline (`paved_outline`), a vertex +/// that turns past `CORNER_TURN` by itself is part of one where the outline's direction from a +/// support back to half a support back and from half a support ahead to a support ahead agree +/// within `CORNER_TURN`, and the vertex lies more than `SHORT_M` off the line of either. Such +/// vertices closer than the support along the outline are one feature, placed at the farthest off. +pub fn short_features(plan: &FacePlan) -> Vec { + let mpu = metres_per_unit(plan.cell.origin().y + CELL_UNITS / 2); + let support = SUPPORT_M / mpu; + let mut out = Vec::new(); + for chain in paved_outline(plan) { + let (pts, n) = (&chain.pts, chain.pts.len()); + let turn = chain.turns(); + let edge = edge_lengths(pts); + let size: Vec> = (0..n) + .map(|i| { + if turn[i]?.abs() <= CORNER_TURN { + return None; + } + let reach = |dir: usize, d: f64| along(pts, &edge, &turn, i, dir, d); + let (p1, p0, q0, q1) = + (reach(n - 1, support), reach(n - 1, support / 2.0), reach(1, support / 2.0), reach(1, support)); + let (din, dout) = ([p0[0] - p1[0], p0[1] - p1[1]], [q1[0] - q0[0], q1[1] - q0[1]]); + let (lin, lout) = (libm::hypot(din[0], din[1]), libm::hypot(dout[0], dout[1])); + if lin == 0.0 || lout == 0.0 { + return None; + } + let angle = libm::atan2(din[0] * dout[1] - din[1] * dout[0], din[0] * dout[0] + din[1] * dout[1]); + if angle.abs() > CORNER_TURN { + return None; + } + let v = [f64::from(pts[i][0]), f64::from(pts[i][1])]; + let off = |a: [f64; 2], d: [f64; 2], l: f64| (d[0] * (v[1] - a[1]) - d[1] * (v[0] - a[0])).abs() / l; + let size = off(p0, din, lin).max(off(q0, dout, lout)) * mpu; + (size > SHORT_M).then_some(size) + }) + .collect(); + // Group from a vertex that is part of none, so no feature wraps a closed chain's start. + let Some(start) = (0..n).find(|&i| size[i].is_none()) else { continue }; + let mut run: Option<(ShortFeature, f64)> = None; + let mut s = 0.0; + for x in 1..=n { + let i = (start + x) % n; + s += edge[(i + n - 1) % n]; + let Some(z) = size[i] else { continue }; + match &mut run { + Some((f, last)) if s - *last <= support => { + *last = s; + if z > f.size_m { + (f.at, f.size_m, f.face, f.turn) = (pts[i], z, chain.face(i), turn[i].unwrap_or(0.0)); + } + } + _ => { + out.extend(run.take().map(|r| r.0)); + let turn = turn[i].unwrap_or(0.0); + run = Some((ShortFeature { face: chain.face(i), at: pts[i], size_m: z, turn }, s)); + } + } + } + out.extend(run.map(|r| r.0)); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The places of an open chain, in units of 1: each with its corner's radius. + fn chain_places(pts: &[P], support: f64) -> Vec<(P, f64)> { + let n = pts.len(); + let turn: Vec> = (0..n).map(|i| (i > 0 && i + 1 < n).then(|| turn_at(pts, i))).collect(); + let radius = radii(pts, &turn, &|_| support); + (0..n).filter_map(|i| Some((pts[i], place(pts, &turn, &radius, i, 6000.0)?))).collect() + } + + #[test] + fn a_square_corner_is_one_place_at_its_vertex() { + // Along x, then a right turn (toward −y: concave for the side on the left). + let c = chain_places(&[[-1000, 0], [-500, 0], [0, 0], [0, -500], [0, -1000]], 625.0); + assert_eq!(c.len(), 1); + assert_eq!(c[0].0, [0, 0]); + assert!((c[0].1 - 625.0 / std::f64::consts::FRAC_PI_2).abs() < 1.0); + } + + #[test] + fn a_step_of_the_precision_at_the_support_end_is_no_place() { + // A straight edge with a 4-unit step: a turn of ±45° that a window may cut in half. + let pts = [[-1000, 0], [-312, 0], [-308, -4], [0, -4], [1000, -4]]; + for support in [600.0, 625.0, 630.0] { + assert!(chain_places(&pts, support).is_empty(), "support {support}"); + } + } + + #[test] + fn an_arc_and_its_tail_are_one_corner_placed_on_the_arc() { + // A concave arc of radius 1200 in 10° steps, a convex step where its chord meets the + // edge, then the edge. + let mut pts: Vec

= vec![[-3000, 0], [0, 0]]; + for k in 1..=9 { + let a = f64::from(k) * 10f64.to_radians(); + pts.push([(1200.0 * libm::sin(a)) as i32, (-1200.0 * (1.0 - libm::cos(a))) as i32]); + } + let end = *pts.last().unwrap(); + pts.extend([[end[0] + 3, end[1] - 300], [end[0] + 3, end[1] - 2000]]); + let c = chain_places(&pts, 625.0); + assert_eq!(c.len(), 1, "{c:?}"); + let p = c[0].0; + let off = libm::hypot(f64::from(p[0]), f64::from(p[1] + 1200)) - 1200.0; + assert!(off.abs() < 2.0, "the corner's place {p:?} lies off the arc by {off}"); + } +} diff --git a/host/obc-ground-plan/src/faces/cover.rs b/host/obc-ground-plan/src/faces/cover.rs new file mode 100644 index 0000000000..921e6652a9 --- /dev/null +++ b/host/obc-ground-plan/src/faces/cover.rs @@ -0,0 +1,109 @@ +//! Which candidates cover a point: a grid of candidate boxes, and per candidate its segments in +//! horizontal strips, so a winding number reads only the segments of the point's strip. + +use super::geom::P; + +/// The strip height and the grid cell: 1,024 frame units, about 1.6 m. +const SHIFT: u32 = 10; + +struct Region { + bbox: [i32; 4], + /// Per strip from `bbox[1] >> SHIFT`, the segments whose y range meets it. + strips: Vec>, +} + +pub struct Cover { + regions: Vec, + origin: [i32; 2], + cols: usize, + rows: usize, + grid: Vec>, + /// The candidates whose box spans more than `WIDE` grid cells: every query reads them. + wide: Vec, +} + +/// A candidate over more grid cells than this is read by every query instead of filling the grid. +const WIDE: usize = 64; + +fn strip(y: i32) -> i32 { + y >> SHIFT +} + +impl Cover { + /// The index of candidates' rings over the window [x0, y0, x1, y1]. + pub fn new(window: [i32; 4], candidates: &[&[Vec

]]) -> Cover { + let origin = [window[0] >> SHIFT, window[1] >> SHIFT]; + let cols = ((window[2] >> SHIFT) - origin[0] + 1) as usize; + let rows = ((window[3] >> SHIFT) - origin[1] + 1) as usize; + let mut cover = + Cover { regions: Vec::new(), origin, cols, rows, grid: vec![Vec::new(); cols * rows], wide: Vec::new() }; + for (id, rings) in candidates.iter().enumerate() { + let points = rings.iter().flatten(); + let bbox = points.fold([i32::MAX, i32::MAX, i32::MIN, i32::MIN], |b, p| { + [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])] + }); + let mut strips = Vec::new(); + if bbox[0] <= bbox[2] { + strips = vec![Vec::new(); (strip(bbox[3]) - strip(bbox[1]) + 1) as usize]; + for ring in rings.iter() { + for i in 0..ring.len() { + let (a, b) = (ring[i], ring[(i + 1) % ring.len()]); + for s in strip(a[1].min(b[1]))..=strip(a[1].max(b[1])) { + strips[(s - strip(bbox[1])) as usize].push([a, b]); + } + } + } + let cx = |x: i32| ((x >> SHIFT) - origin[0]).clamp(0, cols as i32 - 1) as usize; + let cy = |y: i32| ((y >> SHIFT) - origin[1]).clamp(0, rows as i32 - 1) as usize; + let (xs, ys) = (cx(bbox[0])..=cx(bbox[2]), cy(bbox[1])..=cy(bbox[3])); + if xs.clone().count() * ys.clone().count() > WIDE { + cover.wide.push(id as u32); + } else { + for y in ys { + for x in xs.clone() { + cover.grid[y * cols + x].push(id as u32); + } + } + } + } + cover.regions.push(Region { bbox, strips }); + } + cover + } + + /// The winding number of candidate `id` about a point in doubled coordinates. + fn winding(&self, id: usize, q: [i64; 2]) -> i32 { + let r = &self.regions[id]; + let (x, y) = (q[0].div_euclid(2) as i32, q[1].div_euclid(2) as i32); + if x < r.bbox[0] || x > r.bbox[2] || y < r.bbox[1] || y > r.bbox[3] { + return 0; + } + let mut w = 0; + for &[a, b] in &r.strips[(strip(y) - strip(r.bbox[1])) as usize] { + let (a2, b2) = ([2 * i64::from(a[0]), 2 * i64::from(a[1])], [2 * i64::from(b[0]), 2 * i64::from(b[1])]); + let side = || { + i128::from(b2[0] - a2[0]) * i128::from(q[1] - a2[1]) + - i128::from(q[0] - a2[0]) * i128::from(b2[1] - a2[1]) + }; + if a2[1] <= q[1] { + if b2[1] > q[1] && side() > 0 { + w += 1; + } + } else if b2[1] <= q[1] && side() < 0 { + w -= 1; + } + } + w + } + + /// The candidates that cover a point in doubled coordinates, in index order. + pub fn at(&self, q: [i64; 2]) -> Vec { + let cx = ((q[0].div_euclid(2) as i32 >> SHIFT) - self.origin[0]).clamp(0, self.cols as i32 - 1) as usize; + let cy = ((q[1].div_euclid(2) as i32 >> SHIFT) - self.origin[1]).clamp(0, self.rows as i32 - 1) as usize; + let mut out: Vec = (self.grid[cy * self.cols + cx].iter().chain(&self.wide).copied()) + .filter(|&id| self.winding(id as usize, q) != 0) + .collect(); + out.sort_unstable(); + out + } +} diff --git a/host/obc-ground-plan/src/faces/culverts.rs b/host/obc-ground-plan/src/faces/culverts.rs new file mode 100644 index 0000000000..1efb3eebe5 --- /dev/null +++ b/host/obc-ground-plan/src/faces/culverts.rs @@ -0,0 +1,309 @@ +//! The culverts of line water under ways on the ground, as candidates of the face slice: a zone where the water +//! does not show. The classifier gives a road's or a railway's ford over water that a culvert carries the culvert's +//! class, as the bake lays it (`graph::parts::fords`); a ford has no zone. A road's or a railway's zone is the water's +//! band under the way and out over its verge, and as far past it as the way's fill stands more than the mouth's +//! height over the water, at least as far as the fill falls by that height. The water's face ends there and casts +//! no cone into the zone (`records`), so the ground of the slopes over it rises from the water's sides only: the +//! step from the water up to the zone is the mouth, an arch as wide as the water and at most as high as its bank's +//! steepest cut at the half-width; the mesh stands a pipe's end there (`CulvertMouth`, `plan/piece.wgsl`). Where open +//! water goes on in its tunnel, a zone over the tunnel's start makes the same mouth. A path takes no zone: its +//! surface lies across the water. Each zone is a function of global data within its reach, so two cells build it +//! alike. + +use std::collections::BTreeMap; + +use i_overlay::core::overlay_rule::OverlayRule; + +use super::geom::{winding, P}; +use super::stroke::{pieces_along, shapes, union, Rings}; +use super::{heights, Cand, Ctx, CulvertMouth, HeightRule, Label, Owner, Surface, WayLine, TERRAIN, VERGE}; +use crate::faces::rules::Rank; +use crate::frame::metres_per_unit; +use crate::graph::{CrossingKind, Family, Level, WalkPoint}; +use crate::sections::{Reach, HALF_MAX_M}; + +/// A zone reads the water this far along from its crossing: it holds a way's verge and fill past it at a +/// crossing angle down to about 30°. +pub const ZONE_ALONG_M: f64 = 25.0; +/// A zone reads its way this far along from its crossing: `ZONE_ALONG_M` and a way's half-width and verge. +pub const ZONE_READ_M: f64 = 35.0; +/// A zone lies within this of its seed: a crossing's zone within `ZONE_ALONG_M` along the water and the water's +/// band (its half-width and bank top), a tunnel start's within the water's reach along it and a round end of its +/// half-width and reach. The widest river (`HALF_MAX_M`, a reach of 15 m) meets it with the tunnel start's. +pub const REACH_M: f64 = ZONE_ALONG_M + 20.0; +/// Faces are final this far past the cell: the heights to 32.5 m, and a height reads the crossings' faces +/// within the water term of its reach, 15.5 m. +const FINAL_M: f64 = 48.0; + +/// The rows of the culverts in the reach table, from the greatest bank reach and `culvert_max_m` of a water row. +/// The zone: what it reads, where it changes faces, and `FINAL_M`. An open culvert (`graph::open_culverts`): a +/// sample's level reads the crossing on its chain within `culvert_max_m`, whose class reads its chain as far again, +/// and the faces read the level; the graph's levels read no water of a culvert crossing. +pub fn reach_rows(bank_m: f64, culvert_max_m: f64) -> Vec { + let row = |name: &str, terms: &[(&str, f64)]| Reach { + name: name.into(), + owner: "faces::culverts", + chain: true, + terms: terms.iter().map(|&(what, m)| (what.to_string(), m)).collect(), + }; + vec![ + row( + "culvert zone", + &[ + ("ZONE_READ_M: its way, water and terrain", ZONE_READ_M), + ("ZONE_ALONG_M and the water's band", ZONE_ALONG_M + HALF_MAX_M + bank_m), + ("FINAL_M", FINAL_M), + ], + ), + row( + "open culvert", + &[("the crossing on its chain", culvert_max_m), ("its class", culvert_max_m), ("FINAL_M", FINAL_M)], + ), + ] +} + +/// The zones of the culverts whose crossing lies in `bx` (cell units), over the lines of the faces, and their +/// mouths: where the water's middle line meets a zone's outline, with water in front of it. +pub(super) fn candidates(ctx: &Ctx, lines: &[WayLine], bx: [i32; 4]) -> (Vec, Vec) { + let g = ctx.graph; + let of_way: BTreeMap = lines.iter().enumerate().map(|(i, l)| (l.way, i)).collect(); + let (mut out, mut mouths) = (Vec::new(), Vec::new()); + let near = |p: P| p[0] >= bx[0] && p[0] <= bx[2] && p[1] >= bx[1] && p[1] <= bx[3]; + for c in g.crossings.iter().filter(|c| c.kind == CrossingKind::Culvert && near(c.pos)) { + let (Some(w), Some(s)) = (g.way_at(&c.over, Level::Ground), g.way_at(&c.under, Level::Ground)) else { + continue; + }; + let (Some(&lw), Some(&ls)) = (of_way.get(&w), of_way.get(&s)) else { continue }; + if !matches!(g.ways[w as usize].family, Family::Road | Family::Rail) || !lines[ls].sec.water { + continue; + } + let (way, water) = (&lines[lw].sec, &lines[ls].sec); + let (ws, ss) = (g.sample_near(w, c.pos), g.sample_near(s, c.pos)); + // The fill past the verge down to the mouth's height over the water (the bank's steepest cut, which + // holds a way's fill, at the half-width), and at least as far as the fill falls by that height: the mouth + // stands at the foot of the way's bank, never at its edge. + let mouth = water.cut_max * water.half_m; + let over = g.samples[ws as usize].z_m - g.samples[ss as usize].z_m; + let past = ((over - mouth).max(mouth) / way.fill.max(1e-3)).clamp(0.0, way.reach_m); + let bank = water.half_m + heights::cone_reach(water.cut, water.rise_m, &ctx.rules.plan.heights); + let (band_s, middle) = water_band(ctx, s, ss, bank); + let band_w = band(ctx, lines, &of_way, w, ws, past, bounds(&band_s)); + let q2 = [2 * i64::from(c.pos[0]), 2 * i64::from(c.pos[1])]; + let found = shapes(&band_w, &band_s, OverlayRule::Intersect, c.pos).into_iter().find(|s| winding(s, q2) != 0); + let Some(rings) = found else { continue }; + mouths.extend(mouths_of(ctx, &middle, &rings, water.half_m)); + out.push(zone(ctx, rings, Some((w, way.rank as u8)), c.pos)); + } + // Where open water goes on in its tunnel, a zone over the tunnel's start: the water's band out to its reach, + // where its slopes have let go, and as long. The step there is the same mouth. + for j in g.joints.iter().filter(|j| near(j.pos)) { + let level = |k: usize| g.ways[j.arms[k].way as usize].level; + let Some(k) = (0..2).find(|&k| level(k) == Level::Tunnel && level(1 - k) == Level::Ground) else { continue }; + let (tunnel, open) = (&j.arms[k], &j.arms[1 - k]); + let Some(&l) = of_way.get(&open.way).filter(|&&l| lines[l].sec.water) else { continue }; + if g.ways[tunnel.way as usize].family != Family::Water { + continue; + } + let sec = &lines[l].sec; + let r = &g.ways[tunnel.way as usize].samples; + let start = if tunnel.dir > 0 { r.start } else { r.end - 1 }; + let over = g.walk(tunnel.way, start, tunnel.dir, sec.reach_m, false).swap_remove(0); + let p: Vec

= over.iter().map(|w| w.pos).collect(); + let h: Vec = p.iter().map(|q| (sec.half_m + sec.reach_m) / mpu(ctx, q.map(f64::from))).collect(); + let mut rings = Vec::new(); + stroke(&p, &h, [false, true], &mut rings); + if !rings.is_empty() && p.len() >= 2 { + // The mouth: the zone's square end at the joint, across the tunnel's line. + let into = unit(sub(p[1].map(f64::from), p[0].map(f64::from))); + let at = j.pos.map(f64::from); + mouths.push(CulvertMouth { at, into, edge: [-into[1], into[0]], half_m: sec.half_m }); + out.push(zone(ctx, union(&rings, j.pos), None, j.pos)); + } + } + // A mouth with another zone in front of it has no water there. + let front = |m: &CulvertMouth| { + let d = MOUTH_FRONT_M / mpu(ctx, m.at); + let q = [m.at[0] - d * m.into[0], m.at[1] - d * m.into[1]]; + let q2 = [libm::round(2.0 * q[0]) as i64, libm::round(2.0 * q[1]) as i64]; + out.iter().all(|z| winding(&z.rings, q2) == 0) + }; + mouths.retain(front); + // Two zones whose outlines meet at the water (a road beside a railway) give one mouth there. + let mut kept: Vec = Vec::new(); + for m in mouths { + let apart = |k: &CulvertMouth| libm::hypot(k.at[0] - m.at[0], k.at[1] - m.at[1]) * mpu(ctx, m.at); + if kept.iter().all(|k| apart(k) >= MOUTH_FRONT_M) { + kept.push(m); + } + } + (out, kept) +} + +/// A mouth stands where the water this far in front of it lies in no zone (metres). +const MOUTH_FRONT_M: f64 = 0.3; + +/// The mouths where the water's middle line `middle` (units) crosses the outline of a zone's `rings`: each crossing, +/// the line's direction there toward the zone, and the outline's. +fn mouths_of(ctx: &Ctx, middle: &[P], rings: &Rings, half_m: f64) -> Vec { + let mut out: Vec = Vec::new(); + for w in middle.windows(2) { + let (a, b) = (w[0].map(f64::from), w[1].map(f64::from)); + let ab = sub(b, a); + if ab == [0.0; 2] { + continue; + } + for ring in rings { + for k in 0..ring.len() { + let (c, d) = (ring[k].map(f64::from), ring[(k + 1) % ring.len()].map(f64::from)); + let (cd, ac) = (sub(d, c), sub(c, a)); + let den = cross(ab, cd); + if den == 0.0 { + continue; + } + let (t, u) = (cross(ac, cd) / den, cross(ac, ab) / den); + if !(0.0..1.0).contains(&t) || !(0.0..1.0).contains(&u) { + continue; + } + let at = [a[0] + t * ab[0], a[1] + t * ab[1]]; + // A middle line through a vertex of the outline crosses two of its edges there. + if out.iter().any(|m| libm::hypot(m.at[0] - at[0], m.at[1] - at[1]) * mpu(ctx, at) < MOUTH_FRONT_M) { + continue; + } + let dir = unit(ab); + let e = MOUTH_FRONT_M / mpu(ctx, at); + let ahead = + [libm::round(2.0 * (at[0] + e * dir[0])) as i64, libm::round(2.0 * (at[1] + e * dir[1])) as i64]; + let into = if winding(rings, ahead) != 0 { dir } else { [-dir[0], -dir[1]] }; + out.push(CulvertMouth { at, into, edge: unit(cd), half_m }); + } + } + } + out +} + +fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] { + [a[0] - b[0], a[1] - b[1]] +} + +fn cross(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[1] - a[1] * b[0] +} + +fn unit(a: [f64; 2]) -> [f64; 2] { + let n = libm::hypot(a[0], a[1]).max(1e-12); + [a[0] / n, a[1] / n] +} + +/// A zone's candidate: of a way (its line and class), or of a tunnel's start, named by its seed. +fn zone(ctx: &Ctx, rings: Rings, way: Option<(u32, u8)>, seed: P) -> Cand { + let rank = ctx.rules.plan.rank(Rank::Zone); + let owner = way.map_or(Owner::Terrain, |w| Owner::Way(w.0)); + let material = way.map(|w| w.0); + let label = Label { owner, surface: Surface::Zone, rule: HeightRule::Slope, material, rank, ..TERRAIN }; + let g = [ctx.origin.x + i64::from(seed[0]), ctx.origin.y + i64::from(seed[1])]; + Cand { + rings, + label, + key: (rank, way.map_or(u8::MAX, |w| w.1), 5), + glob: Some([g[0], g[1], 0, 0, 0]), + line: 0, + relabel: None, + beyond: Vec::new(), + fill: None, + discs: Vec::new(), + } +} + +/// Metres per frame unit at a point. +fn mpu(ctx: &Ctx, p: [f64; 2]) -> f64 { + metres_per_unit(ctx.origin.y + libm::round(p[1]) as i64) +} + +/// The band of the ways that a walk of `ZONE_READ_M` each way from sample `at` of `way` passes, out to their +/// verges' outer edge and `d` metres on: the strokes of the faces' own lines over the box `bx` (units) grown by +/// that offset, as rings that may overlap (the booleans that read them take their union, NonZero). A way of the +/// walk with no line of the faces (a deck or a tunnel) holds no ground of this level and adds nothing. +fn band(ctx: &Ctx, lines: &[WayLine], of_way: &BTreeMap, way: u32, at: u32, d: f64, bx: [f64; 4]) -> Rings { + let g = ctx.graph; + let walks = [-1, 1].map(|dir| g.walk(way, at, dir, ZONE_READ_M, false).swap_remove(0)); + let mut ways: Vec = walks.iter().flatten().map(|p| p.way).collect(); + ways.sort_unstable(); + ways.dedup(); + let r = (HALF_MAX_M + d) / mpu(ctx, g.samples[at as usize].pos.map(f64::from)); + // A segment whose box meets the grown box: a long segment may cross it with both ends outside. + let near = |a: P, b: P| { + let (lo, hi) = + ([a[0].min(b[0]), a[1].min(b[1])].map(f64::from), [a[0].max(b[0]), a[1].max(b[1])].map(f64::from)); + hi[0] >= bx[0] - r && lo[0] <= bx[2] + r && hi[1] >= bx[1] - r && lo[1] <= bx[3] + r + }; + let mut out = Vec::new(); + for w in ways { + let Some(&i) = of_way.get(&w) else { continue }; + let l = &lines[i]; + let n = l.p.len().saturating_sub(1); + let mut k = 0; + while k < n { + let Some(from) = (k..n).find(|&i| near(l.p[i], l.p[i + 1])) else { break }; + let to = (from..n).find(|&i| !near(l.p[i], l.p[i + 1])).unwrap_or(n); + let run = from.saturating_sub(1)..(to + 2).min(l.p.len()); + let off: Vec = run.clone().map(|i| l.bands[i][VERGE] + d / mpu(ctx, l.p[i].map(f64::from))).collect(); + if run.len() >= 2 { + pieces_along(&l.p[run], &off, &[], [&[], &[]], [false, false], false, &mut out); + } + k = to; + } + } + out +} + +/// The water's band about sample `at` of water way `s`: the network within `ZONE_ALONG_M` along it, on through +/// its joints and into every arm of a junction, `bank` metres wide each side; and its middle line through the +/// joints only. +fn water_band(ctx: &Ctx, s: u32, at: u32, bank: f64) -> (Rings, Vec

) { + let g = ctx.graph; + let mut lines: Vec<(Vec, [bool; 2])> = Vec::new(); + let mut main: Vec = Vec::new(); + for (k, d) in [-1i8, 1].into_iter().enumerate() { + let mut walks = g.walk(s, at, d, ZONE_ALONG_M, true); + let first = walks.remove(0); + if k == 0 { + main = first.into_iter().rev().collect(); + } else { + main.extend(first.into_iter().skip(1)); + } + lines.extend(walks.into_iter().map(|w| (w, [true, false]))); + } + let middle = main.iter().map(|w| w.pos).collect(); + lines.push((main, [false, false])); + let mut out = Vec::new(); + for (line, round) in lines { + let p: Vec

= line.iter().map(|w| w.pos).collect(); + let h: Vec = line.iter().map(|w| bank / mpu(ctx, w.pos.map(f64::from))).collect(); + stroke(&p, &h, round, &mut out); + } + (out, middle) +} + +/// The box of rings (units). +fn bounds(rings: &Rings) -> [f64; 4] { + let mut b = [f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY]; + for p in rings.iter().flatten().map(|p| p.map(f64::from)) { + b = [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]; + } + b +} + +/// The stroke of a polyline (units) with a half-width per point, square ends or round ones, as the band layers +/// are stroked, into `out`. +fn stroke(p: &[P], h: &[f64], round: [bool; 2], out: &mut Rings) { + let mut keep: Vec = Vec::with_capacity(p.len()); + for k in 0..p.len() { + if keep.last().is_none_or(|&j| p[j] != p[k]) { + keep.push(k); + } + } + let (p, h): (Vec

, Vec) = keep.iter().map(|&k| (p[k], h[k])).unzip(); + if p.len() >= 2 { + pieces_along(&p, &h, &[], [&[], &[]], round, false, out); + } +} diff --git a/host/obc-ground-plan/src/faces/deck.rs b/host/obc-ground-plan/src/faces/deck.rs new file mode 100644 index 0000000000..1b1f67acb5 --- /dev/null +++ b/host/obc-ground-plan/src/faces/deck.rs @@ -0,0 +1,184 @@ +//! The decks of the storeys over the ground: the ways that storey k ≥ 1 holds (the graph splits each bridge way at +//! the end lines that the tiles carry, `graph::level_tags::split`, so a deck is a whole way), their open ends, and the +//! stroke of a deck: its paved layers and the band about them (`edge_band_m`, `Surface::DeckEdge`). + +use super::geom::P; +use super::{WayLine, SLOPE}; +use crate::graph::{level_tags, Family, Level, WayGraph}; +use crate::sections::Finish; +use crate::CellInput; + +/// The number of a tag of the feature of way w. +fn tag(g: &WayGraph, input: &CellInput, w: u32, key: &str) -> Option { + let f = &input.features[g.parts[g.ways[w as usize].part as usize].feature.0 as usize]; + f.tags.get(key).and_then(|t| t.parse().ok()) +} + +/// The decks of a graph: per way its storey (0 for a way on no deck) and whether each of its ends is open. +pub(crate) struct Decks { + pub storey: Vec, + /// An open end meets a way that goes on past it on another storey: a way on the ground (storey 0 goes on), or a + /// deck on another storey. The shell leaves it open; a free end is closed. + pub open: Vec<[bool; 2]>, +} + +impl Decks { + /// A deck way's storey is its feature's (`level_tags::STOREY`, one more than each deck under it), 1 by default. + pub(crate) fn of(g: &WayGraph, input: &CellInput) -> Decks { + let deck_way = |w: u32| { + let x = &g.ways[w as usize]; + x.level == Level::Deck && x.family != Family::Water + }; + let storey: Vec = (0..g.ways.len() as u32) + .map(|w| if deck_way(w) { tag(g, input, w, level_tags::STOREY).map_or(1, |s| s as i8) } else { 0 }) + .collect(); + let mut decks = Decks { storey, open: vec![[false; 2]; g.ways.len()] }; + let mut open = vec![[false; 2]; g.ways.len()]; + for arms in g.junctions.iter().map(|j| &j.arms[..]).chain(g.joints.iter().map(|j| &j.arms[..])) { + for a in arms.iter().filter(|a| deck_way(a.way)) { + if arms.iter().any(|b| decks.goes_on(g, b.way, decks.storey[a.way as usize])) { + open[a.way as usize][usize::from(a.dir < 0)] = true; + } + } + } + decks.open = open; + decks + } + + /// Whether way w goes on at another level than storey k: a way on the ground (but water), or a deck on another + /// storey. + pub(crate) fn goes_on(&self, g: &WayGraph, w: u32, k: i8) -> bool { + let x = &g.ways[w as usize]; + x.family != Family::Water + && (x.level == Level::Ground || x.level == Level::Deck && self.storey[w as usize] != k) + } +} + +/// A deck's stroke on a line of storey k ≥ 1: its carriageway, its paved shoulder and the band (`band`, units at +/// a vertex) in the slope's place; the shoulder, the verge and the bank are 0 wide. A deck is one leg and ends +/// square. +pub(crate) fn deck_bands(line: &mut WayLine, band: &dyn Fn(P) -> f64) { + for i in 0..line.p.len() { + let paved = line.bands[i][0]; + line.bands[i] = [paved, paved, paved, paved, paved + band(line.p[i])]; + } + line.cuts.clear(); + line.spans.clear(); + line.round = [false; 2]; + line.deck = [false; 2]; +} + +/// The open end lines of a deck's line: the end point, the unit direction into the line and the half-width of its +/// stroke, its band included (units). +pub(crate) fn open_ends(line: &WayLine, open: [bool; 2]) -> Vec<[f64; 5]> { + let n = line.p.len(); + let end = |at: usize, next: usize| { + let (p, q) = (line.p[at], line.p[next]); + let d = [f64::from(q[0] - p[0]), f64::from(q[1] - p[1])]; + let len = libm::hypot(d[0], d[1]).max(1e-9); + [f64::from(p[0]), f64::from(p[1]), d[0] / len, d[1] / len, line.bands[at][SLOPE]] + }; + let mut out = Vec::new(); + if n >= 2 && open[0] { + out.push(end(0, 1)); + } + if n >= 2 && open[1] { + out.push(end(n - 1, n - 2)); + } + out +} + +/// A cell's storeys over the ground: their face plans (storey 1 first) and what their shells read. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Storeys { + pub plans: Vec, + /// Per deck way of the plans, by way: its slab, its edge feature and its piers. + pub ways: Vec<(u32, DeckWay)>, + /// The baked piers (`bridge-pier`) within `PIER_NEAR_M` of the cell, frame units from its origin. + pub piers: Vec<[i32; 2]>, + /// Storey 0's mesh points on its end lines (`EdgeKind::DeckEdge`, `mesh::points::edge_points`): a deck's end on + /// such a line takes the same points. + pub ground_ends: Vec<[i32; 2]>, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct DeckWay { + /// Its storey over the ground. + pub storey: i8, + /// The slab under the deck's top: the tile's `deck` depth, on ladder step 2 down to the class's least. + pub depth_m: f64, + /// A railing on the free outline, else a parapet. + pub railing: bool, + /// A pier's length along the deck and its width across. + pub pier_m: [f64; 2], + /// What its slab and its edge feature are made of. + pub build: Build, + /// A top of planks. + pub planks: bool, +} + +/// What a deck's slab is made of: a road's on beams and a railway's are concrete, a hanging bridge's steel, any +/// other timber. Its railing is timber on timber, else steel. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Build { + Concrete = 0, + Timber = 1, + Steel = 2, +} + +/// The `bridge:structure` of a bridge that hangs from cables, as `CABLES` of the viewer's `terrain/bins.ts`. +const CABLES: [&str; 3] = ["suspension", "simple-suspension", "cable-stayed"]; + +/// A pier's length along a road deck and a path deck, and its width as a share of the deck's paved width: the +/// crossing block's thickness table. +const PIER_ALONG_M: [f64; 2] = [1.6, 0.5]; +const PIER_SHARE: f64 = 0.6; +/// A pier whose point lies this near the cell may reach into it. +pub const PIER_NEAR_M: f64 = 5.0; + +impl Storeys { + /// The deck way `w` of the plans. + pub fn way(&self, w: u32) -> Option<&DeckWay> { + self.ways.binary_search_by_key(&w, |x| x.0).ok().map(|k| &self.ways[k].1) + } +} + +impl DeckWay { + /// Its build and its planks in a storey line's finish word (`records::BUILD_SHIFT`, `records::PLANKS`). + pub(crate) fn finish_bits(&self) -> u32 { + (self.build as u32) << super::records::BUILD_SHIFT | if self.planks { super::records::PLANKS } else { 0 } + } + + pub(crate) fn of(g: &WayGraph, input: &CellInput, rules: &super::Rules, w: u32, decks: &Decks) -> DeckWay { + let way = &g.ways[w as usize]; + let feature = &input.features[g.parts[way.part as usize].feature.0 as usize]; + let sec = rules.sections.way(&feature.kind, &feature.tags, false); + let depth = g.deck_depth(input, w, &sec); + let depth_m = tag(g, input, w, level_tags::SLAB).map_or(depth, |s| s.min(depth)); + let paved = sec.half_m + if sec.shoulder_paved { sec.shoulder_m } else { 0.0 }; + let width = 2.0 * (paved + rules.structures.edge_band_m); + // The rule of `segment` in the viewer's structures/bridges.ts: a road on beams is a concrete bridge with + // parapets; a covered bridge, one that hangs and a path's bridge have a railing, a railway's too. A top + // that the viewer did not count as paved (`isPaved` of roads/decks.ts) is of planks on such a bridge. + let text = |key: &str| feature.tags.get(key).map_or("", String::as_str); + let (covered, cable) = (text("bridge") == "covered", CABLES.contains(&text("bridge:structure"))); + let rail = sec.group == "rail"; + let beam_road = !covered && !cable && !sec.path; + let build = if cable { + Build::Steel + } else if rail || beam_road { + Build::Concrete + } else { + Build::Timber + }; + let paved_top = matches!(sec.finish, Some(Finish::Main | Finish::Road | Finish::Oneway)); + DeckWay { + storey: decks.storey[w as usize], + depth_m, + railing: sec.railing || !beam_road || width < rules.structures.railing_width_m, + pier_m: [PIER_ALONG_M[usize::from(sec.path)], PIER_SHARE * 2.0 * paved], + build, + planks: !beam_road && !rail && !paved_top, + } + } +} diff --git a/host/obc-ground-plan/src/faces/geom.rs b/host/obc-ground-plan/src/faces/geom.rs new file mode 100644 index 0000000000..17ae4eaf2e --- /dev/null +++ b/host/obc-ground-plan/src/faces/geom.rs @@ -0,0 +1,276 @@ +//! Exact integer predicates and the few float constructions of the faces. A float reads only +//! differences of integers or global positions, so two cells compute one point alike. + +use crate::frame::CELL_UNITS; + +/// A cell-frame point, and a point of a ring. +pub type P = [i32; 2]; + +/// Whether the box of segment a b meets the box `bx` (x0, y0, x1, y1). +pub fn meets(bx: [i32; 4], a: P, b: P) -> bool { + a[0].max(b[0]) >= bx[0] && a[0].min(b[0]) <= bx[2] && a[1].max(b[1]) >= bx[1] && a[1].min(b[1]) <= bx[3] +} + +/// Half away from zero, as the plan rounds every derived point. +pub fn round(v: f64) -> i64 { + libm::round(v) as i64 +} + +pub fn cross(o: P, a: P, b: P) -> i128 { + let (ax, ay) = (i128::from(a[0]) - i128::from(o[0]), i128::from(a[1]) - i128::from(o[1])); + let (bx, by) = (i128::from(b[0]) - i128::from(o[0]), i128::from(b[1]) - i128::from(o[1])); + ax * by - ay * bx +} + +/// The point of segment ab nearest the doubled point q, doubled, with its squared distance from q. +pub fn nearest_on(a: P, b: P, q: [i64; 2]) -> (u64, [i64; 2]) { + let (a2, b2) = ([2.0 * f64::from(a[0]), 2.0 * f64::from(a[1])], [2.0 * f64::from(b[0]), 2.0 * f64::from(b[1])]); + let (dx, dy) = (b2[0] - a2[0], b2[1] - a2[1]); + let l2 = dx * dx + dy * dy; + let t = + if l2 == 0.0 { 0.0 } else { (((q[0] as f64 - a2[0]) * dx + (q[1] as f64 - a2[1]) * dy) / l2).clamp(0.0, 1.0) }; + let c = [libm::round(a2[0] + t * dx) as i64, libm::round(a2[1] + t * dy) as i64]; + let (ex, ey) = ((c[0] - q[0]) as i128, (c[1] - q[1]) as i128); + ((ex * ex + ey * ey) as u64, c) +} + +/// Twice the signed area: positive for a ring with x east, y south that the plan calls positive. +pub fn area2(ring: &[P]) -> i128 { + let mut sum = 0i128; + for (i, &a) in ring.iter().enumerate() { + let b = ring[(i + 1) % ring.len()]; + sum += i128::from(a[0]) * i128::from(b[1]) - i128::from(b[0]) * i128::from(a[1]); + } + sum +} + +/// The winding number of the rings about a point in doubled coordinates (2x, 2y). A point on an edge +/// counts by the half-open rule; callers keep their points off the edges. +pub fn winding(rings: &[Vec

], q: [i64; 2]) -> i32 { + let mut w = 0; + for ring in rings { + for (i, &a) in ring.iter().enumerate() { + let b = ring[(i + 1) % ring.len()]; + let (ax, ay) = (2 * i128::from(a[0]), 2 * i128::from(a[1])); + let (bx, by) = (2 * i128::from(b[0]), 2 * i128::from(b[1])); + let (qx, qy) = (i128::from(q[0]), i128::from(q[1])); + let side = (bx - ax) * (qy - ay) - (by - ay) * (qx - ax); + if ay <= qy { + if by > qy && side > 0 { + w += 1; + } + } else if by <= qy && side < 0 { + w -= 1; + } + } + } + w +} + +/// Whether a point in doubled coordinates lies on a ring's edge or within `d2` (squared, doubled +/// units) of it. +pub fn near_edge(rings: &[Vec

], q: [i64; 2], d2: i128) -> bool { + rings.iter().any(|ring| { + (0..ring.len()).any(|i| { + let (a, b) = (ring[i], ring[(i + 1) % ring.len()]); + dist2_doubled(a, b, q) <= d2 + }) + }) +} + +/// The squared distance from a doubled point to segment ab, in doubled units, as an exact fraction +/// rounded up: enough to compare with a whole bound. +fn dist2_doubled(a: P, b: P, q: [i64; 2]) -> i128 { + let (ax, ay) = (2 * i128::from(a[0]), 2 * i128::from(a[1])); + let (bx, by) = (2 * i128::from(b[0]), 2 * i128::from(b[1])); + let (qx, qy) = (i128::from(q[0]), i128::from(q[1])); + let (dx, dy) = (bx - ax, by - ay); + let t = (qx - ax) * dx + (qy - ay) * dy; + let len = dx * dx + dy * dy; + if t <= 0 || len == 0 { + return (qx - ax).pow(2) + (qy - ay).pow(2); + } + if t >= len { + return (qx - bx).pow(2) + (qy - by).pow(2); + } + let c = dx * (qy - ay) - dy * (qx - ax); + (c * c + len - 1) / len +} + +/// An inner point of a patch (section 5.4 of the plan): for each edge of ring 0 from its least vertex, +/// its middle moved 2 units along the axis nearest to its inward normal; the first that lies inside +/// the patch and more than 1 unit from every edge. Doubled coordinates. +pub fn inner_point(rings: &[Vec

]) -> Option<[i64; 2]> { + // A patch under 4 units wide takes a point 1 unit in, off every edge. + [(4, 4), (2, 0)].into_iter().find_map(|(step, clear)| inner_point_at(rings, step, clear)) +} + +fn inner_point_at(rings: &[Vec

], step: i64, clear: i128) -> Option<[i64; 2]> { + let ring = &rings[0]; + let start = (0..ring.len()).min_by_key(|&i| (ring[i][1], ring[i][0]))?; + for k in 0..ring.len() { + let (a, b) = (ring[(start + k) % ring.len()], ring[(start + k + 1) % ring.len()]); + let (dx, dy) = (i64::from(b[0]) - i64::from(a[0]), i64::from(b[1]) - i64::from(a[1])); + let mut q = [i64::from(a[0]) + i64::from(b[0]), i64::from(a[1]) + i64::from(b[1])]; + // The inward normal of a positive ring is (−dy, dx). + if dy.abs() >= dx.abs() { + q[0] -= step * dy.signum(); + } else { + q[1] += step * dx.signum(); + } + if winding(rings, q) != 0 && !near_edge(rings, q, clear) { + return Some(q); + } + } + None +} + +/// The grid lines (x or y a whole multiple of `step`) that segment ab crosses strictly, as points in +/// the order from a: for x = X, y = y0 + round((X − x0)(y1 − y0) / (x1 − x0)), half away from zero, +/// from the segment's lesser end; but where that lands on a cell line and the exact y does not, one +/// unit nearer the exact y, so a point that one cell holds alone never lies on the line two cells +/// share. The rule reads only the segment, in either direction, and integer differences. +pub fn grid_points(a: P, b: P, step: i64, out: &mut Vec

) { + if a > b { + let mut back = Vec::new(); + grid_points(b, a, step, &mut back); + out.extend(back.into_iter().rev()); + return; + } + let mut found: Vec<(i128, i128, P)> = Vec::new(); + for axis in 0..2 { + let (a0, a1) = (i64::from(a[axis]), i64::from(b[axis])); + let (o0, o1) = (i64::from(a[1 - axis]), i64::from(b[1 - axis])); + if a0 == a1 { + continue; + } + let (lo, hi) = (a0.min(a1), a0.max(a1)); + let mut line = (lo.div_euclid(step) + 1) * step; + while line < hi { + let num = i128::from(line - a0) * i128::from(o1 - o0); + let den = i128::from(a1 - a0); + let q = div_round(num, den); + let mut o = i128::from(o0) + q; + let rest = (num - q * den) * den.signum(); + if o.rem_euclid(i128::from(CELL_UNITS)) == 0 && rest != 0 { + o += rest.signum(); + } + let mut p = [0i32; 2]; + p[axis] = line as i32; + p[1 - axis] = o as i32; + // The parameter along ab as the fraction (line − a0) / (a1 − a0), compared exactly. + let (n, d) = (i128::from(line - a0), den); + let (n, d) = if d < 0 { (-n, -d) } else { (n, d) }; + found.push((n, d, p)); + line += step; + } + } + found.sort_by(|x, y| (x.0 * y.1).cmp(&(y.0 * x.1)).then(x.2.cmp(&y.2))); + found.dedup_by_key(|x| x.2); + out.extend(found.into_iter().map(|x| x.2).filter(|&p| p != a && p != b)); +} + +/// num / den rounded half away from zero. +fn div_round(num: i128, den: i128) -> i128 { + let (n, d) = if den < 0 { (-num, -den) } else { (num, den) }; + if n >= 0 { + (2 * n + d) / (2 * d) + } else { + -((-2 * n + d) / (2 * d)) + } +} + +/// The ring with a vertex at each crossing of a grid line of `step` (`grid_points`). +pub fn with_grid_lines(ring: &[P], step: i64) -> Vec

{ + let mut out = Vec::with_capacity(ring.len() + 4); + for (i, &a) in ring.iter().enumerate() { + out.push(a); + grid_points(a, ring[(i + 1) % ring.len()], step, &mut out); + } + out.dedup(); + while out.len() > 1 && out.first() == out.last() { + out.pop(); + } + out +} + +/// The closest points of segments ab and cd, as parameters (s on ab, t on cd), in a frame relative to +/// a: floats of integer differences. +pub fn closest(a: P, b: P, c: P, d: P) -> (f64, f64, f64) { + let f = |p: P| [f64::from(p[0] - a[0]), f64::from(p[1] - a[1])]; + let (b, c, d) = (f(b), f(c), f(d)); + let seg = |p: [f64; 2], u: [f64; 2], v: [f64; 2]| { + let (dx, dy) = (v[0] - u[0], v[1] - u[1]); + let len = dx * dx + dy * dy; + if len == 0.0 { + 0.0 + } else { + (((p[0] - u[0]) * dx + (p[1] - u[1]) * dy) / len).clamp(0.0, 1.0) + } + }; + let at = |u: [f64; 2], v: [f64; 2], t: f64| [u[0] + (v[0] - u[0]) * t, u[1] + (v[1] - u[1]) * t]; + let dist = |p: [f64; 2], q: [f64; 2]| ((p[0] - q[0]) * (p[0] - q[0]) + (p[1] - q[1]) * (p[1] - q[1])).sqrt(); + let o = [0.0, 0.0]; + let mut best = (f64::INFINITY, 0.0, 0.0); + // The minimum of two segments that do not cross is at an end of one of them. + for (s, t) in [(0.0, seg(o, c, d)), (1.0, seg(b, c, d)), (seg(c, o, b), 0.0), (seg(d, o, b), 1.0)] { + let dd = dist(at(o, b, s), at(c, d, t)); + if dd < best.0 { + best = (dd, s, t); + } + } + let den = b[0] * (d[1] - c[1]) - b[1] * (d[0] - c[0]); + if den != 0.0 { + let s = ((c[0]) * (d[1] - c[1]) - (c[1]) * (d[0] - c[0])) / den; + let t = (c[0] * b[1] - c[1] * b[0]) / den; + if (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&t) { + best = (0.0, s, t); + } + } + best +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn grid_points_are_exact_in_order_and_off_the_cell_lines() { + let u = CELL_UNITS as i32; + let mut out = Vec::new(); + grid_points([-10, -7], [u + 10, 3], CELL_UNITS, &mut out); + assert_eq!(out, [[0, -7], [183505, 0], [u, 3]]); + let mut back = Vec::new(); + grid_points([u + 10, 3], [-10, -7], CELL_UNITS, &mut back); + assert_eq!(back, [[u, 3], [183505, 0], [0, -7]]); + let mut corner = Vec::new(); + grid_points([-4, -4], [4, 4], CELL_UNITS, &mut corner); + assert_eq!(corner, [[0, 0]]); + // Along a tile line and along a cell line: the tile corners, exact, with no step. + let mut along = Vec::new(); + grid_points([64, u - 70], [64, u + 70], 64, &mut along); + assert_eq!(along, [[64, u - 64], [64, u], [64, u + 64]]); + let mut on = Vec::new(); + grid_points([-70, u], [70, u], 64, &mut on); + assert_eq!(on, [[-64, u], [0, u], [64, u]]); + // The line y = 64 crossed 0.3 units east or west of the cell line x = 0: one unit nearer the + // exact point, not onto the line. + for (b, x) in [([1, 29], 1), ([-1, 29], -1)] { + let mut near = Vec::new(); + grid_points([0, 79], b, 64, &mut near); + assert_eq!(near, [[x, 64]]); + } + assert_eq!(div_round(5, 2), 3); + assert_eq!(div_round(-5, 2), -3); + } + + #[test] + fn inner_points_and_winding() { + let square = vec![vec![[0, 0], [10, 0], [10, 10], [0, 10]]]; + assert!(area2(&square[0]) > 0); + let q = inner_point(&square).unwrap(); + assert_eq!(winding(&square, q), 1); + let thin = vec![vec![[0, 0], [100, 0], [100, 2], [0, 2]]]; + assert_eq!(winding(&thin, inner_point(&thin).unwrap()), 1); + } +} diff --git a/host/obc-ground-plan/src/faces/heights/check.rs b/host/obc-ground-plan/src/faces/heights/check.rs new file mode 100644 index 0000000000..546407a75f --- /dev/null +++ b/host/obc-ground-plan/src/faces/heights/check.rs @@ -0,0 +1,749 @@ +//! The checks of the heights of a cell: the steps of a grid over the cell, inside a face or on a face +//! edge, the slope faces steeper than a rock face, the ripple of the carriageways, and the heights of +//! points on the cell's lines, which two cells must give alike. + +use super::{height_at, height_at_sides, Block, Height, HeightRules, Kind, Step as Rule}; +use crate::faces::records::{ + edge_ends, edge_line, find, label, outline_words, CAND, DISC, EDGE, JUNCTION, LABEL, LINE, PLATFORM, +}; +use crate::faces::Surface; +use crate::frame::{metres_per_unit, CellKey, GlobalPoint, CELL_UNITS}; +use crate::terrain::Terrain; + +/// A step: a jump over one frame unit of more than this. +pub const STEP_M: f64 = 0.01; +/// The ripple's grid: second differences over this. +pub const RIPPLE_M: f64 = 0.25; +/// The grid of `edge_steps` in the fixture's checks. +pub const EDGE_GRID_M: f64 = 1.0; +/// A water face of the owner rule lies at its host's own surface within this. +pub const WATER_LEVEL_M: f64 = 0.001; + +/// Where a step stands. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Class { + /// Inside one face. + Inside, + /// On a face edge, by a rule of its size. + Named(Rule), + /// On a face edge, with no rule of its size: a fault. + Unnamed, + /// On the edge of a face that GP6's rules do not own yet, with no rule of its size: a band face + /// with no material line, or a platform. + Apart, +} + +/// A step between two grid points: where it stands (within a frame unit) and the two sides there. +#[derive(Clone, Debug)] +pub struct Step { + /// The two points about the jump, frame units from the cell's origin. + pub a: [f64; 2], + pub b: [f64; 2], + pub dh: f64, + /// The labels at a and b. + pub labels: [Option; 2], + pub class: Class, + /// The heights of both labels at a. + pub sides: [Height; 2], +} + +#[derive(Clone, Debug, Default)] +pub struct Scan { + pub points: u64, + /// The grid points where a cap of `SLOTS` lines, `QUADS` quads or `REGIONS` regions left records + /// out, and the paved points whose label's material line the records lack (for a blend face, every + /// record of its kind: it then takes the plain terrain). + pub slots_full: Vec<[f64; 2]>, + pub host_missing: Vec<([f64; 2], Option)>, + /// The points of a water face of the owner rule whose height is not its host's own surface within + /// `WATER_LEVEL_M`: the painter reads the records of one kind only, so W is exact. + pub water_off: Vec<[f64; 2]>, + pub steps: Vec, + /// The second differences of the carriageway grid points along and across their line (m). + pub ripple: [Vec; 2], + /// Two neighbour slope points whose ground climbs more than `face_max` per metre between them where + /// the plain terrain climbs less: the first point and the climb per metre. + pub steep: Vec<([f64; 2], f64)>, +} + +/// The plain terrain at q, frame units from the cell's origin: at the nearest frame unit. +pub fn terrain_at(terrain: &Terrain, cell: CellKey, q: [f64; 2]) -> Option { + let o = cell.origin(); + terrain.height(GlobalPoint { x: o.x + q[0].round() as i64, y: o.y + q[1].round() as i64 }) +} + +/// The height at q with the label of `find` there. +pub fn at(words: &[u32], terrain: &Terrain, cell: CellKey, q: [f64; 2]) -> Option<(Height, Option)> { + let t = terrain_at(terrain, cell, q)?; + let label = find(words, q); + Some((height_at(words, q, label, t), label)) +} + +/// What `audit` finds at a point: its height and label, whether a cap left records out, whether the +/// records lack the label's material line, and whether a water face of the owner rule leaves its host's +/// own surface. +type Audit = ((Height, Option), bool, bool, bool); + +/// The height at q with the label of `find` there, and the faults there (`Audit`). +fn audit(words: &[u32], terrain: &Terrain, cell: CellKey, q: [f64; 2]) -> Option { + let t = terrain_at(terrain, cell, q)?; + let label = find(words, q); + let rule = label.map_or(0, |id| self::label(words, id)[0] >> 24); + if rule == 0 { + return Some(((height_at(words, q, label, t), label), false, false, false)); + } + let b = Block::at(words, q); + let p = HeightRules::of(words); + if rule == 1 { + return Some(((height_at(words, q, label, t), label), super::groups(&b, q, &p).1, false, false)); + } + let material = super::material(words, label); + let items = super::bin_items(&b, q)?; + let present = super::present(&b, q, &p, [material, u32::MAX], &items); + let h = super::by_label(&b, q, &present.recs, &items, label, t, &p).0; + // A host face misses its host; a blend face has none, and misses every record of its kind. + let missing = match rule { + 3 => !present.recs.iter().any(|r| r.water == b.water(material)), + _ => material != u32::MAX && !present.recs.iter().any(|r| r.line == material), + }; + let full = present.full || (rule == 3 && super::regions_full(words, q, label.unwrap_or(u32::MAX), &p)); + let water = label.is_some_and(|id| self::label(words, id)[0] & 0xff == Surface::Water as u32) && rule == 2; + let host = present.recs.iter().find(|r| r.line == material); + let off = water && host.is_some_and(|r| (h.h - r.z).abs() > WATER_LEVEL_M); + Some(((h, label), full, missing, off)) +} + +/// Whether a label's face is one that GP6's rules do not own yet: a paved band face with no material +/// line, or a platform. +fn apart(words: &[u32], id: Option) -> bool { + id.is_some_and(|id| { + let l = label(words, id); + let owner = (l[0] >> 8) & 0xff; + owner == PLATFORM || (l[0] >> 24 >= 2 && l[2] == u32::MAX) + }) +} + +/// `scan`'s grid points of `grid_m` over the cell with a known terrain, those where a cap left records +/// out (`Scan::slots_full`) and those whose label's material line the records lack +/// (`Scan::host_missing`), without the steps: the census reads the caps of each cell of a region. +pub fn caps(words: &[u32], terrain: &Terrain, cell: CellKey, grid_m: f64) -> [u64; 3] { + let step = grid_m / metres_per_unit(cell.origin().y + CELL_UNITS / 2); + let n = (CELL_UNITS as f64 / step).ceil() as usize; + let mut out = [0; 3]; + for k in 0..n * n { + let q = [((k % n) as f64 + 0.5) * step, ((k / n) as f64 + 0.5) * step]; + if q[0] >= CELL_UNITS as f64 || q[1] >= CELL_UNITS as f64 { + continue; + } + if let Some((_, full, missing, _)) = audit(words, terrain, cell, q) { + out = [out[0] + 1, out[1] + u64::from(full), out[2] + u64::from(missing)]; + } + } + out +} + +/// The steps of a grid of `grid_m` over the cell, and the ripple at its carriageway points. Between +/// two neighbours whose heights differ by more than `STEP_M`, the span halves, keeping the half whose +/// heights change more, while that half keeps most of the change; a jump that holds down to one frame +/// unit is a step. A step on a face edge is named when both sides at one point give its size by a rule. +pub fn scan(words: &[u32], terrain: &Terrain, cell: CellKey, grid_m: f64) -> Scan { + let rules = HeightRules::of(words); + let face_max = rules.face_max; + let mpu = metres_per_unit(cell.origin().y + CELL_UNITS / 2); + let step = grid_m / mpu; + let n = (CELL_UNITS as f64 / step).ceil() as usize; + let point = |i: usize, j: usize| [(i as f64 + 0.5) * step, (j as f64 + 0.5) * step]; + let mut out = Scan { points: (n * n) as u64, ..Scan::default() }; + let grid: Vec)>> = (0..n * n) + .map(|k| { + let q = point(k % n, k / n); + let a = (q[0] < CELL_UNITS as f64 && q[1] < CELL_UNITS as f64) + .then(|| audit(words, terrain, cell, q)) + .flatten()?; + if a.1 { + out.slots_full.push(q); + } + if a.2 { + out.host_missing.push((q, a.0 .1)); + } + if a.3 { + out.water_off.push(q); + } + Some(a.0) + }) + .collect(); + for k in 0..n * n { + let (i, j) = (k % n, k / n); + if let Some(r) = grid[k].and_then(|g| ripple(words, terrain, cell, point(i, j), g)) { + out.ripple[0].push(r[0]); + out.ripple[1].push(r[1]); + } + for (nb, di, dj) in + [(i + 1 < n).then_some((k + 1, 1, 0)), (j + 1 < n).then_some((k + n, 0, 1))].into_iter().flatten() + { + let (Some(ha), Some(hb)) = (grid[k], grid[nb]) else { continue }; + let (mut a, mut b) = (point(i, j), point(i + di, j + dj)); + let climb = |ga: f64, gb: f64| (gb - ga).abs() / grid_m; + if ha.0.kind == Kind::Slope && hb.0.kind == Kind::Slope && climb(ha.0.h, hb.0.h) > face_max { + if let (Some(ta), Some(tb)) = (terrain_at(terrain, cell, a), terrain_at(terrain, cell, b)) { + if climb(ta, tb) < face_max { + out.steep.push((a, climb(ha.0.h, hb.0.h))); + } + } + } + if (hb.0.h - ha.0.h).abs() <= STEP_M { + continue; + } + let (mut va, mut vb) = (ha, hb); + let found = loop { + let d = (vb.0.h - va.0.h).abs(); + if d <= STEP_M { + break false; + } + if libm::hypot(b[0] - a[0], b[1] - a[1]) <= 1.0 { + break true; + } + let m = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; + let Some(vm) = at(words, terrain, cell, m) else { break false }; + let (d1, d2) = ((vm.0.h - va.0.h).abs(), (vb.0.h - vm.0.h).abs()); + if d1.max(d2) < 0.75 * d { + break false; + } + if d1 >= d2 { + (b, vb) = (m, vm); + } else { + (a, va) = (m, vm); + } + }; + if !found { + continue; + } + let t = terrain_at(terrain, cell, a).unwrap_or(f64::NAN); + let sides = height_at_sides(words, a, [va.1, vb.1], t); + let dh = vb.0.h - va.0.h; + // The sides at one point give the step: else the field jumps between a and b. + let same = ((sides[1].h - sides[0].h) - dh).abs() <= STEP_M; + let class = if va.1 == vb.1 && ha.1 == hb.1 { + Class::Inside + } else if same && sides[0].step != Rule::None { + Class::Named(sides[0].step) + } else if apart(words, va.1) || apart(words, vb.1) { + Class::Apart + } else { + Class::Unnamed + }; + out.steps.push(Step { a, b, dh, labels: [va.1, vb.1], class, sides }); + } + } + out +} + +/// The steps at the label edges of a grid of `grid_m` over the cell, read by both sides at one point: +/// between two neighbours with two labels, the span halves to one frame unit by the labels alone, and +/// `height_at_sides` gives the step there. So a step beside a slope that falls the same way counts, +/// which `scan`'s halving by height can miss. The steps over `STEP_M` with no rule (`Unnamed`, or +/// `Apart` beside a face that GP6's rules do not own yet). +pub fn edge_steps(words: &[u32], terrain: &Terrain, cell: CellKey, grid_m: f64) -> Vec { + let step = grid_m / metres_per_unit(cell.origin().y + CELL_UNITS / 2); + let n = (CELL_UNITS as f64 / step) as usize; + let point = |i: usize, j: usize| [(i as f64 + 0.5) * step, (j as f64 + 0.5) * step]; + let labels: Vec> = (0..n * n).map(|k| find(words, point(k % n, k / n))).collect(); + let mut out = Vec::new(); + for k in 0..n * n { + let (i, j) = (k % n, k / n); + for nb in [(i + 1 < n).then_some(k + 1), (j + 1 < n).then_some(k + n)].into_iter().flatten() { + if labels[k] == labels[nb] { + continue; + } + let (mut a, mut b, mut lb) = (point(i, j), point(nb % n, nb / n), labels[nb]); + while libm::hypot(b[0] - a[0], b[1] - a[1]) > 1.0 { + let m = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; + match find(words, m) { + l if l == labels[k] => a = m, + l => (b, lb) = (m, l), + } + } + let Some(t) = terrain_at(terrain, cell, a) else { continue }; + let sides = height_at_sides(words, a, [labels[k], lb], t); + let dh = sides[1].h - sides[0].h; + if dh.abs() <= STEP_M || sides[0].step != Rule::None { + continue; + } + let class = if apart(words, labels[k]) || apart(words, lb) { Class::Apart } else { Class::Unnamed }; + out.push(Step { a, b, dh, labels: [labels[k], lb], class, sides }); + } + } + out +} + +/// A step that another line's cone holds higher than the paved side's wall cap (`Step::HeldOverCap`): where it +/// stands, its height, the metres from it to the outline of the line that holds it (infinite where q's bin lists +/// none of its edges), the caps of the paved side's host and of that line, and whether either is line water. +#[derive(Clone, Debug)] +pub struct HeldOver { + pub at: [f64; 2], + pub height: f64, + pub gap: f64, + pub caps: [f64; 2], + pub water: bool, +} + +/// The `HeldOverCap` steps at the label edges of a grid of `grid_m` over the cell, found as `edge_steps` finds +/// its steps. +pub fn held_over_cap(words: &[u32], terrain: &Terrain, cell: CellKey, grid_m: f64) -> Vec { + let step = grid_m / metres_per_unit(cell.origin().y + CELL_UNITS / 2); + let n = (CELL_UNITS as f64 / step) as usize; + let point = |i: usize, j: usize| [(i as f64 + 0.5) * step, (j as f64 + 0.5) * step]; + let labels: Vec> = (0..n * n).map(|k| find(words, point(k % n, k / n))).collect(); + let p = HeightRules::of(words); + let mut out = Vec::new(); + for k in 0..n * n { + let (i, j) = (k % n, k / n); + for nb in [(i + 1 < n).then_some(k + 1), (j + 1 < n).then_some(k + n)].into_iter().flatten() { + if labels[k] == labels[nb] { + continue; + } + let (mut a, mut b, mut lb) = (point(i, j), point(nb % n, nb / n), labels[nb]); + while libm::hypot(b[0] - a[0], b[1] - a[1]) > 1.0 { + let m = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; + match find(words, m) { + l if l == labels[k] => a = m, + l => (b, lb) = (m, l), + } + } + let Some(t) = terrain_at(terrain, cell, a) else { continue }; + let sides = height_at_sides(words, a, [labels[k], lb], t); + if sides[0].step != Rule::HeldOverCap || (sides[1].h - sides[0].h).abs() <= STEP_M { + continue; + } + let (slope, paved) = if sides[0].kind == Kind::Paved { (sides[1], sides[0]) } else { (sides[0], sides[1]) }; + let bl = Block::at(words, a); + let cap = |l: u32| if l == u32::MAX { 0.0 } else { bl.line(l as usize).wall_max(&p) }; + let gap = super::walls(&bl, a, slope.owner, &p).map_or(f64::INFINITY, |w| w.1 / p.face_max); + out.push(HeldOver { + at: a, + height: (paved.h - slope.h).abs(), + gap, + caps: [cap(paved.owner), cap(slope.owner)], + water: [paved.owner, slope.owner].iter().any(|&l| l != u32::MAX && bl.line(l as usize).water), + }); + } + } + out +} + +/// A ground point within this many metres past a deck end line must stand under the deck's underside less the gap. +pub const PAST_M: f64 = 0.5; +/// The points of `deck_ends` across an end line lie this far apart, and the first this far inside its paved ends. +pub const ACROSS_M: f64 = 0.25; + +/// The deck ends of a cell's records and their faults: points of an end line or within `PAST_M` past it that no +/// deck's stroke holds; ground points within `PAST_M` past it over the deck's underside less the gap (the place, +/// the metres over); points of the end line with ground beyond it whose step is shorter than the deck's depth and +/// the gap less `step_m` or not an `EndFace` (the place, the step, the deck's drop, its label). And the points of an +/// end line with a paved face beyond it with less step: a junction's face or another way's goes on there, so the +/// end has no end face. The end lines' points lie in the cell. +#[derive(Clone, Debug, Default)] +pub struct DeckEnds { + pub ends: usize, + pub points: usize, + pub uncovered: Vec<[f64; 2]>, + pub over: Vec<([f64; 2], f64)>, + pub short: Vec<([f64; 2], f64, f64, Rule)>, + pub paved_beyond: Vec<[f64; 2]>, +} + +/// A deck end line of a block: the end point (frame units from the cell's origin), the unit direction into its +/// line, and the half-width of its paved layers (units). +#[derive(Clone, Copy, Debug)] +pub struct EndLine { + pub at: [f64; 2], + pub into: [f64; 2], + pub half: f64, +} + +impl EndLine { + /// q in units along `into` from the end point and across, signed. + pub fn place(&self, q: [f64; 2]) -> [f64; 2] { + let v = [q[0] - self.at[0], q[1] - self.at[1]]; + [v[0] * self.into[0] + v[1] * self.into[1], v[1] * self.into[0] - v[0] * self.into[1]] + } +} + +/// The deck end lines of a block's lines (`records::DECK`). +pub fn end_lines(words: &[u32]) -> Vec { + let mut out = Vec::new(); + for l in 0..words[3] as usize { + let b = Block::at(words, [0.0, 0.0]); + let ln = b.line(l); + for e in (0..2).filter(|&e| ln.deck[e] && !ln.ceiling) { + let (i, j) = if e == 0 { (0, 1) } else { (ln.count - 1, ln.count - 2) }; + let (a, next) = (b.position(&ln, i), b.position(&ln, j)); + let d = [next[0] - a[0], next[1] - a[1]]; + let len = libm::hypot(d[0], d[1]); + let b = Block::at(words, a); + let half = (b.sample(&ln, i).h + ln.side) / b.mpu; + out.push(EndLine { at: a, into: [d[0] / len, d[1] / len], half }); + } + } + out +} + +pub fn deck_ends(words: &[u32], terrain: &Terrain, cell: CellKey) -> DeckEnds { + let p = HeightRules::of(words); + let mut out = DeckEnds::default(); + let inside = |q: [f64; 2]| (0.0..CELL_UNITS as f64).contains(&q[0]) && (0.0..CELL_UNITS as f64).contains(&q[1]); + for end in end_lines(words).into_iter().filter(|e| inside(e.at)) { + let mpu = Block::at(words, end.at).mpu; + let (u, nrm) = (end.into, [-end.into[1], end.into[0]]); + let at = |across: f64, along: f64| { + [end.at[0] + (nrm[0] * across + u[0] * along) / mpu, end.at[1] + (nrm[1] * across + u[1] * along) / mpu] + }; + out.ends += 1; + let half = end.half * mpu; + let n = ((2.0 * half - 2.0 * ACROSS_M) / ACROSS_M).floor() as usize; + for k in 0..=n { + let across = -half + ACROSS_M + k as f64 * ACROSS_M; + let q = at(across, 0.0); + let (Some(t), true) = (terrain_at(terrain, cell, q), inside(q)) else { continue }; + out.points += 1; + // The deck beyond the end line, whose bound `under_deck` reads inside its stroke only. + let Some((_, drop)) = super::under_deck(words, at(across, -0.01)) else { + out.uncovered.push(q); + continue; + }; + let one = 2.0 * mpu; + let labels = [find(words, at(across, one)), find(words, at(across, -one))]; + let sides = height_at_sides(words, q, labels, t); + let step = sides[0].h - sides[1].h; + if step < drop - p.step_m && sides[1].kind == Kind::Paved { + out.paved_beyond.push(q); + } else if step < drop - p.step_m || sides[0].step != Rule::EndFace { + out.short.push((q, step, drop, sides[0].step)); + } + for m in 1..=5 { + let q = at(across, -PAST_M * f64::from(m) / 5.0); + let Some(t) = terrain_at(terrain, cell, q).filter(|_| inside(q)) else { continue }; + let Some((under, _)) = super::under_deck(words, q) else { + out.uncovered.push(q); + continue; + }; + let (h, _) = at_label(words, q, t); + if h.kind != Kind::Paved && h.h > under + 1e-9 { + out.over.push((q, h.h - under)); + } + } + } + } + out +} + +/// The height and label at q with the terrain t. +fn at_label(words: &[u32], q: [f64; 2], t: f64) -> (Height, Option) { + let label = find(words, q); + (height_at(words, q, label, t), label) +} + +/// The joints of two decks of a block: where two ceiling lines end at one point, the point and the lesser +/// half-width of their strokes (metres). +fn deck_joints(words: &[u32]) -> Vec<([f64; 2], f64)> { + let b = Block::at(words, [0.0, 0.0]); + let mut ends = Vec::new(); + for l in 0..words[3] as usize { + let ln = b.line(l); + for i in [0, ln.count - 1].into_iter().filter(|_| ln.ceiling) { + let p = b.position(&ln, i); + ends.push((l, p, Block::at(words, p).sample(&ln, i).h)); + } + } + let mut out = Vec::new(); + for (k, &(l, p, h)) in ends.iter().enumerate() { + out.extend(ends[k + 1..].iter().filter(|e| e.0 != l && e.1 == p).map(|e| (p, h.min(e.2)))); + } + out +} + +/// Over a grid of `grid_m` on the cell, the points that a deck's stroke holds: their count, the ground points +/// (terrain and slope rules) over the deck's underside less the gap, and the paved points over it; and the points +/// within the lesser half-width of a joint of two decks that no stroke holds (a notch between their ends). +pub fn under_decks(words: &[u32], terrain: &Terrain, cell: CellKey, grid_m: f64) -> [usize; 4] { + let step = grid_m / metres_per_unit(cell.origin().y + CELL_UNITS / 2); + let n = (CELL_UNITS as f64 / step) as usize; + let joints = deck_joints(words); + let mut out = [0; 4]; + for k in 0..n * n { + let q = [((k % n) as f64 + 0.5) * step, ((k / n) as f64 + 0.5) * step]; + let Some(t) = terrain_at(terrain, cell, q) else { continue }; + let Some((under, _)) = super::under_deck(words, q) else { + let mpu = Block::at(words, q).mpu; + let notch = joints.iter().any(|(j, r)| libm::hypot(q[0] - j[0], q[1] - j[1]) * mpu < r - 0.01); + out[3] += usize::from(notch); + continue; + }; + let (h, _) = at_label(words, q, t); + out[0] += 1; + if h.h > under + 1e-9 { + out[if h.kind == Kind::Paved { 2 } else { 1 }] += 1; + } + } + out +} + +/// The points of `wall_steps` along an outline edge lie this far apart, at most. +pub const WALL_TOP_M: f64 = 0.25; +/// A step this high beside a wall class's road draws as a wall (`WALL_STEP_M` of `plan/piece.wgsl`). +pub const WALL_M: f64 = 0.5; + +/// The outline edges of a cell's records that lie in the cell by their middle: their ends (frame units), their +/// unit direction, their host line and their turn at b (`Edge::turn`), in the records' order. +fn cell_edges(words: &[u32]) -> impl Iterator + '_ { + let inside = |v: f64| (0.0..CELL_UNITS as f64).contains(&v); + let block = Block::at(words, [0.0, 0.0]); + outline_words(words).chunks(EDGE).enumerate().filter_map(move |(k, e)| { + let (a, b) = edge_ends(e); + let (a, b) = ([f64::from(a[0]), f64::from(a[1])], [f64::from(b[0]), f64::from(b[1])]); + let len = libm::hypot(b[0] - a[0], b[1] - a[1]); + let u = [(b[0] - a[0]) / len, (b[1] - a[1]) / len]; + (inside((a[0] + b[0]) / 2.0) && inside((a[1] + b[1]) / 2.0)) + .then(|| (a, b, u, edge_line(e), block.edge(k as u32).turn[1])) + }) +} + +/// The wall-top steps of a cell: along each outline edge of a wall class that lies in the cell by its middle, +/// points up to `WALL_TOP_M` apart (edges under 0.1 m left out); two neighbours on one no-room wall at least +/// `WALL_M` high whose wall height changes by more than `grade` per metre: the first point and that change. +pub fn wall_steps(words: &[u32], terrain: &Terrain, cell: CellKey, grade: f64) -> Vec<([f64; 2], f64)> { + let b = Block::at(words, [0.0, 0.0]); + let mut out = Vec::new(); + for (a, z, u, line, _) in cell_edges(words) { + let len = libm::hypot(z[0] - a[0], z[1] - a[1]) * b.mpu; + if len < 0.1 || !b.line(line as usize).wall { + continue; + } + let (n, steps) = ([u[1], -u[0]], (len / WALL_TOP_M).ceil() as usize); + let wall = |k: usize| { + let q = [a[0] + (z[0] - a[0]) * k as f64 / steps as f64, a[1] + (z[1] - a[1]) * k as f64 / steps as f64]; + let labels = [-2.0, 2.0].map(|o| find(words, [q[0] + o * n[0], q[1] + o * n[1]])); + let s = height_at_sides(words, q, labels, terrain_at(terrain, cell, q)?); + let w = s[1].h - s[0].h; + (s[1].step == Rule::NoRoom && w.abs() >= WALL_M).then_some((q, w)) + }; + let walls: Vec<_> = (0..=steps).map(wall).collect(); + for pair in walls.windows(2) { + if let [Some((q, w0)), Some((_, w1))] = pair { + let climb = (w1 - w0).abs() * steps as f64 / len; + if climb > grade { + out.push((*q, climb)); + } + } + } + } + out +} + +/// `slope_steps` reads the ground this many metres out from the rim, and these metres along it to each side. +pub const SLOPE_OUT_M: [f64; 3] = [1.0, 2.0, 4.0]; +pub const SLOPE_SIDE_M: [f64; 2] = [0.25, 0.05]; +/// The slope steps of a cell (the shading bands, a groove or a ridge): at each end in the cell where the +/// record's turn goes on to the next edge on a straight rim, the ground's grade along the rim over each of +/// `SLOPE_SIDE_M` before and after the end, at each of `SLOPE_OUT_M` out where all three points lie on a slope; +/// where the grade changes by more than `grade`: the end and the greatest change. The rim is straight where +/// the turn is within what a shift of each whole-unit end by one unit across the rim gives (2 / length per +/// edge, in units): a cut at the bin grid rounds its point and a split floors its middle. +pub fn slope_steps(words: &[u32], terrain: &Terrain, cell: CellKey, grade: f64) -> Vec<([f64; 2], f64)> { + let mpu = Block::at(words, [0.0, 0.0]).mpu; + let edges: Vec<_> = cell_edges(words).collect(); + let mut out = Vec::new(); + for pair in edges.windows(2) { + let [(a0, v, u, l0, turn), (a1, z, _, l1, _)] = [pair[0], pair[1]]; + let rounding = 2.0 / libm::hypot(v[0] - a0[0], v[1] - a0[1]) + 2.0 / libm::hypot(z[0] - a1[0], z[1] - a1[1]); + if v != a1 || l0 != l1 || turn.is_nan() || turn.abs() > rounding { + continue; + } + let n = [u[1], -u[0]]; + let ground = |out: f64, side: f64| { + let q = [v[0] + (n[0] * out + u[0] * side) / mpu, v[1] + (n[1] * out + u[1] * side) / mpu]; + at(words, terrain, cell, q).filter(|(h, _)| h.kind == Kind::Slope).map(|(h, _)| h.h) + }; + let change = (SLOPE_OUT_M.iter().flat_map(|&o| SLOPE_SIDE_M.map(|d| (o, d)))) + .filter_map(|(o, d)| { + let (l, c, r) = (ground(o, -d)?, ground(o, 0.0)?, ground(o, d)?); + Some(((r - c) - (c - l)).abs() / d) + }) + .fold(0.0, f64::max); + if change > grade { + out.push((v, change)); + } + } + out +} + +/// The second differences of h at a carriageway point c over `RIPPLE_M` along and across its line +/// (NaN where a neighbour lies in another face), or None for a point that the ripple gate leaves out: +/// no carriageway of a way's own face, or within a feather of a junction's circle (a junction ramp). +pub fn ripple( + words: &[u32], + terrain: &Terrain, + cell: CellKey, + c: [f64; 2], + h: (Height, Option), +) -> Option<[f64; 2]> { + let id = h.1?; + let l = label(words, id); + let surface = l[0] & 0xff; + let carriageway = surface == Surface::Carriageway as u32 || surface == Surface::Crossing as u32; + if !carriageway || l[0] >> 24 != 2 || l[2] == u32::MAX || near_junction(words, c) { + return None; + } + let b = Block::at(words, c); + let u = direction(&b, l[2] as usize, c); + let s = RIPPLE_M / b.mpu; + let mut out = [f64::NAN; 2]; + for (k, d) in [u, [-u[1], u[0]]].into_iter().enumerate() { + let p = at(words, terrain, cell, [c[0] + d[0] * s, c[1] + d[1] * s]); + let m = at(words, terrain, cell, [c[0] - d[0] * s, c[1] - d[1] * s]); + if let (Some(p), Some(m)) = (p, m) { + if p.1 == h.1 && m.1 == h.1 { + out[k] = p.0.h - 2.0 * h.0.h + m.0.h; + } + } + } + Some(out) +} + +/// Whether q lies within a feather of the circle of a junction's fan (its arms' greater feather). +fn near_junction(words: &[u32], q: [f64; 2]) -> bool { + let b = Block::at(words, q); + let p = HeightRules::of(words); + let Some(items) = super::bin_items(&b, q) else { return false }; + items.discs.iter().any(|&item| { + let cand = &words[words[4] as usize + CAND * (item & 0xffff) as usize..][..CAND]; + if cand[3] == u32::MAX || (label(words, cand[3])[0] >> 8) & 0xff != JUNCTION { + return false; + } + let e = &words[words[8] as usize + cand[5] as usize + DISC * (item >> 16) as usize..][..DISC]; + let feather = [e[3], e[4]] + .iter() + .filter(|&&l| l != u32::MAX) + .map(|&l| b.line(l as usize).reach.max(p.feather_min_m)) + .fold(0.0, f64::max); + let r = f64::from(f32::from_bits(e[2])) * b.mpu; + let d = libm::hypot(q[0] - f64::from(e[0] as i32), q[1] - f64::from(e[1] as i32)) * b.mpu; + d <= r + feather + }) +} + +/// The unit direction (frame axes) of line l's segment nearest q among the segments of q's bin. +fn direction(b: &Block, l: usize, q: [f64; 2]) -> [f64; 2] { + let ln = b.line(l); + let Some(items) = super::bin_items(b, q) else { return [1.0, 0.0] }; + let mut best = (f64::INFINITY, [1.0, 0.0]); + for &item in items.segs { + if (item & 0xffff) as usize != l { + continue; + } + let i = (item >> 16) as usize; + let (pa, pb) = (b.position(&ln, i), b.position(&ln, i + 1)); + let ab = [pb[0] - pa[0], pb[1] - pa[1]]; + let l2 = ab[0] * ab[0] + ab[1] * ab[1]; + if l2 <= 0.0 { + continue; + } + let f = (((q[0] - pa[0]) * ab[0] + (q[1] - pa[1]) * ab[1]) / l2).clamp(0.0, 1.0); + let d = libm::hypot(q[0] - pa[0] - f * ab[0], q[1] - pa[1] - f * ab[1]); + if d < best.0 { + best = (d, [ab[0] / l2.sqrt(), ab[1] / l2.sqrt()]); + } + } + best.1 +} + +/// A point on a cell line as one cell reads it: the line (0 for x = const, 1 for y = const), its global +/// coordinate and the global coordinate along it. +pub type BorderKey = (u8, i64, i64); + +/// A border point's height and terrain bits, and its side's name. +#[derive(Clone, Debug, PartialEq)] +pub struct BorderValue { + pub h: u64, + pub t: u64, + pub name: String, +} + +/// The heights of points on the four lines of a cell, every `step` units along each: both cells of a +/// line read the same global points. +pub fn border(words: &[u32], terrain: &Terrain, cell: CellKey, step: i64) -> Vec<(BorderKey, BorderValue)> { + let o = cell.origin(); + let mut out = Vec::new(); + for along in (step / 2..CELL_UNITS).step_by(step as usize) { + for (axis, at) in [(0u8, 0), (0, CELL_UNITS), (1, 0), (1, CELL_UNITS)] { + let q = if axis == 0 { [at as f64, along as f64] } else { [along as f64, at as f64] }; + let Some((h, _)) = self::at(words, terrain, cell, q) else { continue }; + let t = terrain_at(terrain, cell, q).unwrap_or(f64::NAN); + let (line, g) = if axis == 0 { (o.x + at, o.y + along) } else { (o.y + at, o.x + along) }; + out.push(((axis, line, g), BorderValue { h: h.h.to_bits(), t: t.to_bits(), name: side_name(words, &h) })); + } + } + out +} + +/// A side as its kind and the class rank of its owner line. +pub fn side_name(words: &[u32], h: &Height) -> String { + let kind = match h.kind { + Kind::Terrain => "terrain", + Kind::Slope => "slope", + Kind::Paved => "paved", + }; + if h.owner == u32::MAX { + return kind.to_string(); + } + let class = words[words[6] as usize + LINE * h.owner as usize + 7]; + format!("{kind}:{class}") +} + +/// The records present at q, the host lines of the outline near it and both sides' causes, for the +/// debug tool's `--why`. +pub fn explain(words: &[u32], q: [f64; 2], labels: [Option; 2], t: f64) -> String { + use super::{by_label, groups, material, paved, present, slope_edge, Block, HeightRules}; + let b = Block::at(words, q); + let p = HeightRules::of(words); + let mut s = format!("q {q:?} t {t:.3} mpu {:.6} slope edge {:.3} m\n", b.mpu, slope_edge(&b, q)); + let items = super::bin_items(&b, q); + let recs = items.as_ref().map_or(Vec::new(), |i| present(&b, q, &p, labels.map(|l| material(words, l)), i).recs); + for (k, r) in recs.iter().enumerate() { + let ln = b.line(r.line as usize); + let ends = [0, 1].map(|e| b.past_end(&ln, e, q)); + let segs: Vec = items + .as_ref() + .map_or(Vec::new(), |i| i.segs.iter().filter(|&&w| w & 0xffff == r.line).map(|w| w >> 16).collect()); + s += &format!( + " rec {k}: line {} segs {segs:?} of {} class {} rail {} level ends past {ends:.3?} z {:.3} d {:.3} feather {} paved {:.3}\n", + r.line, ln.count, r.class, r.rail, r.z, r.d, r.feather, paved(&recs, k, &p) + ); + } + for g in groups(&b, q, &p).0 { + s += &format!( + " outline of line {} class {} rail {}: fill {:.3} cut {:.3} steep {:.3} d {:.3} toe {:.3} fade {:.3}\n", + g.line, g.class, g.rail, g.fill, g.cut, g.steep, g.d, g.toe, g.fade + ); + } + let none = super::NO_ITEMS; + for l in labels { + let (h, c) = by_label(&b, q, &recs, items.as_ref().unwrap_or(&none), l, t, &p); + let rule = l.map_or(0, |id| words[words[5] as usize + LABEL * id as usize] >> 24); + s += &format!(" label {l:?} rule {rule}: {h:?} by {:?}\n", c.by); + } + // A region's edges within its fade: the face beyond (its host line) and the metres to it. + for l in labels.into_iter().flatten() { + for e in crate::faces::records::blend_edges(words, q).filter(|e| e.region == l) { + let d = super::to_segment(q, e.a.map(f64::from), e.b.map(f64::from)) * b.mpu; + if d < p.region_fade_m { + let material = e.other.map_or(u32::MAX, |o| label(words, o)[2]); + s += &format!(" edge of {l} to {:?} material {material}: {d:.3} m\n", e.other); + } + } + } + let sides = height_at_sides(words, q, labels, t); + s += &format!(" step {:?}\n", sides[0].step); + s +} diff --git a/host/obc-ground-plan/src/faces/heights/mod.rs b/host/obc-ground-plan/src/faces/heights/mod.rs new file mode 100644 index 0000000000..e672711799 --- /dev/null +++ b/host/obc-ground-plan/src/faces/heights/mod.rs @@ -0,0 +1,1922 @@ +//! The heights of the one road model: one point function over a cell's records, for the near mesh's +//! vertices and the far stamp's texels (the viewer's `terrain/heights.wgsl`, a port line for line). +//! +//! Per point, each line near it gives its own surface (its curve's height on the mitre-quad frame plus +//! bank times the metres across), its distance past its core and a presence that falls from 1 at the +//! core's edge to 0 at its feather. The paved field is a normalized painter of these surfaces in which +//! each pair of records blends as far as they agree: inside the core of the first record present it is +//! that record's surface exactly; a compatible lesser record ramps to it; an incompatible one keeps its +//! own surface and meets it in a step on the greater record's core edge. Slopes start from the face +//! plan's paved outline, at the paved field's height there (the records' outline edges): per host line +//! a fill and a cut over its edges, released at the reach, and a smooth `min(cut, max(T, fill))`, where +//! a line's cut rises to the bank of the other lines' fills (`slope`), so one wall stands at the lower +//! line's edge. The ground (the terrain and the slopes) stays under every deck's ceiling (`ceiling`). + +pub mod check; +#[cfg(test)] +mod tests; + +use super::records::{ + blend_edge, edge_ends, edge_line, junction, label as label_words, skip_item, BAND, BINS, BIN_UNITS, CAND, CEILING, + DECK, DISC, EDGE, FILL, GRADE_STEPS, HEAD, HEADER, JR, JR_ARM, LABEL, LEG_SHIFT, LEVEL, LINE, MARGIN_M, RAIL, + SAMPLE, STOREY, TURN_STEPS, WALL, WATER, +}; +use super::Surface; +use crate::frame::{metres_per_unit_at, CELL_UNITS}; + +/// What kind of rule gave a height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Terrain, + Slope, + Paved, +} + +/// The rule of a step between the two sides of a face edge. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Step { + None, + /// A slope side whose cone found no room: the wall of its shift at the paved outline. + NoRoom, + /// A slope side that another line's cone holds, against a paved side: the bank of a higher line + /// at the edge of a lower one (the bank budget), or a cut. + Held, + /// Two paved sides whose hosts do not agree: by their records' heights, or of the two kinds (water and a way). + Unrelated, + /// The end line of a line at a level change to a tunnel or a gallery. + StructureEnd, + /// Line water's end at a culvert's zone (`faces::culverts`), which takes no cone from it: the mouth. + Mouth, + /// The end face of a deck end: a step on the end line of a line's `DECK` end, or one whose lower side a + /// deck's ceiling holds. + EndFace, + /// A step that another line's cone holds (as `Held`) higher than the paved side's wall cap: a fault + /// (`check::held_over_cap`). + HeldOverCap, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Height { + pub h: f64, + pub kind: Kind, + /// The host line of a paved point, the line whose cone holds a slope point, else `u32::MAX`. + pub owner: u32, + /// The rule of the step at a face edge (`height_at_sides`), when the step has that rule's size. + pub step: Step, +} + +/// The rule values of heights: the block `heights` of `plan.json`. A cell's records carry them +/// (`RULES` words after the head), so the crate and the viewer read the same values. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HeightRules { + /// The least feather of a line: its presence falls from 1 at its core's edge to 0 a feather on. + pub feather_min_m: f64, + /// Two lines blend up to half of `dz_wall` and step from it: the lesser line's return grade times + /// the greater line's feather over this. + pub blend_steep: f64, + /// A line's surface weighs its healthy quads by their metres across past the least, to 0 at this. + pub leg_reach_m: f64, + /// Frame health: none within the margin of the mitre crossing, full the width farther. The frame's + /// least radius is the half-width plus both, so the whole carriageway has full health. + pub health_margin_m: f64, + pub health_width_m: f64, + /// The frame's mitres turn toward the least radius by at most this angle from either chord + /// (degrees): a mitre off its chords twists the road across by the grade times its tangent. + pub frame_tilt_deg: f64, + /// The slope's foot at the outline is rounded over this. + pub round_m: f64, + /// A cone lets go over this share of its reach, and halfway through it has moved `fade_gap_m`. + pub fade_share: f64, + pub fade_gap_m: f64, + /// The toe and crest round: its width in height grows at `toe_per_m` from the outline up to + /// `toe_max_m`, and spans about `toe_span_m` whatever the grade gap (at least `toe_gap_min`). + pub toe_per_m: f64, + pub toe_max_m: f64, + pub toe_span_m: f64, + pub toe_gap_min: f64, + /// A fan's relation of its arms, and a third line's relation of two lines that meet it, fade over + /// this before the feather. + pub via_fade_m: f64, + /// Within this of the slope band's outer edge the slope fades into the terrain. + pub band_fade_m: f64, + /// The greatest half-width of the band about a mitre line over which neighbour quads blend. + pub mitre_band_m: f64, + /// The width (metres of height) of the smooth maximum of the fills (the bank budget and the fill + /// envelope) and of the cut's rise to the budget, which grows to it from 0 at the outline as the + /// toe round: two cones of two lines meet in a round, not a crease. + pub budget_round_m: f64, + /// The highest wall of a wall class at its edge: where a higher line's bank asks for more, the cut + /// rises past the wall's top at its steepest. + pub wall_max_m: f64, + /// The steepest slope (rise per metre) that a cone takes by its class or its budget; only a need + /// past the highest wall steepens a face more, as far as it asks. + pub face_max: f64, + /// A step over this between the two sides of a face edge needs a rule. + pub step_m: f64, + /// A junction's region fades to the faces beyond its edges over this (at most `MARGIN_M`, up to + /// which the records give the distance to its edges). + pub region_fade_m: f64, + /// The ground under a deck stays this far under its underside (`ceiling`). + pub ceiling_gap_m: f64, + /// A deck's ceiling lets go over the cones' `fade_share` of this, past its stroke, and is gone from it. + pub ceiling_release_m: f64, + pub legs: Legs, +} + +/// Two legs of one way at different heights: one line surface over both, blended in a ramp of +/// `leg_reach_m`, or the nearer leg alone. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Legs { + Ramp, + Wall, +} + +/// The number fields of `HeightRules` in the order of the block's words; then `legs` (0 ramp, 1 wall). +pub const RULE_FIELDS: [&str; 23] = [ + "feather_min_m", + "blend_steep", + "leg_reach_m", + "health_margin_m", + "health_width_m", + "frame_tilt_deg", + "round_m", + "fade_share", + "fade_gap_m", + "toe_per_m", + "toe_max_m", + "toe_span_m", + "toe_gap_min", + "via_fade_m", + "band_fade_m", + "mitre_band_m", + "budget_round_m", + "wall_max_m", + "face_max", + "step_m", + "region_fade_m", + "ceiling_gap_m", + "ceiling_release_m", +]; +pub const RULES: usize = RULE_FIELDS.len() + 1; + +impl HeightRules { + pub fn new(v: [f64; RULE_FIELDS.len()], legs: Legs) -> Self { + let [feather_min_m, blend_steep, leg_reach_m, health_margin_m, health_width_m, frame_tilt_deg, round_m, fade_share, fade_gap_m, toe_per_m, toe_max_m, toe_span_m, toe_gap_min, via_fade_m, band_fade_m, mitre_band_m, budget_round_m, wall_max_m, face_max, step_m, region_fade_m, ceiling_gap_m, ceiling_release_m] = + v; + HeightRules { + feather_min_m, + blend_steep, + leg_reach_m, + health_margin_m, + health_width_m, + frame_tilt_deg, + round_m, + fade_share, + fade_gap_m, + toe_per_m, + toe_max_m, + toe_span_m, + toe_gap_min, + via_fade_m, + band_fade_m, + mitre_band_m, + budget_round_m, + wall_max_m, + face_max, + step_m, + region_fade_m, + ceiling_gap_m, + ceiling_release_m, + legs, + } + } + + fn values(&self) -> [f64; RULE_FIELDS.len()] { + [ + self.feather_min_m, + self.blend_steep, + self.leg_reach_m, + self.health_margin_m, + self.health_width_m, + self.frame_tilt_deg, + self.round_m, + self.fade_share, + self.fade_gap_m, + self.toe_per_m, + self.toe_max_m, + self.toe_span_m, + self.toe_gap_min, + self.via_fade_m, + self.band_fade_m, + self.mitre_band_m, + self.budget_round_m, + self.wall_max_m, + self.face_max, + self.step_m, + self.region_fade_m, + self.ceiling_gap_m, + self.ceiling_release_m, + ] + } + + /// The block's words of the rules: f32 values, then the legs rule. + pub fn words(&self) -> [u32; RULES] { + let mut w = [0; RULES]; + for (k, v) in self.values().into_iter().enumerate() { + w[k] = (v as f32).to_bits(); + } + w[RULES - 1] = u32::from(self.legs == Legs::Wall); + w + } + + /// The rules that a block carries. + pub(crate) fn of(words: &[u32]) -> Self { + let w = &words[HEAD..][..RULES]; + HeightRules::new(std::array::from_fn(|k| f32w(w[k])), if w[RULES - 1] == 1 { Legs::Wall } else { Legs::Ramp }) + } +} + +/// The most lines that heights keeps at one point, and the most quads of one line; the GPU port +/// holds the same. The fixture check `slots_full` shows that no point passes them. +pub const SLOTS: usize = 10; +pub const QUADS: usize = 4; + +fn smoothstep(x: f64) -> f64 { + let x = x.clamp(0.0, 1.0); + x * x * (3.0 - 2.0 * x) +} + +/// 1 at 0, 0 at 1 and past it, with zero slope at both ends. +fn phi(x: f64) -> f64 { + 1.0 - smoothstep(x) +} + +/// The width of the toe's smooth min/max at d metres past the outline: slope `toe_per_m` at 0, level +/// at `most` (`toe_max_m` or less) from twice the distance where the slope would reach it, with no kink +/// (a kink of the width is a crease of the ground along the whole slope). +fn toe_width(d: f64, most: f64, p: &HeightRules) -> f64 { + let most = most.min(p.toe_max_m); + let x = (p.toe_per_m * d / (2.0 * most)).min(1.0); + most * (1.0 - (1.0 - x) * (1.0 - x)) +} + +/// The lesser of two widths with no kink where they cross: (a⁻⁴ + b⁻⁴)^(-1/4), between 0.84 and 1 +/// times the hard min; the hard min where either is 0 or less. +fn soft_min(a: f64, b: f64) -> f64 { + let (lo, hi) = (a.min(b), a.max(b)); + if lo <= 0.0 { + return lo; + } + let r = lo / hi; + lo / (1.0 + r * r * r * r).sqrt().sqrt() +} + +fn smin(a: f64, b: f64, k: f64) -> f64 { + if k <= 0.0 { + return a.min(b); + } + let h = (k - (a - b).abs()).max(0.0) / k; + a.min(b) - h * h * k / 4.0 +} + +fn smax(a: f64, b: f64, k: f64) -> f64 { + -smin(-a, -b, k) +} + +/// The soft greatest of the fills `at[j].0` over `js`, and the greatest one's index: the mean of the two +/// greatest, the second weighted by (1 − gap / k)² where positive, with k growing from 0 at the +/// greatest one's outline (as the toe round). It never rises above the greatest (a smooth maximum lifts +/// a tie by k / 4) and is exact at the greatest one's edge, so the ground starts there. It sinks the +/// greatest by at most 0.106 k, at a gap of 0.4 k. Where the two change places they tie, and a tie's +/// mean is its value whatever k, so the envelope has no jump; with a third fill it would have one. +fn soft_top( + at: &[(f64, f64, f64, f64)], + js: impl Iterator + Clone, + p: &HeightRules, +) -> (f64, Option) { + let Some(top) = js.clone().max_by(|&a, &c| at[a].0.total_cmp(&at[c].0).then(c.cmp(&a))) else { + return (f64::NEG_INFINITY, None); + }; + let second = js.filter(|&j| j != top).map(|j| at[j].0).fold(f64::NEG_INFINITY, f64::max); + let (v, k) = (at[top].0, toe_width(at[top].3, p.budget_round_m, p)); + if k <= 0.0 || !second.is_finite() || !v.is_finite() { + return (v, Some(top)); + } + let x = (1.0 - (v - second) / k).max(0.0); + ((v + x * x * second) / (1.0 + x * x), Some(top)) +} + +fn f32w(w: u32) -> f64 { + f64::from(f32::from_bits(w)) +} + +fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] { + [a[0] - b[0], a[1] - b[1]] +} + +fn dot(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[0] + a[1] * b[1] +} + +fn cross(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[1] - a[1] * b[0] +} + +fn norm(a: [f64; 2]) -> f64 { + dot(a, a).sqrt() +} + +/// The distance from q to the point at share f of segment a, a + ab: q − a first, which is exact, so +/// two cells give the same bits. +fn off_foot(q: [f64; 2], a: [f64; 2], ab: [f64; 2], f: f64) -> f64 { + norm([q[0] - a[0] - f * ab[0], q[1] - a[1] - f * ab[1]]) +} + +/// The frame's units across at q in the quad of segment a, a + ab with the mitres ta and tb, at its +/// share t (signed, + left): from the chord's line along q's line of equal t, which is normal to the +/// mitres' mean at t. So on a mitre line it is the distance along it, the same in both quads. +fn across(q: [f64; 2], a: [f64; 2], ab: [f64; 2], ta: [f64; 2], tb: [f64; 2], t: f64) -> f64 { + let m = unit([ta[0] + t * (tb[0] - ta[0]), ta[1] + t * (tb[1] - ta[1])]); + let v = sub(q, a); + let along = dot(ab, m); + let f = if along != 0.0 { dot(v, m) / along } else { 0.0 }; + -cross(m, [v[0] - f * ab[0], v[1] - f * ab[1]]) +} + +/// The distance from q to the segment a, c: q − a first, so two cells give the same bits. +fn to_segment(q: [f64; 2], a: [f64; 2], c: [f64; 2]) -> f64 { + let ab = sub(c, a); + let l2 = dot(ab, ab); + let f = if l2 > 0.0 { (dot(sub(q, a), ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; + off_foot(q, a, ab, f) +} + +fn unit(a: [f64; 2]) -> [f64; 2] { + let n = norm(a); + if n > 0.0 { + [a[0] / n, a[1] / n] + } else { + [1.0, 0.0] + } +} + +/// The block's words as heights reads them, at one point. +struct Block<'a> { + w: &'a [u32], + /// Metres per frame unit at the point: two cells that share it read the same scale. + mpu: f64, +} + +impl<'a> Block<'a> { + fn at(w: &'a [u32], q: [f64; 2]) -> Self { + Block { w, mpu: metres_per_unit_at(f64::from(w[10]) * CELL_UNITS as f64 + q[1]) } + } +} + +#[derive(Clone, Copy, Debug)] +struct Line { + first: usize, + count: usize, + cut: f64, + fill: f64, + reach: f64, + class: u32, + /// Shoulder plus verge, metres. + side: f64, + ret: f64, + /// The class's steepest fill and cut of the no-room rule (rise per metre). + fill_max: f64, + cut_max: f64, + rail: bool, + /// A class with a wall at its edge where a higher line's bank needs one (`leg_wall`). + wall: bool, + /// Line water: its records and a way's never meet in one painter. + water: bool, + /// Its fill cone starts this far over its edge and this far past it (metres): water's dyke. + rise: f64, + crest: f64, + /// Whether the start and the end are a level change to a tunnel or a gallery, and to a deck. + level: [bool; 2], + deck: [bool; 2], + /// A deck's ceiling line (`CEILING`): its `ret` holds its drop, and `flat` the unit normal of its stroke's + /// flat end at its start and at its end, into the line (`pack2x16snorm`). + ceiling: bool, + flat: [u32; 2], + /// The storey of a line over the ground (`STOREY`), else 0. + storey: i8, +} + +impl Line { + /// The highest wall at this line's edge: `wall_max_m` for a wall class, none for another. + fn wall_max(&self, p: &HeightRules) -> f64 { + if self.wall { + p.wall_max_m + } else { + 0.0 + } + } + + /// The slope of the highest cut toward a bank budget: the class's steepest cut, at most a rock face. + fn steepest_cut(&self, p: &HeightRules) -> f64 { + self.cut_max.max(self.cut).min(p.face_max) + } +} + +#[derive(Clone, Copy, Debug)] +struct Sample { + p: [f64; 2], + /// Half-width, metres. + h: f64, + z: f64, + bank: f64, + grade: f64, +} + +impl Block<'_> { + fn line(&self, l: usize) -> Line { + let w = &self.w[self.w[6] as usize + LINE * l..][..LINE]; + Line { + first: w[2] as usize, + count: w[3] as usize, + cut: f32w(w[4]), + fill: f32w(w[5]), + reach: f32w(w[6]), + class: w[7], + side: f32w(w[8]) + f32w(w[9]), + ret: f32w(w[10]), + fill_max: f32w(w[14]), + cut_max: f32w(w[15]), + rail: w[1] & RAIL != 0, + wall: w[1] & WALL != 0, + water: w[1] & WATER != 0, + rise: f32w(w[16]), + crest: f32w(w[17]), + level: [w[12] == LEVEL, w[13] == LEVEL], + deck: [w[12] == DECK, w[13] == DECK], + ceiling: w[1] & CEILING != 0, + flat: [w[4], w[5]], + storey: if w[1] & STOREY != 0 { (w[1] >> LEG_SHIFT) as i8 } else { 0 }, + } + } + + /// The way of line l. + fn way(&self, l: u32) -> u32 { + self.w[self.w[6] as usize + LINE * l as usize] + } + + /// Whether line l is water; false for none (`u32::MAX`). + fn water(&self, l: u32) -> bool { + l != u32::MAX && self.w[self.w[6] as usize + LINE * l as usize + 1] & WATER != 0 + } + + /// Metres of q past end e (0 the start, 1 the end) of the line along its mitre there: negative before it. + fn past_end(&self, ln: &Line, e: usize, q: [f64; 2]) -> f64 { + let i = if e == 0 { 0 } else { ln.count - 1 }; + let along = dot(sub(q, self.position(ln, i)), self.mitre(ln, i)) * self.mpu; + if e == 0 { + -along + } else { + along + } + } + + fn sample(&self, ln: &Line, i: usize) -> Sample { + let w = &self.w[self.w[7] as usize + SAMPLE * (ln.first + i)..][..SAMPLE]; + Sample { + p: [f64::from(w[0] as i32), f64::from(w[1] as i32)], + h: f32w(w[2]) * self.mpu, + z: f32w(w[5]), + bank: f32w(w[6]), + grade: f32w(w[7]), + } + } + + /// The metres along the way of sample i. + fn along(&self, ln: &Line, i: usize) -> f64 { + f32w(self.w[self.w[7] as usize + SAMPLE * (ln.first + i) + 3]) + } + + fn position(&self, ln: &Line, i: usize) -> [f64; 2] { + let at = self.w[7] as usize + SAMPLE * (ln.first + i); + [f64::from(self.w[at] as i32), f64::from(self.w[at + 1] as i32)] + } + + /// The glob order of sample i. + fn glob(&self, ln: &Line, i: usize) -> u32 { + self.w[self.w[7] as usize + SAMPLE * (ln.first + i) + 4] + } + + /// Half-width at sample i, metres. + fn half(&self, ln: &Line, i: usize) -> f64 { + f32w(self.w[self.w[7] as usize + SAMPLE * (ln.first + i) + 2]) * self.mpu + } + + /// The mitre direction at sample i (unit): the bisector of its two chords. + fn mitre(&self, ln: &Line, i: usize) -> [f64; 2] { + let w = &self.w[self.w[7] as usize + SAMPLE * (ln.first + i) + 8..][..2]; + [f32w(w[0]), f32w(w[1])] + } + + /// The health radius on a side (+1 left, −1 right) at sample i, frame units. + fn rho(&self, ln: &Line, i: usize, side: f64) -> f64 { + f32w(self.w[self.w[7] as usize + SAMPLE * (ln.first + i) + if side > 0.0 { 10 } else { 11 }]) + } +} + +fn hermite(z0: f64, z1: f64, m0: f64, m1: f64, t: f64) -> f64 { + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * z0 + (t3 - 2.0 * t2 + t) * m0 + (-2.0 * t3 + 3.0 * t2) * z1 + (t3 - t2) * m1 +} + +/// A line's surface at a point, from one of its segments. +#[derive(Clone, Copy, Debug)] +struct Frame { + /// Its own height there (metres). + z: f64, + /// Metres across (signed, + left). + delta: f64, + /// Frame health in [0, 1]. + nu: f64, +} + +/// The frame's health toward one side's health radius `r`, at `seg` metres across toward that side +/// (negative on the other side): 0 within the margin of the crossing, 1 from the width farther. The +/// product of both sides' health is continuous across the centre line. +fn health(r: f64, seg: f64, p: &HeightRules) -> f64 { + smoothstep((r - seg - p.health_margin_m) / p.health_width_m) +} + +/// Segment i of a line at q, with its two samples read: in its mitre quad, or past the line's first or +/// last sample along the end chord with the end grade. None where the quad does not hold q. +#[allow(clippy::too_many_arguments)] +fn segment_of(b: &Block, ln: &Line, i: usize, sa: &Sample, sb: &Sample, q: [f64; 2], p: &HeightRules) -> Option { + let (ta, tb) = (b.mitre(ln, i), b.mitre(ln, i + 1)); + let da = dot(sub(q, sa.p), ta); + let db = dot(sub(sb.p, q), tb); + let (first, last) = (i == 0, i + 2 == ln.count); + let ab = sub(sb.p, sa.p); + let len = norm(ab); + if len <= 0.0 { + return None; + } + let u = [ab[0] / len, ab[1] / len]; + // Positive on the left of the direction: the frame's y points south. + let lateral = -cross(u, sub(q, sa.p)) * b.mpu; + let len_m = len * b.mpu; + let (t, z, delta, nu); + if da >= 0.0 && db >= 0.0 { + t = if da + db > 0.0 { da / (da + db) } else { 0.5 }; + z = hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, t); + // The frame's metres across: both quads give them on their mitre line. + delta = across(q, sa.p, ab, ta, tb, t) * b.mpu; + // Interpolated as a curvature, so a straight neighbour (no crossing) does not swamp it. + let r = |side: f64| b.mpu / ((1.0 - t) / b.rho(ln, i, side) + t / b.rho(ln, i + 1, side)); + nu = health(r(1.0), delta, p) * health(r(-1.0), -delta, p); + } else if first && da < 0.0 && db >= 0.0 { + let past = -dot(sub(q, sa.p), u) * b.mpu; + t = 0.0; + z = sa.z - sa.grade * past; + delta = lateral; + // The end vertex's health, as the first quad has it on the end's mitre line. + nu = health(b.rho(ln, i, 1.0) * b.mpu, delta, p) * health(b.rho(ln, i, -1.0) * b.mpu, -delta, p); + } else if last && db < 0.0 && da >= 0.0 { + let past = dot(sub(q, sb.p), u) * b.mpu; + t = 1.0; + z = sb.z + sb.grade * past; + delta = lateral; + nu = health(b.rho(ln, i + 1, 1.0) * b.mpu, delta, p) * health(b.rho(ln, i + 1, -1.0) * b.mpu, -delta, p); + } else { + return None; + } + let bank = sa.bank + t * (sb.bank - sa.bank); + // The bank tilts about the frame's metres across, which agree on the mitre line with the + // neighbour's and go on smoothly past the quad (past an end, the end chord's distance). + let mut z = z + bank * delta; + if da >= 0.0 && db >= 0.0 { + // Neighbour quads agree in value on their mitre line, not in slope: each blends with the + // neighbour's surface carried on past that line, over a band (`mitre_band`). + let own = (da + db) * b.mpu; + for (x, has, j) in [(da * b.mpu, i > 0, i.wrapping_sub(1)), (db * b.mpu, i + 2 < ln.count, i + 1)] { + if has && x < p.mitre_band_m.min(own / 2.0) { + if let Some((zn, other)) = surface(b, ln, j, q) { + z = mitre_band(z, zn, x, own, other, p); + } + } + } + } + Some(Frame { z, delta, nu }) +} + +/// A quad's own surface `z` at x metres from its mitre line, blended with the neighbour's surface `zn` +/// carried on past it: half each on the line, its own alone from the band's edge, with a C1 weight. +/// The two agree on the line, so the blend is C1 across it whatever the band's width on each side. +/// The band is narrower than half of either quad's length through q (`own`, `other`: da + db, metres), +/// so a quad's two bands never meet and the neighbour's surface is carried on past its line by less +/// than half its length. +fn mitre_band(z: f64, zn: f64, x: f64, own: f64, other: f64, p: &HeightRules) -> f64 { + if other <= 0.0 { + return z; + } + let w = 1.0 / (1.0 / p.mitre_band_m + 2.0 / own + 2.0 / other); + let s = smoothstep((x / w + 1.0) / 2.0); + s * z + (1.0 - s) * zn +} + +/// Segment j's surface at q carried past its mitre quad (the quad's formula with t outside [0, 1]), +/// and its length through q (da + db, metres; None when not positive). +fn surface(b: &Block, ln: &Line, j: usize, q: [f64; 2]) -> Option<(f64, f64)> { + let (sa, sb) = (b.sample(ln, j), b.sample(ln, j + 1)); + let da = dot(sub(q, sa.p), b.mitre(ln, j)); + let db = dot(sub(sb.p, q), b.mitre(ln, j + 1)); + let ab = sub(sb.p, sa.p); + let len = norm(ab); + if da + db <= 0.0 || len <= 0.0 { + return None; + } + let t = da / (da + db); + let len_m = len * b.mpu; + let z = hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, t); + let n = across(q, sa.p, ab, b.mitre(ln, j), b.mitre(ln, j + 1), t) * b.mpu; + Some((z + (sa.bank + t * (sb.bank - sa.bank)) * n, (da + db) * b.mpu)) +} + +/// The lines present at a point, and whether a cap of `SLOTS` lines or `QUADS` quads left some out. +struct Present { + recs: Vec, + full: bool, +} + +/// One line present at a point. +#[derive(Clone, Copy, Debug)] +struct Rec { + line: u32, + class: u32, + /// The glob order of its first sample: the painter's order among equal classes. Two cells give two + /// lines the same order, and it holds along the line. + glob: u32, + z: f64, + /// Metres past its core, 0 inside. + d: f64, + feather: f64, + ret: f64, + rail: bool, + water: bool, + /// Per other record (by its index after sorting), how much a fan relates the two at q. + rel: [f64; SLOTS], +} + +/// The bin of q (closed cell square, as `find`): its header's word, or None outside the cell or for +/// an empty bin. +fn bin_head(w: &[u32], q: [f64; 2]) -> Option { + let cell = CELL_UNITS as f64; + if !(0.0..=cell).contains(&q[0]) || !(0.0..=cell).contains(&q[1]) { + return None; + } + let bin = |v: f64| ((v / f64::from(BIN_UNITS)).floor() as i32).min(BINS - 1); + let head = w[9] as usize + HEADER * (bin(q[1]) * BINS + bin(q[0])) as usize; + (w[head] != 0).then_some(head) +} + +/// The items that the paved field reads about a point: its height segments (`line | sample << 16`), +/// its discs (`candidate | disc << 16`) and its blend edges (by index). A bin's lists at a point of the +/// cell; the build's window bins at an outline end past it, which list the same items. +pub(crate) struct Items<'a> { + pub segs: &'a [u32], + pub discs: &'a [u32], + pub blend: &'a [u32], +} + +/// No items: a point outside the cell or in an empty bin. +const NO_ITEMS: Items<'static> = Items { segs: &[], discs: &[], blend: &[] }; + +/// The first word of the height segments of the bin at `head`. +fn heights_start(w: &[u32], head: usize) -> usize { + w[head] as usize + (w[head + 3] >> 16) as usize + (w[head + 1] & 0xffff) as usize +} + +/// The items of q's bin. +fn bin_items<'a>(b: &Block<'a>, q: [f64; 2]) -> Option> { + let w = b.w; + let head = bin_head(w, q)?; + let at = heights_start(w, head); + let (n_h, n_d, n_b) = + ((w[head + 2] >> 16) as usize, (w[head + 2] & 0xffff) as usize, (w[head + 3] & 0xffff) as usize); + Some(Items { segs: &w[at..at + n_h], discs: &w[at + n_h..at + n_h + n_d], blend: &w[at + n_h + n_d..][..n_b] }) +} + +/// The outline edges that q's bin lists, by host line: half words after their count, the first low. A +/// block with no outline edges (the far level) lists none. +fn outline_items<'a>(b: &Block<'a>, q: [f64; 2]) -> impl Iterator + 'a { + let w = b.w; + let (at, n) = match bin_head(w, q).filter(|_| w[14] < w[9]) { + Some(head) => { + let at = heights_start(w, head) + (w[head + 2] >> 16) as usize + (w[head + 2] & 0xffff) as usize; + let at = at + (w[head + 3] & 0xffff) as usize; + (at, (w[at] & 0xffff) as usize) + } + None => (0, 0), + }; + (1..=n).map(move |k| w[at + k / 2] >> (16 * (k % 2)) & 0xffff) +} + +/// Metres from q to the outer edge of the slope band (the band layer with surface slope), from the +/// edges of q's bin (those that meet the bin grown by `MARGIN_M`): exact within it, else at least it. +fn slope_edge(b: &Block, q: [f64; 2]) -> f64 { + let w = b.w; + let Some(head) = bin_head(w, q) else { return f64::INFINITY }; + let mut at = w[head] as usize; + let mut best = f64::INFINITY; + for _ in 0..(w[head + 1] >> 16) { + let next = skip_item(w, at); + let cand = &w[w[4] as usize + CAND * (w[at] & 0xffff) as usize..][..CAND]; + let slope = cand[0] == BAND + && cand[3] != u32::MAX + && w[w[5] as usize + LABEL * cand[3] as usize] & 0xff == Surface::Slope as u32; + if slope { + let mut run = at + 2; + for _ in 0..w[at + 1] { + let n = w[run] as usize; + let v = |k: usize| [f64::from(w[run + 1 + 2 * k] as i32), f64::from(w[run + 2 + 2 * k] as i32)]; + for k in 0..n.saturating_sub(1) { + best = best.min(to_segment(q, v(k), v(k + 1))); + } + run += 1 + 2 * n; + } + } + at = next; + } + best * b.mpu +} + +/// The lines present at q (from `items`): per line, its surface from the quads that hold q with some +/// health, kept while its core lies within its feather or its reach. `keep`: the material lines of the +/// labels asked for, never skipped as absent: a face's host is its material line wherever the face lies. +/// The lines are those of the first kept line's storey: storey 0's come first and end at the first ceiling +/// line; a storey over the ground reads only its own, which come last. +fn present(b: &Block, q: [f64; 2], p: &HeightRules, keep: [u32; 2], items: &Items) -> Present { + let storey = if keep[0] == u32::MAX { 0 } else { b.line(keep[0] as usize).storey }; + let (hs, ds) = (items.segs, items.discs); + let (nh, nd) = (hs.len(), ds.len()); + let mut out: Vec = Vec::with_capacity(SLOTS); + let mut full = false; + let mut k = 0; + while k < nh { + let l = (hs[k] & 0xffff) as usize; + let ln = b.line(l); + // The ceiling lines and the storeys over the ground come last: no line of storey 0 follows. + if storey == 0 && (ln.ceiling || ln.storey != 0) { + break; + } + if ln.storey != storey { + k += 1; + continue; + } + // A line whose core lies a feather or more from q is not present: skip it before its frames. + // Every listed segment by its nearest point: the least metres to the core and to the centre. + let feather = ln.reach.max(p.feather_min_m); + let kept = keep.contains(&(l as u32)); + let mut end = k; + let (mut near, mut least) = (f64::INFINITY, f64::INFINITY); + while end < nh && (hs[end] & 0xffff) as usize == l { + let i = (hs[end] >> 16) as usize; + end += 1; + let (pa, pb) = (b.position(&ln, i), b.position(&ln, i + 1)); + let ab = sub(pb, pa); + let l2 = dot(ab, ab); + let f = if l2 > 0.0 { (dot(sub(q, pa), ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let (ha, hb) = (b.half(&ln, i), b.half(&ln, i + 1)); + let dist = off_foot(q, pa, ab, f) * b.mpu; + near = near.min(dist - (ha + f * (hb - ha)) - ln.side); + least = least.min(dist); + } + if near >= feather && !kept { + k = end; + continue; + } + let mut quads = [(0.0, 0.0); QUADS]; + let mut deltas = [0.0; QUADS]; + let mut nq = 0; + // The least frame metres across of the line's healthy quads so far. + let mut across = f64::INFINITY; + // The fallback surface where no healthy quad is near: a soft nearest of the segments' + // surfaces at their nearest points. + let (mut fb_w, mut fb_z) = (0.0, 0.0); + while k < end { + let i = (hs[k] >> 16) as usize; + k += 1; + let (sa, sb) = (b.sample(&ln, i), b.sample(&ln, i + 1)); + // The quads that can weigh, in the order of the line's samples: the same in every cell. + let f = segment_of(b, &ln, i, &sa, &sb, q, p); + // The legs' reach counts from the nearest quad that holds q, healthy or not. + across = f.map_or(across, |f| across.min(f.delta.abs())); + if let Some(f) = f.filter(|f| f.nu > 0.0) { + if f.delta.abs() - across < p.leg_reach_m { + if nq == QUADS { + // The quads that a nearer one put past the leg's reach weigh 0: they go. + let mut kept = 0; + for j in 0..nq { + if deltas[j] - across < p.leg_reach_m { + (quads[kept], deltas[kept]) = (quads[j], deltas[j]); + kept += 1; + } + } + nq = kept; + } + if nq == QUADS { + full = true; + crate::probe::hit(crate::probe::Cap::Quads); + } else { + quads[nq] = (f.z, f.nu); + deltas[nq] = f.delta.abs(); + nq += 1; + } + } + } + let ab = sub(sb.p, sa.p); + let l2 = dot(ab, ab); + let f = if l2 > 0.0 { (dot(sub(q, sa.p), ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let dist = off_foot(q, sa.p, ab, f) * b.mpu; + // Support within the segment's own band (its half-width, side and reach): every bin + // that q can lie in lists it. + let support = (sa.h + f * (sb.h - sa.h)) + ln.side + ln.reach; + let psi = phi((dist - least) / p.leg_reach_m) * phi(dist / support); + if psi <= 0.0 { + continue; + } + let len_m = l2.sqrt() * b.mpu; + let side = if cross(ab, sub(q, sa.p)) <= 0.0 { 1.0 } else { -1.0 }; + let z = hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, f) + + (sa.bank + f * (sb.bank - sa.bank)) * side * dist; + fb_w += psi; + fb_z += psi * z; + } + // The distance past the core is the plain one to the nearest segment: 0 exactly inside. + let core_d = near.max(0.0); + if (core_d >= feather.max(ln.reach) && !kept) || (nq == 0 && fb_w <= 0.0) { + continue; + } + // The line's surface: each healthy quad weighs its health times φ of its metres across past + // the least over `leg_reach_m`, so a far leg weighs nothing (or, by `legs`, the nearest quad + // alone); the fallback takes the rest of 1. + let (mut sa_w, mut z) = (0.0, 0.0); + let jn = (0..nq).min_by(|&a, &c| deltas[a].total_cmp(&deltas[c])).unwrap_or(0); + for j in 0..nq { + let a = match p.legs { + Legs::Ramp => quads[j].1 * phi((deltas[j] - across) / p.leg_reach_m), + Legs::Wall if j == jn => quads[j].1, + Legs::Wall => 0.0, + }; + sa_w += a; + z += a * quads[j].0; + } + let fb = (1.0 - sa_w).max(0.0); + let zf = if fb_w > 0.0 { fb_z / fb_w } else { 0.0 }; + out.push(Rec { + line: l as u32, + class: ln.class, + glob: b.glob(&ln, 0), + z: (z + fb * zf) / (sa_w + fb), + d: core_d, + feather, + ret: ln.ret, + rail: ln.rail, + water: ln.water, + rel: [0.0; SLOTS], + }); + } + // The order of the painter: class rank (rails first), then the global key. Past `SLOTS` records + // the last by it go, but never the labels' material lines. + out.sort_by_key(|r| (r.class, r.glob, r.line)); + if out.len() > SLOTS { + full = true; + crate::probe::hit(crate::probe::Cap::Slots); + } + while out.len() > SLOTS { + let Some(k) = out.iter().rposition(|r| !keep.contains(&r.line)) else { break }; + out.remove(k); + } + // A point's fan relates its two arms' ways near it; a round of the paved outline does not, as no + // graph point joins its ways, and two legs of one way relate by their heights only. + let mut pairs: Vec<(u32, u32, f64)> = Vec::new(); + let extras = b.w[8] as usize; + for &item in &ds[..nd] { + let cand = &b.w[b.w[4] as usize + CAND * (item & 0xffff) as usize..][..CAND]; + let e = &b.w[extras + cand[5] as usize + DISC * (item >> 16) as usize..][..DISC]; + let c = [f64::from(e[0] as i32), f64::from(e[1] as i32)]; + let (l0, l1) = (e[3], e[4]); + let past = norm(sub(q, c)) * b.mpu - f32w(e[2]) * b.mpu; + if cand[0] != FILL && l0 != u32::MAX && l1 != u32::MAX && b.way(l0) != b.way(l1) { + pairs.push((l0, l1, past)); + } + } + // A fan relates its two arms out to the greater feather past its circle. Two lines that each meet + // a third at a corner near q are related through it as far as that third line's own feather + // reaches past both corners: the arms of two junctions on a short link meet. Both fade over + // `via_fade_m` before the feather. + let n = out.len(); + let mut past = [[f64::INFINITY; SLOTS]; SLOTS]; + for &(l0, l1, d) in &pairs { + let (Some(i), Some(j)) = (out.iter().position(|r| r.line == l0), out.iter().position(|r| r.line == l1)) else { + continue; + }; + past[i][j] = past[i][j].min(d); + past[j][i] = past[i][j]; + } + for i in 0..n { + for j in 0..n { + if i == j { + continue; + } + let fade = |past: f64, feather: f64| phi((past - feather + p.via_fade_m) / p.via_fade_m); + let mut w = fade(past[i][j], out[i].feather.max(out[j].feather)); + // Through a third line only as far as it is present: it leaves the records a feather + // from its core, so the relation goes with its presence. + for (k, via) in out.iter().enumerate() { + if k != i && k != j { + w = w.max(fade(past[i][k].max(past[k][j]), via.feather) * fade(via.d, via.feather)); + } + } + out[i].rel[j] = w; + } + } + Present { recs: out, full } +} + +/// The paved field for host o (an index into `recs`). +fn paved(recs: &[Rec], o: usize, p: &HeightRules) -> f64 { + paved_as(recs, o, 0, recs[o].water, p) +} + +/// The rise from which two lines step instead of blending: the one that the lesser line's return +/// grade `ret` climbs over the greater line's feather (metres) at the steepness `blend_steep`. +pub fn step_limit(ret: f64, feather: f64, p: &HeightRules) -> f64 { + ret * feather / p.blend_steep +} + +/// The agreement of records i and j: a fan relates them, the face relates them as arms (a bit per +/// record in `arms`), or the rise between them is one that the lesser one's return grade climbs over +/// the greater one's feather. A return grade of 0 (water's) climbs no rise. +fn agree(recs: &[Rec], i: usize, j: usize, arms: u32, p: &HeightRules) -> f64 { + let (upper, lower) = if i < j { (&recs[i], &recs[j]) } else { (&recs[j], &recs[i]) }; + let wall = step_limit(lower.ret, upper.feather, p); + let ok = wall / 2.0; + let dz = (recs[i].z - recs[j].z).abs(); + let face = f64::from(u8::from((arms >> i) & (arms >> j) & 1 != 0)); + let rise = if wall > 0.0 { phi((dz - ok) / (wall - ok)) } else { 0.0 }; + rise.max(recs[i].rel[j]).max(face) +} + +/// The paved field for host o (`usize::MAX` for none: a blend face). Each other record weighs as far +/// as it agrees with the host, so a face takes no part of a way it disagrees with and two disagreeing +/// ways meet in a step where the host changes: on a face edge. `arms`: a bit per record that the face +/// relates to every other such record (a junction's arms in its region). The painter reads only the +/// records of its kind (`water`, the host's), as if no other were present: water meets a way only in +/// the slopes. +fn paved_as(recs: &[Rec], o: usize, arms: u32, water: bool, p: &HeightRules) -> f64 { + let n = recs.len(); + let mut beta = [0.0; SLOTS]; + for (b, r) in beta.iter_mut().zip(recs) { + *b = phi(r.d / r.feather); + } + let agree = |i: usize, j: usize| agree(recs, i, j, arms, p); + // Among them, a greater record i rules a lesser j as far as it is present: fully inside its core, + // so a host's core is exact, and by (1 − β) toward it, so the weight goes to 0 at that core's edge + // with no step. The host is ruled only as far as they agree and keeps its share (1 − c) there: + // disagreeing ways meet in a step where the host changes, on a face edge. A lesser record keeps a + // greater one off its ground as far as they disagree, but the host is never kept off. + let (mut sw, mut swz) = (0.0, 0.0); + let kind = |k: usize| recs[k].water == water; + for j in (0..n).filter(|&j| kind(j)) { + let mut w = if j == o || o >= n { beta[j] } else { beta[j] * agree(o, j) }; + for (i, &bi) in beta[..n].iter().enumerate().filter(|&(i, _)| kind(i)) { + if i < j { + w *= if j == o { 1.0 - bi * agree(i, j) } else { 1.0 - bi }; + } else if i > j && j != o { + // The host is never kept off, so its face always has a height of its own. + w *= 1.0 - bi * (1.0 - agree(i, j)); + } + } + sw += w; + swz += w * recs[j].z; + } + if sw > 0.0 { + swz / sw + } else if o < n { + recs[o].z + } else { + // No host and every record ruled out: the nearest one's own surface. + (0..n).filter(|&k| kind(k)).min_by(|&a, &c| recs[a].d.total_cmp(&recs[c].d)).map_or(f64::NAN, |k| recs[k].z) + } +} + +/// A cone's rise over metres d past the outline at slope s: rounded over the first `round_m`, so the +/// slope meets the paved field with no crease and a boundary a few centimetres off the true arc meets +/// it with no step. +fn cone(s: f64, d: f64, p: &HeightRules) -> f64 { + let a = p.round_m; + if d < a { + s * d * d / (2.0 * a) + } else { + s * (d - a / 2.0) + } +} + +/// The metres past the outline where a cone of slope s rises by `rise` (the inverse of `cone`): where +/// a bank's cut reaches its rise on level ground, the bank top. +pub(crate) fn cone_reach(s: f64, rise: f64, p: &HeightRules) -> f64 { + let a = p.round_m; + if rise <= 0.0 { + 0.0 + } else if rise < s * a / 2.0 { + (2.0 * a * rise / s).sqrt() + } else { + rise / s + a / 2.0 + } +} + +/// The no-room rule of a cone of slope s from a point of the outline that stands `need` above (a fill) or +/// below (a cut) the plain terrain where the cone should meet it (NaN unknown): a cone that at its own +/// slope does not meet the terrain where it starts to let go steepens up to the greatest slope `max`; the +/// rest is a wall, up to `wall` high. Past that the face steepens on, as steep as the need asks: with no +/// cap, it meets a cliff inside the run and the release has nothing left to take. A cone that starts +/// `crest` metres past its edge has that much less run. The slope and the wall, both continuous in the +/// need, so a need that runs on continuously along the outline gives a slope and a wall top with no step. +fn fit(s: f64, max: f64, need: f64, wall: f64, p: &HeightRules, reach: f64, crest: f64) -> (f64, f64) { + let run = (run(reach, p) - crest).max(1e-3); + let (s, max) = (s.min(p.face_max), max.min(p.face_max)); + if need.is_nan() { + return (s, 0.0); + } + let mut s = if need <= s * run { s } else { (need / run).min(max.max(s)) }; + if need - s * run > wall { + s = (need - wall) / run; + } + (s, (need - s * run).clamp(0.0, wall)) +} + +/// A value of an outline edge's ends at share f of it: linear between them, so two edges that share an end +/// give it alike there; an unknown end (NaN) takes the other end's. +fn at_share(v: [f64; 2], f: f64) -> f64 { + let [a, b] = match (v[0].is_nan(), v[1].is_nan()) { + (true, false) => [v[1]; 2], + (false, true) => [v[0]; 2], + _ => v, + }; + (1.0 - f) * a + f * b +} + +/// The fill's need at share f of an outline edge: the paved height less the terrain where its cones let go. +fn need_at(e: &Edge, f: f64) -> f64 { + at_share([e.h[0] - e.t[0], e.h[1] - e.t[1]], f) +} + +/// The metres over which a cone from its round foot should meet the terrain: up to where it lets go. +fn run(reach: f64, p: &HeightRules) -> f64 { + (reach * (1.0 - p.fade_share) - p.round_m / 2.0).max(1e-3) +} + +/// The toe and crest round's width in height for a cone pair of slopes sf (fill) and sc (cut) over +/// terrain rising `grade` per metre outward: the smooth min/max is about 2 k / (grade gap) metres +/// wide, so k = gap × `toe_span_m` / 2 rounds it over `toe_span_m` whatever the gap. +fn span_k(sf: f64, sc: f64, grade: f64, p: &HeightRules) -> f64 { + if grade.is_nan() { + return f64::INFINITY; + } + let gap = (grade + sf).abs().min((sc - grade).abs()).max(p.toe_gap_min); + 0.5 * p.toe_span_m * gap +} + +/// What gave a side its height: for a slope, the line whose cone or bank (in another line's budget) +/// holds it, whether two parts of that line hold each other there, and whether it stands on that wall +/// class's own wall, which a bank asks for and `wall_max_m` caps; for a paved side, its host line; for +/// a region, its arms (a bit per record). +#[derive(Clone, Copy, Debug)] +struct Cause { + by: Option, + arms: u32, + parts: bool, + wall: bool, + /// A deck's ceiling holds the side (`ceiling`). + ceiling: bool, +} + +const NO_CAUSE: Cause = Cause { by: None, arms: 0, parts: false, wall: false, ceiling: false }; + +impl Cause { + /// The records that host a paved side: its host, or a region's arms, which all host it. + fn hosts<'a>(&'a self, recs: &'a [Rec]) -> impl Iterator + 'a { + (0..recs.len()) + .filter(move |&k| if self.arms != 0 { self.arms >> k & 1 != 0 } else { self.by == Some(recs[k].line) }) + } +} + +/// How far a cone has let go at d metres from its edge, and by how much it has moved. Near the reach a +/// cone lets go: the fill sinks and the cut rises without bound, so at the reach the ground is the +/// terrain and a fading cut never digs into another way's fill. +fn release(d: f64, reach: f64, p: &HeightRules) -> (f64, f64) { + let w = reach * p.fade_share; + let fade = smoothstep((d - (reach - w)) / w); + (fade, p.fade_gap_m * fade / (1.0 - fade).max(1e-6)) +} + +/// An edge of the paved outline (`records`): its ends with the paved face on the left, its host line, +/// the paved height at each end, the plain terrain where the cones from each end start to let go and the +/// terrain's grade outward there (NaN unknown), and the outline's turn at each end to the edge that goes on +/// from it (radians, positive toward the paved face; NaN where none goes on). +#[derive(Clone, Copy, Debug)] +struct Edge { + a: [f64; 2], + b: [f64; 2], + line: u32, + h: [f64; 2], + t: [f64; 2], + grade: [f64; 2], + turn: [f64; 2], +} + +impl Block<'_> { + fn edge(&self, k: u32) -> Edge { + let w = &self.w[self.w[14] as usize + EDGE * k as usize..][..EDGE]; + let (a, b) = edge_ends(w); + let half = |g: u32, steps: f64| match g as u16 as i16 { + i16::MIN => f64::NAN, + g => f64::from(g) / steps, + }; + let (grade, turn) = (|g: u32| half(g, GRADE_STEPS), |t: u32| half(t, TURN_STEPS) * std::f64::consts::PI); + Edge { + a: [f64::from(a[0]), f64::from(a[1])], + b: [f64::from(b[0]), f64::from(b[1])], + line: edge_line(w), + h: [f32w(w[4]), f32w(w[5])], + t: [f32w(w[6]), f32w(w[7])], + grade: [grade(w[3] >> 16), grade(w[8])], + turn: [turn(w[9]), turn(w[8] >> 16)], + } + } +} + +/// Where q lies past an end of an outline edge, within the cone of that end: the end (0 a, 1 b) and the metres +/// to it. q lies `along` metres along the edge and `out` metres out from its line (negative into its paved +/// face); the edge is `len` metres long and turns by `turn` at its ends (`Edge::turn`). Past an end the outline +/// turns toward the paved face by t > 0 there, the end's cone covers the fan between the two edges' normals, +/// which the next edge's own cone covers too; where it turns the other way or goes on straight, the next edge +/// holds the ground; where no edge goes on, the cone covers all past the end. +fn fan(along: f64, out: f64, len: f64, turn: [f64; 2]) -> Option<(usize, f64)> { + let (x, end) = if along > len { + (along - len, 1) + } else if along < 0.0 { + (along, 0) + } else { + return None; + }; + let t = turn[end]; + if t.is_nan() { + return Some((end, libm::hypot(x, out))); + } + if t <= 0.0 { + return None; + } + // The next edge's direction at the end, as (along, out): its normal bounds the fan. + let (c, s) = (libm::cos(t), libm::sin(t)); + let before = if end == 1 { x * c - out * s <= 0.0 } else { x * c + out * s >= 0.0 }; + before.then(|| (end, libm::hypot(x, out))) +} + +/// The cone of an outline edge at q (sign 1 a fill, −1 a cut) whose top runs linearly from `top[0]` to +/// `top[1]`: across its strip the top falls at s, the line goes on past the ends' normals falling by `steep` +/// (a rock face) more than the edge climbs per metre, so it never holds the next edge's ground; within an +/// end's fan (`fan`) the end's own cone at s. So a rim cut or bent anywhere gives the ground of the uncut rim, +/// and the ground is continuous. q lies `along` metres along the edge and `out` metres out from its line. With +/// a crest b the cone falls from b metres out: the cone of the outline grown by b, level within b of it. +#[allow(clippy::too_many_arguments)] +fn edge_cone( + along: f64, + out: f64, + len: f64, + top: [f64; 2], + s: f64, + sign: f64, + turn: [f64; 2], + steep: f64, + crest: f64, +) -> f64 { + let g = if len > 0.0 { (top[1] - top[0]) / len } else { 0.0 }; + let past = (-along).max(along - len).max(0.0); + let line = top[0] + g * along - sign * (s * (out.abs() - crest).max(0.0) + (steep + g.abs()) * past); + match fan(along, out, len, turn) { + Some((end, r)) if sign > 0.0 => line.max(top[end] - s * (r - crest).max(0.0)), + Some((end, r)) => line.min(top[end] + s * (r - crest).max(0.0)), + None => line, + } +} + +/// How much the round of a cone of slope s at its foot (`cone`) holds it back at d metres from its +/// outline. A line's envelope takes it once, at its nearest edge: a round in each edge's cone would let +/// a neighbour edge up or down the outline's grade pass the foot's own height there. +fn round_back(s: f64, d: f64, p: &HeightRules) -> f64 { + s * d - cone(s, d, p) +} + +/// An outline edge's cone reaches this many frame units past its line into its paved face before it +/// falls on as a rock face. +const SIDE_UNITS: f64 = 32.0; + +/// One host line's outline near q: its released fill and cut, the cut it may rise to toward its budget +/// (`steep`: a wall class's wall up to `wall_max_m`, then any class's steepest cut), the metres to its +/// nearest edge, the least toe width of its edges, whether it is a wall class, and how far it has let +/// go. `plain`: its fill without a rise and a crest, which bounds its own cut (a way's is its fill). +#[derive(Clone, Copy, Debug)] +struct Group { + line: u32, + class: u32, + glob: u32, + rail: bool, + wall: bool, + water: bool, + /// The highest wall at its edge (`Line::wall_max`). + cap: f64, + fill: f64, + plain: f64, + cut: f64, + steep: f64, + d: f64, + toe: f64, + fade: f64, +} + +/// The host lines of the outline edges near q (q's bin), at most `SLOTS` in the painter's order, and +/// whether that cap left some out. Per edge within its host's reach: its fill and its cut, each the +/// extreme over the edge's points, by the no-room rule of the need at q's foot on it and released by its +/// own distance. +fn groups(b: &Block, q: [f64; 2], p: &HeightRules) -> (Vec, bool) { + let mut out: Vec = Vec::new(); + let mut at: Option<(Line, Group)> = None; + // A line's group ends where the bin's next edge has another host. + let close = |at: Option<(Line, Group)>, out: &mut Vec| { + let Some((ln, mut g)) = at.filter(|(_, g)| g.d.is_finite()) else { return }; + g.fade = release(g.d, ln.reach, p).0; + g.plain += round_back(ln.fill, g.d, p); + g.fill += round_back(ln.fill, (g.d - ln.crest).max(0.0), p); + g.cut -= round_back(ln.cut, g.d, p); + g.steep -= round_back(ln.steepest_cut(p), g.d, p); + out.push(g); + }; + for k in outline_items(b, q) { + let e = b.edge(k); + if at.as_ref().is_none_or(|(_, g)| g.line != e.line) { + close(at.take(), &mut out); + let ln = b.line(e.line as usize); + let (class, glob, rail, wall, water, cap) = + (ln.class, b.glob(&ln, 0), ln.rail, ln.wall, ln.water, ln.wall_max(p)); + let (fill, cut, steep, d, toe) = + (f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY, f64::INFINITY, f64::INFINITY); + let g = Group { + line: e.line, + class, + glob, + rail, + wall, + water, + cap, + fill, + plain: fill, + cut, + steep, + d, + toe, + fade: 1.0, + }; + at = Some((ln, g)); + } + let Some((ln, g)) = at.as_mut() else { continue }; + // Metres along and off the edge from q − a, which two cells give alike. + let (ab, v) = (sub(e.b, e.a), sub(q, e.a)); + let len = norm(ab); + let u = if len > 0.0 { [ab[0] / len, ab[1] / len] } else { [1.0, 0.0] }; + let out = -cross(u, v); + let (along, off, len) = (dot(v, u) * b.mpu, out.abs() * b.mpu, len * b.mpu); + let foot = along.clamp(0.0, len) - along; + let d = (foot * foot + off * off).sqrt(); + if d >= ln.reach { + continue; + } + let (fade, relax) = release(d, ln.reach, p); + // The slope and the wall at q's foot on the edge, from the need there. The fill starts `rise` over + // the edge and `crest` past it. + let share = if len > 0.0 { (along / len).clamp(0.0, 1.0) } else { 0.0 }; + let need = need_at(&e, share); + let (sf, wf) = fit(ln.fill, ln.fill_max, need + ln.rise, ln.wall_max(p), p, ln.reach, ln.crest); + let (sc, wc) = fit(ln.cut, ln.cut_max, -need, ln.wall_max(p), p, ln.reach, 0.0); + g.d = g.d.min(d); + // An edge's toe width lets go with its cone, so an edge that leaves at the reach leaves no step + // in the least width; past an end's normal outside the end's fan it widens at a rock face's slope, as + // its cone falls on (`edge_cone`). + let past = + if fan(along, out * b.mpu, len, e.turn).is_some() { 0.0 } else { (-along).max(along - len).max(0.0) }; + let w = toe_width(d, span_k(sf, sc, at_share(e.grade, share), p), p) + p.face_max * past; + g.toe = g.toe.min(w + fade * (p.toe_max_m - w)); + // An edge's cone stands on its outward side, the side of its slope face. Past its line into its + // paved face (from `SIDE_UNITS` on, where a face's own whole-unit rim and a point read beside it + // lie) it falls on at a rock face's slope: a cone from the far side of a face never holds the + // near edge's slope at its own fit, and the ground stays continuous where an edge's line passes. + let inside = if len > 0.0 { (-out - SIDE_UNITS).max(0.0) * b.mpu * p.face_max } else { 0.0 }; + // The cone from the paved height moved by `rise` (a wall's top), sign 1 a fill, −1 a cut. + let cone = |rise: f64, s: f64, sign: f64, crest: f64| { + let top = [e.h[0] + rise, e.h[1] + rise]; + edge_cone(along, out * b.mpu, len, top, s, sign, e.turn, p.face_max, crest) + }; + let (fill, cut) = (cone(ln.rise - wf, sf, 1.0, ln.crest), cone(wc, sc, -1.0, 0.0)); + let plain = if ln.rise > 0.0 || ln.crest > 0.0 { + let (sp, wp) = fit(ln.fill, ln.fill_max, need, ln.wall_max(p), p, ln.reach, 0.0); + cone(-wp, sp, 1.0, 0.0) + } else { + fill + }; + g.fill = g.fill.max(fill - relax - inside); + g.plain = g.plain.max(plain - relax - inside); + g.cut = g.cut.min(cut + relax + inside); + // The highest cut toward the budget: a wall class's wall up to `wall_max_m` at its edge, then for + // every class a face at its steepest cut from the wall's top (from the edge where it has none). + let (steep, rise) = (ln.steepest_cut(p), ln.wall_max(p)); + let (ss, _) = fit(steep, steep, -need - rise, 0.0, p, ln.reach, 0.0); + let cut = cone(rise, ss, -1.0, 0.0); + g.steep = g.steep.min(cut + relax + inside); + } + close(at, &mut out); + out.sort_by_key(|g| (g.class, g.glob, g.line)); + let full = out.len() > SLOTS; + if full { + crate::probe::hit(crate::probe::Cap::Slots); + } + out.truncate(SLOTS); + (out, full) +} + +/// Whether line j's fill counts in the soft bank budget of line k: another line's, and a road's, not a +/// rail's or water's. A budget comes from road surfaces, so a stream's dyke lifts no road's cut; a rail's +/// fill counts only past its wall cap (`slope`). +fn counts(groups: &[Group], j: usize, k: usize) -> bool { + j != k && !groups[j].rail && !groups[j].water +} + +/// The slope field: per host line of the outline edges near q, its fill and cut from the paved outline; +/// then `min(cut, max(T, fill))`, smooth at the toe and crest by a width that grows from 0 at the +/// nearest outline. With the line that holds the ground. +/// +/// The bank budget B of a line: the soft greatest fill (`soft_top`) of the lines that count for it. +/// The fill envelope: the soft greatest of all fills. A soft greatest never rises above the greatest +/// fill, so where two fills nearly tie (two arms at a corner, two close roads, two legs of one line) it +/// lifts nothing, and at the greatest fill's own edge it is that fill: no step stands at an upper +/// road's edge. +/// +/// A line's cut rises toward B up to `steep`. A wall class's rises to B up to `wall_max_m` at its edge: +/// the higher line's bank reaches down to the lower line's edge, and the step there is the one wall of +/// the pair. Past the wall's top the cut rises at its steepest (`cut_max`, at most `face_max`), with no +/// step. Another class steepens its cut from its edge, so its own edge never walls. +fn slope(b: &Block, q: [f64; 2], t: f64, p: &HeightRules) -> (f64, Cause) { + let (groups, _) = groups(b, q, p); + if groups.is_empty() { + return (t, NO_CAUSE); + } + let (mut hi, mut toe) = (f64::INFINITY, p.toe_max_m); + let mut hi_by = NO_CAUSE; + let mut at = [(f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY, 0.0); SLOTS]; + for (k, g) in groups.iter().enumerate() { + // The toe's width grows from 0 at this line's outline, never past the gap between its cut and + // fill: the smooth min and max move the ground by up to a quarter of the width, so a wider + // round would lift a slope off its paved edge. A hard min would crease the slope where the + // two widths cross. A line that lets go leaves it alone. + // A fill that its rise lifts over the cut (a waterline) gives a gap under 0: a hard crease. + let kq = soft_min(g.toe, g.cut - g.fill); + toe = toe.min(kq + g.fade * (p.toe_max_m - kq)); + at[k] = (g.fill, g.cut, g.steep, g.d); + } + // A line holds the ground with two of its parts where its own plain fill passes its cut. + let by = |k: Option| Cause { + by: k.map(|k| groups[k].line), + arms: 0, + parts: k.is_some_and(|k| groups[k].plain > at[k].1), + wall: false, + ceiling: false, + }; + let (lo, top) = soft_top(&at, 0..groups.len(), p); + let lo_by = by(top); + // The least of the cuts before their rise, and the bank that lifts it if one does. + let (mut own, mut own_bank) = (f64::INFINITY, None); + for k in 0..groups.len() { + let (_, cut, steep, d) = at[k]; + let counted = || (0..groups.len()).filter(|&j| counts(&groups, j, k)); + let (budget, held) = soft_top(&at, counted(), p); + // Another line's rail bed counts with its fill less its wall cap: up to a wall high it gives the line no + // wall, a higher one lifts its cut by the rest, on which the line stands as on its own wall. The rail + // bed's own step stays the step of the line's cut. + let rails = (0..groups.len()).filter(|&j| j != k && groups[j].rail); + let rail = rails.map(|j| at[j].0 - groups[j].cap).fold(f64::NEG_INFINITY, f64::max); + let (budget, lifter) = if rail > budget { + (rail, Cause { wall: true, ..by(Some(k)) }) + } else { + (budget, by(Some(held.unwrap_or(k)))) + }; + // The round of the cut's rise to B grows from 0 at k's outline and at the outline of every line + // that counts in B, as the toe round: a wall's foot, a bank that ends at the edge and the upper + // line's own edge stay exact. The least distance over them is continuous where the line that + // gives B changes. + let w = toe_width(counted().map(|j| at[j].3).fold(d, f64::min), p.budget_round_m, p); + // The cut rises to min(budget, steep) in the same round: where the bank begins, the cut and the + // bank meet in a round. With the line that gives it. Two parts of one line that no leg cut parts + // (a switchback) hold each other as two lines do, by the hard maximum with the line's own fill: + // only where that fill passes the line's cut, so it changes nothing where the line agrees + // with itself. + let lift = smin(budget, steep, w); + let v = smax(cut, lift, w).max(groups[k].plain.min(steep)); + if cut < own { + let lifted = lift > cut && budget <= steep; + (own, own_bank) = (cut, lifted.then_some(lifter)); + } + // Where the budget passes `steep`, a wall class stands on its own wall and the face past it. + let side = match (lift > cut, budget <= steep) { + (true, true) => (v, lifter), + (true, false) if groups[k].wall => (v, Cause { wall: true, ..by(Some(k)) }), + _ => (v, by(Some(k))), + }; + if side.0 < hi { + (hi, hi_by) = side; + } + } + // The round lifts the ground by up to a quarter of its width, so it narrows to 0 at the band's + // outer edge, over all of `MARGIN_M` (past which `slope_edge` is a bound, not a distance): a + // round that narrows over less drops its lift in a crease, and one that stays wide leaves a lip + // for the band fade. + let edge = slope_edge(b, q); + let toe = toe * smoothstep(edge / MARGIN_M); + let g = smin(hi, smax(t, lo, toe), toe); + // The slope band's outer edge is the terrain's: the ground meets it there whatever the band's + // shape (corner rings, square ends at a structure). + let g = t + smoothstep(edge / p.band_fade_m) * (g - t); + // The line that holds the ground is the bound that min(hi, max(t, lo)) takes before the rounds: a + // round moves the ground toward the terrain by a few centimetres where the bounds nearly meet, and + // must not move the cause with it. Ground that stands above the least cut stands on that cut's bank. + let by = if let Some(bank) = own_bank.filter(|_| t.max(lo).min(hi) > own) { + bank + } else if hi < t.max(lo) { + hi_by + } else if lo > t { + lo_by + } else { + NO_CAUSE + }; + (g, by) +} + +/// The no-room walls of line l's outline at q, as the tops of the fill's and the cut's wall (the top +/// equals the edge's height where a cone has no wall), and how far the line's steepest cone climbs +/// between them and q: of its edge nearest q in q's bin, at q's foot on it. None where q's bin lists no +/// edge of l. +fn walls(b: &Block, q: [f64; 2], l: u32, p: &HeightRules) -> Option<([(f64, f64); 2], f64)> { + let ln = b.line(l as usize); + let mut best: Option<(f64, f64, f64, f64)> = None; + for k in outline_items(b, q) { + let e = b.edge(k); + if e.line != l { + continue; + } + let ab = sub(e.b, e.a); + let l2 = dot(ab, ab); + let f = if l2 > 0.0 { (dot(sub(q, e.a), ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let d = off_foot(q, e.a, ab, f); + if best.is_some_and(|w| w.0 <= d) { + continue; + } + let need = need_at(&e, f); + let (_, wf) = fit(ln.fill, ln.fill_max, need + ln.rise, ln.wall_max(p), p, ln.reach, ln.crest); + let (_, wc) = fit(ln.cut, ln.cut_max, -need, ln.wall_max(p), p, ln.reach, 0.0); + best = Some((d, wf, wc, e.h[0] + f * (e.h[1] - e.h[0]))); + } + // The fill's wall stands under its top, which the rise lifts. + best.map(|(d, wf, wc, h)| ([(wf, h + ln.rise - wf), (wc, h + wc)], p.face_max * d * b.mpu)) +} + +/// A unit vector from `pack2x16snorm` words. +fn snorm2(w: u32) -> [f64; 2] { + unit([f64::from(w as u16 as i16) / 32767.0, f64::from((w >> 16) as u16 as i16) / 32767.0]) +} + +/// Per ceiling line segment of q's height segments (`segs`, whose ceiling lines come last): the metres of q +/// outside the deck's stroke, the deck's surface at q's foot (banked as the line's surface is across its +/// stroke, level past it) less its drop, which is the bound inside the stroke, and the drop. The stroke ends +/// flat at each end of the line, on the line through the end sample along its `flat` normal: a segment whose +/// start lies within its half-width and `ceiling_release_m` of an end, along the line, holds q past that end +/// line as past its own end. The end segments reach on along their chord to the flat ends. +fn decks<'a>( + b: &'a Block, + q: [f64; 2], + segs: &'a [u32], + p: &'a HeightRules, +) -> impl Iterator + 'a { + // The storeys' lines over the ground come after the ceiling lines. + let lines = segs.iter().rev().map(move |&item| (b.line((item & 0xffff) as usize), (item >> 16) as usize)); + let ceilings = lines.skip_while(|(ln, _)| ln.storey != 0).map_while(|(ln, i)| ln.ceiling.then_some((ln, i))); + ceilings.filter_map(move |(ln, i)| { + let (sa, sb) = (b.sample(&ln, i), b.sample(&ln, i + 1)); + let ab = sub(sb.p, sa.p); + let len = norm(ab); + if len <= 0.0 { + return None; + } + let u = [ab[0] / len, ab[1] / len]; + let v = sub(q, sa.p); + let (t, lateral) = (dot(v, u), -cross(u, v) * b.mpu); + let (f, across) = if (i == 0 && t < 0.0) || (i + 2 == ln.count && t > len) { + (if t < 0.0 { 0.0 } else { 1.0 }, lateral.abs()) + } else { + let f = (t / len).clamp(0.0, 1.0); + (f, off_foot(q, sa.p, ab, f) * b.mpu) + }; + let half = sa.h + f * (sb.h - sa.h); + // Metres behind each flat end that this segment reaches. + let last = ln.count - 1; + let behind = |e: usize, near: bool| { + let at = b.position(&ln, if e == 0 { 0 } else { last }); + if near { + -dot(sub(q, at), snorm2(ln.flat[e])) * b.mpu + } else { + 0.0 + } + }; + let near = [ + b.along(&ln, i) - b.along(&ln, 0) <= sa.h + p.ceiling_release_m, + b.along(&ln, last) - b.along(&ln, i + 1) <= sb.h + p.ceiling_release_m, + ]; + let past = behind(0, near[0]).max(behind(1, near[1])).max(0.0); + let out = libm::hypot((across - half).max(0.0), past); + let len_m = len * b.mpu; + let bank = sa.bank + f * (sb.bank - sa.bank); + let z = hermite(sa.z, sb.z, sa.grade * len_m, sb.grade * len_m, f) + bank * lateral.clamp(-half, half); + Some((out, z - ln.ret, ln.ret)) + }) +} + +/// The ceiling at q: the least over the decks near q of their bound inside their stroke (`decks`), past it +/// rising at `face_max` per metre and letting go as a cone does over `ceiling_release_m`, so the ground that it +/// bounds has no step; infinite where no deck is near. +fn ceiling(b: &Block, q: [f64; 2], segs: &[u32], p: &HeightRules) -> f64 { + decks(b, q, segs, p) + .filter(|&(out, ..)| out < p.ceiling_release_m) + .map(|(out, base, _)| base + p.face_max * out + release(out, p.ceiling_release_m, p).1) + .fold(f64::INFINITY, f64::min) +} + +/// The least bound of the decks whose stroke holds q (their underside less `ceiling_gap_m`) and that deck's +/// drop; none outside every stroke. +pub(crate) fn under_deck(words: &[u32], q: [f64; 2]) -> Option<(f64, f64)> { + let b = Block::at(words, q); + let p = HeightRules::of(words); + let items = bin_items(&b, q)?; + let inside = decks(&b, q, items.segs, &p).filter(|&(out, ..)| out <= 0.0); + inside.map(|(_, base, drop)| (base, drop)).reduce(|a, c| if c.0 < a.0 { c } else { a }) +} + +/// The height rule of a label (0 for none). +fn rule_of(words: &[u32], label: Option) -> u32 { + label.map_or(0, |id| words[words[5] as usize + LABEL * id as usize] >> 24) +} + +/// The height at q (frame units from the cell's origin), with the label there (`records::find`) and +/// the plain terrain t there. +pub fn height_at(words: &[u32], q: [f64; 2], label: Option, t: f64) -> Height { + let rule = rule_of(words, label); + let b = Block::at(words, q); + let p = HeightRules::of(words); + let Some(items) = bin_items(&b, q) else { return by_label(&b, q, &[], &NO_ITEMS, label, t, &p).0 }; + let recs = if rule >= 2 { present(&b, q, &p, [material(words, label), u32::MAX], &items).recs } else { Vec::new() }; + by_label(&b, q, &recs, &items, label, t, &p).0 +} + +/// The heights at q of the two sides of an edge, with their labels, and the rule of the step between +/// them: the records present at q are found once. +pub fn height_at_sides(words: &[u32], q: [f64; 2], labels: [Option; 2], t: f64) -> [Height; 2] { + let b = Block::at(words, q); + let p = HeightRules::of(words); + let items = bin_items(&b, q).unwrap_or(NO_ITEMS); + let paved = labels.iter().any(|&l| rule_of(words, l) >= 2) && !items.segs.is_empty(); + let recs = if paved { present(&b, q, &p, labels.map(|l| material(words, l)), &items).recs } else { Vec::new() }; + let sides = labels.map(|l| by_label(&b, q, &recs, &items, l, t, &p)); + let surface = |l: Option| l.map(|id| label_words(words, id)[0] & 0xff); + let ends = labels.map(surface); + let [water, zone] = [Surface::Water, Surface::Zone].map(|s| Some(s as u32)); + let mouth = (ends == [water, zone] || ends == [zone, water]) && (sides[0].0.h - sides[1].0.h).abs() > p.step_m; + let step = if mouth { Step::Mouth } else { step(&b, q, &recs, &sides, &p) }; + sides.map(|(h, _)| Height { step, ..h }) +} + +/// The paved height at q by paved label `id` from the items about q, with the host line as `owner`: the +/// one read of the paved field for the outline's ends (`records` reads them through its window's bins, +/// which list a bin's items). None where the face has no height of its own there: a host face whose +/// host the records lack, a region with no record of its kind present (`check::Scan::host_missing`). +/// Only those read the terrain. +pub(crate) fn paved_end(words: &[u32], q: [f64; 2], id: u32, items: &Items) -> Option { + let b = Block::at(words, q); + let p = HeightRules::of(words); + let recs = present(&b, q, &p, [material(words, Some(id)), u32::MAX], items).recs; + let h = by_label(&b, q, &recs, items, Some(id), f64::NAN, &p).0; + let own = if rule_of(words, Some(id)) == 3 { + recs.iter().any(|r| r.water == b.water(material(words, Some(id)))) + } else { + h.owner != u32::MAX + }; + own.then_some(h) +} + +/// Record line l's frame at q from the segments of `items` (`paved_end`'s): the unit direction from the line +/// toward q and the unit direction along the line. In the mitre quad that holds q (the one nearest across +/// where quads overlap) these are across and along the frame's mitre at q's share, so they turn +/// continuously from quad to quad; past the line's first or last sample, the direction from that sample, +/// which turns continuously round a free end. None where no listed segment of l holds q. +pub(crate) fn frame(words: &[u32], q: [f64; 2], l: u32, items: &Items) -> Option<([f64; 2], [f64; 2])> { + let b = Block::at(words, q); + let ln = b.line(l as usize); + let mut best: Option<(f64, [f64; 2], [f64; 2])> = None; + for i in items.segs.iter().filter(|&&s| s & 0xffff == l).map(|&s| (s >> 16) as usize) { + let (pa, pb, ta, tb) = (b.position(&ln, i), b.position(&ln, i + 1), b.mitre(&ln, i), b.mitre(&ln, i + 1)); + let (v, ab) = (sub(q, pa), sub(pb, pa)); + let (da, db) = (dot(v, ta), dot(sub(pb, q), tb)); + let (out, along) = if da >= 0.0 && db >= 0.0 { + let t = if da + db > 0.0 { da / (da + db) } else { 0.5 }; + let m = unit([ta[0] + t * (tb[0] - ta[0]), ta[1] + t * (tb[1] - ta[1])]); + let along = dot(ab, m); + let f = if along != 0.0 { dot(v, m) / along } else { 0.0 }; + ([v[0] - f * ab[0], v[1] - f * ab[1]], m) + } else if i == 0 && da < 0.0 && db >= 0.0 { + (v, unit(ab)) + } else if i + 2 == ln.count && db < 0.0 && da >= 0.0 { + (sub(q, pb), unit(ab)) + } else { + continue; + }; + let d = norm(out); + if d > 0.0 && best.is_none_or(|(least, ..)| d < least) { + best = Some((d, [out[0] / d, out[1] / d], along)); + } + } + best.map(|(_, out, along)| (out, along)) +} + +/// Within this many frame units of a line's end line, a point lies on it: the stroke's corners are +/// whole units. +const END_UNITS: f64 = 2.0; + +/// The rule of the step between two sides at q, if the step lies within that rule's size (up to +/// `step_m` more): a no-room wall up to its top or up to the terrain, the disagreement of two hosts. +fn step(b: &Block, q: [f64; 2], recs: &[Rec], sides: &[(Height, Cause); 2], p: &HeightRules) -> Step { + if (sides[0].0.h - sides[1].0.h).abs() <= p.step_m { + return Step::None; + } + // An end face: beside a paved side on the deck end line of a line present (one of several ways that end + // there need not host the face), whatever the lower side; or where the ceiling holds the lower side. + let lower = if sides[0].0.h < sides[1].0.h { &sides[0] } else { &sides[1] }; + let on_deck_end = |r: &Rec| { + let ln = b.line(r.line as usize); + (0..2).any(|e| { + let i = if e == 0 { 0 } else { ln.count - 1 }; + let across = cross(b.mitre(&ln, i), sub(q, b.position(&ln, i))).abs() * b.mpu; + ln.deck[e] && b.past_end(&ln, e, q).abs() <= END_UNITS * b.mpu && across <= b.half(&ln, i) + ln.side + }) + }; + if lower.1.ceiling || (sides.iter().any(|(h, _)| h.kind == Kind::Paved) && recs.iter().any(on_deck_end)) { + return Step::EndFace; + } + let within = |rise: f64, size: f64| rise * size > 0.0 && rise.abs() <= size.abs() + p.step_m; + for (a, o) in [(&sides[0], &sides[1]), (&sides[1], &sides[0])] { + let (Kind::Slope, Kind::Paved) = (a.0.kind, o.0.kind) else { continue }; + let rise = a.0.h - o.0.h; + for h in o.1.hosts(recs) { + // A host's no-room walls at its outline: the slope side stands on one, up to the wall's + // top or up to the terrain. + let Some((tops, climb)) = walls(b, q, recs[h].line, p) else { continue }; + let on = |top: f64| rise * (top - o.0.h) > 0.0 && rise.abs() <= (top - o.0.h).abs() + climb + p.step_m; + if tops.iter().any(|&(wall, top)| wall > 0.0 && on(top)) { + return Step::NoRoom; + } + } + // Another line's cone or bank holds the slope side: the bank of a higher line at a lower line's + // edge (an arm's at its region's edge), or a cut at a higher line's edge; or another part of + // the host line, as two lines. A step at a line's own edge held by its own fill is no wall: the + // design puts none at an upper edge. + if let (Some(c), Some(_)) = (a.1.by, o.1.hosts(recs).next()) { + // A side on its own line's wall stands up to `wall_max_m` above the edge, as a no-room wall. + let walled = || rise > 0.0 && walls(b, q, c, p).is_some_and(|w| rise <= p.wall_max_m + w.1 + p.step_m); + if a.1.wall && walled() { + return Step::Held; + } + if a.1.parts || o.1.hosts(recs).all(|h| recs[h].line != c) { + // Up to the paved side's wall cap: past it a fault, which the steep face past a wall's top would + // have taken where the two outlines leave room for it. + let capped = |h: usize| { + let ln = b.line(recs[h].line as usize); + let climb = walls(b, q, recs[h].line, p).map_or(0.0, |w| w.1); + rise.abs() <= ln.wall_max(p) + climb + p.step_m + }; + return if o.1.hosts(recs).any(capped) { Step::Held } else { Step::HeldOverCap }; + } + } + } + // Two paved sides of the two kinds (water and a way): no painter relates them, so any step. + let [(ha, ca), (hb, cb)] = sides; + if let (Kind::Paved, Kind::Paved) = (ha.kind, hb.kind) { + for (i, j) in ca.hosts(recs).flat_map(|i| cb.hosts(recs).map(move |j| (i, j))) { + let apart = recs[i].water != recs[j].water; + if i != j && agree(recs, i, j, 0, p) < 1.0 && (apart || within(ha.h - hb.h, recs[i].z - recs[j].z)) { + return Step::Unrelated; + } + } + } + // A paved side at the end of a host at a level change, where the slope band ends square and fades + // into the terrain over `band_fade_m`. + for (h, c) in sides { + for i in c.hosts(recs).filter(|_| h.kind == Kind::Paved) { + let ln = b.line(recs[i].line as usize); + let near = |e: usize| ln.level[e] && (-p.band_fade_m..=END_UNITS * b.mpu).contains(&b.past_end(&ln, e, q)); + if near(0) || near(1) { + return Step::StructureEnd; + } + } + } + Step::None +} + +/// At most this many regions beyond a region's edges weigh at a point (the nearest); the GPU port holds +/// the same, and the fixture check `slots_full` shows that no point has more. +pub const REGIONS: usize = 2; + +/// A junction's region (a blend face) at q: its own painter (`own`), which relates its arms, and near +/// each of its edges toward another paved face a fade to that face. A paved face beyond gives its +/// host's painter, which is that face's height; another region gives the painter that relates both +/// regions' arms, the same from both sides. Toward a slope or the terrain the region keeps its own +/// painter: the slope starts at its outline from it. Per group of edges, D its least distance, +/// s = smoothstep(D / `region_fade_m`) and ω = σ (1 − s) / s; the height is (own + Σ ω V) / (1 + Σ ω). +/// So it is V on the edge, with V's slope there, and `own` from `region_fade_m` on. σ is a host's +/// presence times the region's agreement with it (a line that disagrees with every arm keeps its step +/// on the edge), else 1. The distances are read up to `region_fade_m` only, where two cells give the +/// same bits (the records' border check holds it). `water`: the region's kind, its material line's. +#[allow(clippy::too_many_arguments)] +fn region( + b: &Block, + q: [f64; 2], + recs: &[Rec], + label: u32, + arms: u32, + blend: &[u32], + water: bool, + p: &HeightRules, +) -> f64 { + let n = recs.len(); + let own = paved_as(recs, usize::MAX, arms, water, p); + let beta = |k: usize| phi(recs[k].d / recs[k].feather); + let arm = |k: usize| arms >> k & 1 != 0; + // The least metres to the edges of each host beyond, at its record's index; the regions beyond + // apart, the nearest `REGIONS`. + let mut dist = [f64::INFINITY; SLOTS]; + let mut beyond = [(u32::MAX, f64::INFINITY); REGIONS]; + for e in blend.iter().map(|&k| blend_edge(b.w, k)).filter(|e| e.region == label) { + let v = |p: [i32; 2]| [f64::from(p[0]), f64::from(p[1])]; + let d = to_segment(q, v(e.a), v(e.b)) * b.mpu; + if d >= p.region_fade_m { + continue; + } + let Some(other) = e.other else { continue }; + let rule = label_words(b.w, other)[0] >> 24; + if rule == 3 { + let k = beyond.iter().position(|g| g.0 == other).unwrap_or(REGIONS - 1); + if beyond[k].0 != other && beyond[k].0 != u32::MAX { + crate::probe::hit(crate::probe::Cap::Regions); + } + if d < beyond[k].1 { + beyond[k] = (other, d); + beyond.sort_by(|a, c| a.1.total_cmp(&c.1)); + } + continue; + } + // A paved face beyond: its host line, if it has one. + let material = label_words(b.w, other)[2]; + if let Some(g) = (rule == 2 || rule == 4).then(|| recs.iter().position(|r| r.line == material)).flatten() { + dist[g] = dist[g].min(d); + } + } + // Each group's distance, σ and target, in the painter's order: the hosts, then the regions. + let mut groups: Vec<(f64, f64, f64)> = Vec::with_capacity(n + REGIONS); + for g in (0..n).filter(|&g| dist[g] < p.region_fade_m) { + let agreed = (0..n).filter(|&k| arm(k)).map(|k| beta(k) * agree(recs, k, g, arms, p)).fold(0.0, f64::max); + groups.push((dist[g], beta(g) * agreed, paved(recs, g, p))); + } + let mut regions: Vec<(f64, f64, f64)> = (beyond.iter().filter(|g| g.0 != u32::MAX)) + .map(|&(other, d)| (d, 1.0, paved_as(recs, usize::MAX, arms | arms_of(b.w, recs, other), water, p))) + .collect(); + regions.sort_by(|a, c| a.0.total_cmp(&c.0).then(a.2.total_cmp(&c.2))); + groups.extend(regions); + let (mut sw, mut sv) = (1.0, 0.0); + for (d, sigma, v) in groups.into_iter().filter(|g| g.1 > 0.0) { + let s = smoothstep(d / p.region_fade_m); + if s <= 0.0 { + return v; + } + let w = sigma * (1.0 - s) / s; + (sw, sv) = (sw + w, sv + w * (v - own)); + } + own + sv / sw +} + +/// Whether more than `REGIONS` regions lie beyond the edges of region `label` within `region_fade_m` +/// of q: then the farthest are left out. +fn regions_full(w: &[u32], q: [f64; 2], label: u32, p: &HeightRules) -> bool { + let mpu = Block::at(w, q).mpu; + let mut seen: Vec = Vec::new(); + for e in super::records::blend_edges(w, q).filter(|e| e.region == label) { + let v = |p: [i32; 2]| [f64::from(p[0]), f64::from(p[1])]; + let other = e.other.unwrap_or(u32::MAX); + let near = to_segment(q, v(e.a), v(e.b)) * mpu < p.region_fade_m; + if near && other != u32::MAX && label_words(w, other)[0] >> 24 == 3 && !seen.contains(&other) { + seen.push(other); + } + } + seen.len() > REGIONS +} + +/// The records that a region relates as its junction's arms (its material line and its junction's arms, +/// or a way's host and other lines), a bit each. +fn arms_of(words: &[u32], recs: &[Rec], id: u32) -> u32 { + let l = label_words(words, id); + let jr = junction(words, id); + let named = |line: u32| { + line == l[2] || jr.map_or(l[4..12].contains(&line), |jr| jr[JR..].chunks(JR_ARM).any(|a| a[0] & 0xffff == line)) + }; + recs.iter().enumerate().filter(|(_, r)| named(r.line)).fold(0, |m, (i, _)| m | 1 << i) +} + +/// The material line of a paved label (owner, blend or kerb rule), u32::MAX for none. +fn material(words: &[u32], label: Option) -> u32 { + let Some(id) = label else { return u32::MAX }; + let a = words[5] as usize + LABEL * id as usize; + if words[a] >> 24 >= 2 { + words[a + 2] + } else { + u32::MAX + } +} + +/// The host: the label's material line, so it is the same over the whole face; None where the records +/// lack it. A face with no material line (a way's band face, until it gets one) takes the first way +/// record whose core holds q, else the nearest way record. +fn host(recs: &[Rec], material: u32) -> Option { + if material != u32::MAX { + return recs.iter().position(|r| r.line == material); + } + let ways = || (0..recs.len()).filter(|&k| !recs[k].water); + ways().find(|&k| recs[k].d <= 0.0).or_else(|| ways().min_by(|&a, &c| recs[a].d.total_cmp(&recs[c].d))) +} + +/// The height at q by the label's height rule, from the records present there and the items about q (a +/// region's blend edges, the ceilings' segments), and its cause. The ground (the terrain and the slope rules) +/// stays under the ceiling. +fn by_label( + b: &Block, + q: [f64; 2], + recs: &[Rec], + items: &Items, + label: Option, + t: f64, + p: &HeightRules, +) -> (Height, Cause) { + let words = b.w; + let lw = |k: usize| label.map_or(u32::MAX, |id| words[words[5] as usize + LABEL * id as usize + k]); + let rule = if label.is_some() { lw(0) >> 24 } else { 0 }; + let height = + |h: f64, kind: Kind, by: Option| Height { h, kind, owner: by.unwrap_or(u32::MAX), step: Step::None }; + if rule <= 1 { + let ((h, cause), kind) = + if rule == 0 { ((t, NO_CAUSE), Kind::Terrain) } else { (slope(b, q, t, p), Kind::Slope) }; + let c = ceiling(b, q, items.segs, p); + if c < h { + return (height(c, kind, None), Cause { ceiling: true, ..NO_CAUSE }); + } + return (height(h, kind, cause.by), cause); + } + let host = host(recs, lw(2)); + let water = b.water(lw(2)); + if rule == 3 && recs.iter().any(|r| r.water == water) { + // A blend face (a junction's region) has no host: every record of its kind present takes part + // by the painter's priorities, and the face relates the junction's arms, so they meet in it + // whichever lies nearest. With no record of its kind it is a host missing: the plain terrain. + let id = label.unwrap_or(u32::MAX); + let arms = arms_of(words, recs, id); + let h = region(b, q, recs, id, arms, items.blend, water, p); + return (height(h, Kind::Paved, host.map(|o| recs[o].line)), Cause { arms, ..NO_CAUSE }); + } + match host { + Some(o) => { + let line = recs[o].line; + (height(paved(recs, o, p), Kind::Paved, Some(line)), Cause { by: Some(line), ..NO_CAUSE }) + } + // A host missing from the records: a fault (`check::Scan::host_missing`). + None => (height(t, Kind::Paved, None), NO_CAUSE), + } +} diff --git a/host/obc-ground-plan/src/faces/heights/tests.rs b/host/obc-ground-plan/src/faces/heights/tests.rs new file mode 100644 index 0000000000..4a80ac8468 --- /dev/null +++ b/host/obc-ground-plan/src/faces/heights/tests.rs @@ -0,0 +1,779 @@ +//! The heights on synthetic cells: each case's ways on a plane of terrain. + +use super::check::{border, edge_steps, scan, terrain_at, Class, Scan}; +use super::{height_at, height_at_sides, Kind, Step}; +use crate::faces::records::{self, find}; +use crate::faces::tests::{at, cell, input_of, line, main_road, mpu, plane, road, track, Line}; +use crate::faces::Rules; +use crate::frame::{CellKey, CELL_UNITS}; +use crate::graph::build; +use crate::sections::Sections; +use crate::CellInput; + +struct Built { + key: CellKey, + words: Vec, + input: CellInput, +} + +fn built(key: CellKey, lines: &[Line], z: &dyn Fn(f64, f64) -> f64, rules: &Rules) -> Built { + let mut input = input_of(key, lines); + input.terrain = plane(key, z); + let graph = build(key, &input, &rules.sections); + let words = records::build(&graph, &input, rules, key, 0, true).near.words; + Built { key, words, input } +} + +impl Built { + /// A point in metres east and south of the centre of `cell()`, frame units from this cell's origin. + fn q(&self, m: [f64; 2]) -> [f64; 2] { + let (g, o) = (at(m), self.key.origin()); + [(g.x - o.x) as f64, (g.y - o.y) as f64] + } + + fn t(&self, q: [f64; 2]) -> f64 { + terrain_at(&self.input.terrain, self.key, q).expect("a known terrain") + } + + fn h(&self, m: [f64; 2]) -> super::Height { + let q = self.q(m); + height_at(&self.words, q, find(&self.words, q), self.t(q)) + } + + fn scan(&self) -> Scan { + scan(&self.words, &self.input.terrain, self.key, 0.5) + } +} + +fn count(s: &Scan, class: Class) -> usize { + s.steps.iter().filter(|st| st.class == class).count() +} + +fn ways(lines: &[Line], z: &dyn Fn(f64, f64) -> f64) -> Built { + built(cell(), lines, z, Rules::embedded()) +} + +#[test] +fn a_road_on_a_hillside_is_exact_in_its_core_and_meets_the_terrain_at_its_band_edge() { + // Terrain rising 0.3 per metre to the south across a road east to west at its height. + let z = |_: f64, y: f64| 500.0 + 0.3 * y; + let c = ways(&[road(&[[-300.0, 0.0], [300.0, 0.0]])], &z); + for x in [-40.0, 0.0, 33.3] { + for y in [-2.4, -1.0, 0.0, 2.4] { + let h = c.h([x, y]); + assert_eq!(h.kind, Kind::Paved); + assert!((h.h - 500.0).abs() < 1e-9, "{x} {y}: {}", h.h); + } + } + let s = c.scan(); + assert_eq!(count(&s, Class::Inside), 0); + assert_eq!(count(&s, Class::Unnamed), 0); + // Across the road: the ground at the slope band's outer edge is the terrain's, and the toe and + // the crest round over metres, not in a kink. + let section: Vec<(f64, super::Height, f64)> = (-1800..=1800) + .map(|k| { + let y = f64::from(k) * 0.01; + let q = c.q([0.0, y]); + (y, c.h([0.0, y]), c.t(q)) + }) + .collect(); + let edges: Vec<&(f64, super::Height, f64)> = section + .windows(2) + .filter(|w| w[0].1.kind == Kind::Slope && w[1].1.kind == Kind::Terrain) + .map(|w| &w[0]) + .collect(); + assert!(!edges.is_empty()); + for (y, h, t) in edges { + assert!((h.h - t).abs() < 0.001, "at {y} m: {} against {t}", h.h); + } + // Between the cone's round foot (0.5 m past the core edge at 2.9 m) and the band fade at the band's + // outer edge: a kink of the toe or the crest would give over 0.1 m. + let d2 = (section.windows(51).filter(|w| (4.0..9.0).contains(&w[25].0.abs()))) + .map(|w| (w[50].1.h - 2.0 * w[25].1.h + w[0].1.h).abs()) + .fold(0.0, f64::max); + assert!(d2 < 0.03, "{d2} m over 0.25 m"); +} + +#[test] +fn a_slope_leaves_its_road_edge_no_faster_than_its_cones() { + // A road at the height of flat terrain: fill, cut and terrain meet at the core edge (2.9 m), where + // a toe round wider than the cones' gap would move the ground off the road by centimetres. + let c = ways(&[road(&[[-300.0, 0.0], [300.0, 0.0]])], &|_, _| 500.0); + let slope = find(&c.words, c.q([0.0, 3.5])); + // The bound is the road's fill cone, cone(2/3, d) = 2/3 d² / (2 round_m) with round_m 0.5. + for d in [0.01, 0.03, 0.1] { + let q = c.q([0.0, 2.9 + d]); + let h = height_at(&c.words, q, slope, c.t(q)); + assert_eq!(h.kind, Kind::Slope); + assert!((h.h - 500.0).abs() <= 0.67 * d * d + 1e-4, "{d} m past the edge: {}", h.h); + } + // No crease out to 2 m, past where the toe width meets the cones' gap (about 0.56 m): across a + // kink the slope change over a sample pair stays the same as the spacing shrinks; on smooth + // ground it shrinks with the spacing. + let edge = c.q([0.0, 2.9]); + let g: Vec = (0..=(2.0 / mpu()) as i32) + .map(|n| { + let q = [edge[0], edge[1] + f64::from(n)]; + height_at(&c.words, q, slope, c.t(q)).h + }) + .collect(); + let bend = |s: usize| { + (s..g.len() - s).map(|n| ((g[n + s] - 2.0 * g[n] + g[n - s]) / (s as f64 * mpu())).abs()).fold(0.0, f64::max) + }; + let (fine, coarse) = (bend(2), bend(8)); + assert!(fine < 0.4 * coarse, "slope change {fine} at 2 units against {coarse} at 8 units"); +} + +#[test] +fn a_fill_that_meets_the_terrain_near_its_band_edge_fades_its_lift_with_no_crease() { + // A road 3 m above terrain falling 0.2 per metre to the south: the fill meets the terrain within + // a few metres of the slope band's outer edge, where the cone lets go and the toe round widens. + let mut way = road(&[[-300.0, 0.0], [300.0, 0.0]]); + way.z = vec![503.0; 2]; + let c = ways(&[way], &|_, y| 500.0 - 0.2 * y); + let edge = c.q([0.0, 2.9]); + let moved: Vec = (0..=(12.0 / mpu()) as i32) + .map(|n| { + let q = [edge[0], edge[1] + f64::from(n)]; + height_at(&c.words, q, find(&c.words, q), c.t(q)).h - c.t(q) + }) + .collect(); + assert!(moved[0] > 2.5 && *moved.last().unwrap() == 0.0, "{} m to {} m", moved[0], moved.last().unwrap()); + // Past the cone's round foot: as in the test above, a crease keeps its slope change as the + // spacing shrinks. + let bend = |s: usize| { + ((1.0 / mpu()) as usize..moved.len() - s) + .map(|n| ((moved[n + s] - 2.0 * moved[n] + moved[n - s]) / (s as f64 * mpu())).abs()) + .fold(0.0, f64::max) + }; + let (fine, coarse) = (bend(2), bend(8)); + assert!(fine < 0.4 * coarse, "slope change {fine} at 2 units against {coarse} at 8 units"); +} + +#[test] +fn a_guest_meets_its_host_at_the_host_core_edge_and_keeps_its_own_height_past_its_ramp() { + let mut guest = road(&[[0.0, 0.0], [0.0, -200.0]]); + guest.z = vec![500.4; 2]; + let c = ways(&[road(&[[-300.0, 0.0], [300.0, 0.0]]), guest], &|_, _| 500.0); + assert!((c.h([-60.0, 0.0]).h - 500.0).abs() < 1e-9); + // The records hold heights in f32. + assert!((c.h([0.0, -60.0]).h - f64::from(500.4f32)).abs() < 1e-9); + // Every face edge along the guest steps by under step_m. + let mut last = find(&c.words, c.q([0.4, -1.0])); + for k in 100..3000 { + let q = c.q([0.4, -f64::from(k) * 0.01]); + let l = find(&c.words, q); + if l != last { + let sides = height_at_sides(&c.words, q, [last, l], c.t(q)); + assert!((sides[0].h - sides[1].h).abs() < 0.001, "at {} m: {sides:?}", f64::from(k) * 0.01); + last = l; + } + } + assert_eq!(count(&c.scan(), Class::Inside), 0); +} + +#[test] +fn a_path_on_a_road_edge_two_metres_up_steps_only_on_face_edges_by_rules_of_its_size() { + // The path's core overlaps the road's; no junction relates them. + let mut path = line("road", &[("highway", "path")], &[[-300.0, 3.6], [300.0, 3.6]]); + path.z = vec![502.0; 2]; + let c = ways(&[road(&[[-300.0, 0.0], [300.0, 0.0]]), path], &|_, _| 500.0); + let s = c.scan(); + assert_eq!(count(&s, Class::Inside), 0); + assert_eq!(count(&s, Class::Unnamed), 0); + let at_road: Vec = (s.steps.iter()) + .filter(|st| matches!(st.class, Class::Named(Step::Held | Step::Unrelated))) + .map(|st| st.dh.abs()) + .filter(|d| *d > 1.9) + .collect(); + assert!(at_road.len() > 500 && at_road.iter().all(|&d| d < 2.01), "{} steps of 2 m", at_road.len()); +} + +#[test] +fn a_bend_of_twelve_metres_is_continuous_and_flat() { + let r = 12.0; + let arc: Vec<[f64; 2]> = (0..=18) + .map(|k| f64::from(k) * std::f64::consts::PI / 18.0) + .map(|a| [r * libm::cos(a), -r * libm::sin(a)]) + .collect(); + let mut points = vec![[r, 200.0]]; + points.extend(arc); + points.push([-r, 200.0]); + let c = ways(&[road(&points)], &|_, _| 500.0); + let s = c.scan(); + assert_eq!(count(&s, Class::Inside), 0); + assert_eq!(count(&s, Class::Unnamed), 0); + let mut d2: Vec = s.ripple.iter().flatten().filter(|v| !v.is_nan()).map(|v| v.abs()).collect(); + d2.sort_by(f64::total_cmp); + assert!(d2.len() > 1000); + assert!(d2[d2.len() * 99 / 100] <= 0.002, "p99 {} m", d2[d2.len() * 99 / 100]); +} + +/// The embedded rules with one text of `plan.json` replaced. +fn rules_with(from: &str, to: &str) -> Rules { + let plan = include_str!("../../../../../data/trailview/plan.json").replacen(from, to, 1); + Rules::parse(Sections::embedded().clone(), &plan).unwrap() +} + +#[test] +fn a_road_across_a_sixty_degree_hillside_walls_both_edges_up_to_the_highest_wall_and_goes_on_as_rock() { + // A tertiary road on a hillside rising 60° to the south: each side needs 18 m to the terrain where + // its cone lets go. Each edge's own fit shapes its side: a wall of the highest wall, whatever that + // is, then a face no steeper than a rock face down to the fill's toe and up to the cut's crest. + let grade = libm::tan(60f64.to_radians()); + for wall in [4.5, 2.0] { + let rules = rules_with(r#""wall_max_m": 4.5"#, &format!(r#""wall_max_m": {wall}"#)); + let c = built(cell(), &[main_road(&[[-300.0, 0.0], [300.0, 0.0]])], &|_, y| 500.0 + grade * y, &rules); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0), "{wall}"); + assert!(s.steep.is_empty(), "{wall}: {:?}", &s.steep[..s.steep.len().min(4)]); + for x in [-100.0, 0.0, 100.0] { + let steps: Vec<(f64, f64, f64)> = + edges_across(&c, x, -20.0, 20.0).into_iter().filter(|e| e.1.abs() > 0.01).collect(); + // Read 5 mm off the edge, where a face at its steepest has climbed 1 cm. + assert!( + steps.len() == 2 && steps.iter().all(|e| (e.1 - wall).abs() < 0.02), + "{wall} at x = {x}: {steps:?}" + ); + } + } +} + +#[test] +fn a_track_across_a_fifty_degree_hillside_has_no_wall_and_steepens_its_slopes_up_to_a_rock_face() { + // The fill needs more than the track's steepest fill gives over its run, which a wall class walls. + let grade = libm::tan(50f64.to_radians()); + let c = ways(&[track(&[[-300.0, 0.0], [300.0, 0.0]])], &|_, y| 500.0 + grade * y); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + assert!(s.steep.is_empty(), "{:?}", &s.steep[..s.steep.len().min(4)]); + for x in [-100.0, 0.0, 100.0] { + let steps: Vec<(f64, f64, f64)> = + edges_across(&c, x, -20.0, 20.0).into_iter().filter(|e| e.1.abs() > 0.01).collect(); + assert!(steps.is_empty(), "at x = {x}: {steps:?}"); + } +} + +#[test] +fn a_rail_beside_a_road_two_metres_up_meets_it_in_a_held_wall_at_its_own_edge() { + let mut rail = line("railway", &[("railway", "rail")], &[[-300.0, 6.0], [300.0, 6.0]]); + rail.z = vec![502.0; 2]; + let c = ways(&[road(&[[-300.0, 0.0], [300.0, 0.0]]), rail], &|_, _| 500.0); + let s = c.scan(); + assert_eq!(count(&s, Class::Unnamed), 0); + // The rail's fill does not count in the road's budget, so the road's cut holds the rail's bank. + let walls: Vec = + s.steps.iter().filter(|st| st.class == Class::Named(Step::Held)).map(|st| st.dh.abs()).collect(); + assert!(walls.len() > 500 && walls.iter().all(|&d| d > 1.0), "{} walls", walls.len()); +} + +/// The face edges that a section at x crosses from y0 to y1 (metres east and south): per edge its y, +/// the rise from the side before it to the side after it, and the side before it, both read there. +fn edges_across(c: &Built, x: f64, y0: f64, y1: f64) -> Vec<(f64, f64, f64)> { + let mut out = Vec::new(); + let mut last = find(&c.words, c.q([x, y0])); + for k in 1..=((y1 - y0) / 0.01) as i32 { + let y = y0 + f64::from(k) * 0.01; + let l = find(&c.words, c.q([x, y])); + if l != last { + let q = c.q([x, y - 0.005]); + let [a, b] = height_at_sides(&c.words, q, [last, l], c.t(q)); + out.push((y - 0.005, b.h - a.h, a.h)); + last = l; + } + } + out +} + +/// A residential road 3 m up north of a road `lower` on flat terrain, parting from it: its centre runs +/// from y = −6 at x = −300 to y = −16 at x = 300. Its bank at 2:3 needs 4.75 m of room. +fn parting(lower: Line) -> Built { + let mut upper = road(&[[-300.0, -6.0], [300.0, -16.0]]); + upper.z = vec![503.0; 2]; + ways(&[lower, upper], &|_, _| 500.0) +} + +#[test] +fn a_wall_class_road_below_another_walls_only_its_own_edge_with_a_top_that_never_jumps_and_ends_in_a_bank() { + // The lower road's centre 0.5 m farther south, as its class is 0.5 m wider: the paved edges are + // 0.2 m apart at x = −300. + let south = 0.5; + let c = parting(main_road(&[[-300.0, south], [300.0, south]])); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + // Per x, from the upper road's centre south to the lower one's: the wall at the lower road's + // edge with its top, and the greatest step nearer the upper road. + let xs: Vec = (0..=1200).map(|k| -200.0 + 0.25 * f64::from(k)).collect(); + let at: Vec<(f64, f64, f64)> = (xs.iter()) + .map(|&x| { + let y = -6.0 - 10.0 * (x + 300.0) / 600.0; + let (mut wall, mut top, mut upper) = (0.0, 500.0, 0.0f64); + for (e, rise, before) in edges_across(&c, x, y, south - 1.0) { + if e > (y + south) / 2.0 && -rise > wall { + (wall, top) = (-rise, before); + } else if e <= (y + south) / 2.0 { + upper = upper.max(rise.abs()); + } + } + (wall, top, upper) + }) + .collect(); + assert!(at[0].0 > 1.5, "the wall at x = −200: {} m", at[0].0); + let upper = at.iter().map(|a| a.2).fold(0.0, f64::max); + assert!(upper < 0.01, "a step of {upper} m at the upper road"); + // The top is the bank budget: it changes by at most 2:3 of the metres along the edge, so the wall + // runs down to 0 with no end face and the bank goes on past it. + let steepest = at.windows(2).map(|w| (w[1].1 - w[0].1).abs() / 0.25).fold(0.0, f64::max); + assert!(steepest <= 0.67 + 0.01, "the top rises {steepest} per metre"); + let end = at.iter().position(|a| a.0 < 0.001).expect("the wall ends"); + assert!(xs[end] > -100.0 && xs[end] < 0.0, "the wall ends at x = {}", xs[end]); + assert!(at[end..].iter().all(|a| a.0 < 0.001), "a wall past the taper"); + assert!(at[end - 1].0 < 0.05, "the last wall step is {} m", at[end - 1].0); +} + +#[test] +fn a_wall_class_road_far_below_another_walls_its_edge_up_to_the_highest_wall_and_climbs_on_at_its_steepest() { + // A 1:1 hillside rising north, a tertiary road on it and a residential road 10 m farther up, its + // paved edge 3.7 m north of the tertiary road's: its bank asks for a wall of over 6 m. + let mut upper = road(&[[-300.0, -9.5], [300.0, -9.5]]); + upper.z = vec![509.5; 2]; + let mut lower = main_road(&[[-300.0, 0.5], [300.0, 0.5]]); + lower.z = vec![499.5; 2]; + let c = ways(&[lower, upper], &|_, y| 500.0 - y); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + let most = Rules::embedded().plan.heights.wall_max_m; + for x in [-100.0, 0.0, 100.0] { + let steps: Vec<(f64, f64, f64)> = + edges_across(&c, x, -9.5, 0.0).into_iter().filter(|e| e.1.abs() > 0.01).collect(); + // One step, the wall at the lower road's edge, up to its top and no higher. + assert!(steps.len() == 1 && (-steps[0].1 - most).abs() < 0.01, "at x = {x}: {steps:?}"); + // Past its top the ground climbs at the steepest cut (2:1) and meets the upper road's bank. + let h = |y: f64| c.h([x, y]).h; + let rise = (1..37).map(|k| (h(-3.0 - 0.1 * f64::from(k)) - h(-2.9 - 0.1 * f64::from(k))) / 0.1); + assert!(rise.fold(0.0, f64::max) <= 2.0 + 0.01, "steeper than the steepest cut at x = {x}"); + } +} + +#[test] +fn a_way_of_a_class_without_walls_below_a_road_gets_a_bank_up_to_its_steepest_cut() { + // A track is 0.5 m wider than a residential road: its centre 0.5 m farther south. + let c = parting(track(&[[-300.0, 0.5], [300.0, 0.5]])); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + // No step at the lower road's edge: its cut rises at most at its steepest cut (cut_max). Where that + // leaves the upper road's bank no room, the step stands at the upper road's edge, held. + for x in [-200.0, -100.0, 0.0, 100.0, 200.0] { + let y = -6.0 - 10.0 * (x + 300.0) / 600.0; + for (e, rise, _) in edges_across(&c, x, y, -1.0) { + assert!(e <= (y + 0.5) / 2.0 || rise.abs() < 0.01, "a step of {rise} m at y = {e} by the track at x = {x}"); + } + } +} + +#[test] +fn a_hairpin_of_a_wall_class_a_step_high_gets_one_wall_at_its_lower_leg_from_the_upper_legs_bank() { + let c = hairpin(TERTIARY, "ramp", 2.0); + for x in [-150.0, -100.0, -50.0] { + let walls: Vec<(f64, f64, f64)> = + edges_across(&c, x, -2.0, 2.0).into_iter().filter(|e| e.1.abs() > 0.01).collect(); + // Up from the lower leg (north) to the bank of the upper one, which runs into its edge. + assert!(walls.len() == 1 && walls[0].0 < 0.0 && (0.5..1.5).contains(&walls[0].1), "at x = {x}: {walls:?}"); + } +} + +/// A way of a class and the metres off its centre where a hairpin's legs leave 1.2 m between their +/// paved edges (the half-width and the shoulder, and half the gap). +type Hairpin = (fn(&[[f64; 2]]) -> Line, f64); +const TRACK: Hairpin = (track, 4.0); +const TERTIARY: Hairpin = (main_road, 4.0); + +/// A hairpin of one way whose legs run 1.2 m apart at their paved edges, `dz` metres apart in height. +fn hairpin((class, half): Hairpin, legs: &str, dz: f64) -> Built { + let rules = rules_with(r#""legs": "ramp""#, &format!(r#""legs": "{legs}""#)); + let mut way = class(&[[-200.0, -half], [100.0, -half], [100.0 + half, 0.0], [100.0, half], [-200.0, half]]); + way.z = vec![500.0, 500.0, 500.0 + dz / 2.0, 500.0 + dz, 500.0 + dz]; + built(cell(), &[way], &|_, _| 500.0 + dz / 2.0, &rules) +} + +#[test] +fn a_hairpin_a_step_high_meets_in_named_steps_and_a_lower_one_in_its_slope_by_any_legs_rule() { + // 2 m, a wall class: two legs, a line each, whatever the rule, and the walls stand on face edges by + // a rule. + for rule in ["ramp", "wall"] { + let s = hairpin(TERTIARY, rule, 2.0).scan(); + let named = s.steps.iter().filter(|st| matches!(st.class, Class::Named(_))).count(); + assert!(named > 200, "{rule}: {named} named steps"); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0), "{rule}"); + } + // 2 m of a class without walls, and 0.4 m: one line, whose two parts meet in the slope between them + // with no step (the lower part's steepest cut climbs over the gap). The legs rule shapes the paved + // field only: the slope reads the paved outline, and a wall needs the budget. + for (dz, rule) in [(2.0, "ramp"), (0.4, "ramp"), (0.4, "wall")] { + let c = hairpin(TRACK, rule, dz); + let [x0, y0] = c.q([-150.0, -1.0]); + let [x1, y1] = c.q([0.0, 1.0]); + let between = |a: [f64; 2]| (x0..x1).contains(&a[0]) && (y0..y1).contains(&a[1]); + assert_eq!(c.scan().steps.iter().filter(|st| between(st.a)).count(), 0, "{dz} {rule}"); + let edges = edge_steps(&c.words, &c.input.terrain, c.key, 0.25); + assert_eq!(edges.iter().filter(|st| between(st.a)).count(), 0, "{dz} {rule}: {edges:?}"); + } +} + +#[test] +fn a_point_on_a_cell_line_gets_the_same_bits_in_both_cells() { + // A road across the east cell line, and one in the east cell whose segments the east bins list + // and the west bins do not. + let x = CELL_UNITS as f64 / 2.0 * mpu(); + let lines = [road(&[[x - 300.0, 0.0], [x + 300.0, 2.0]]), road(&[[x + 15.0, -250.0], [x + 15.0, 250.0]])]; + let z = |x: f64, y: f64| 500.0 + 0.1 * x + 0.05 * y; + let east = CellKey { x: cell().x + 1, y: cell().y }; + let (a, b) = (ways(&lines, &z), built(east, &lines, &z, Rules::embedded())); + let (pa, pb) = (border(&a.words, &a.input.terrain, a.key, 64), border(&b.words, &b.input.terrain, b.key, 64)); + let pb: std::collections::BTreeMap<_, _> = pb.into_iter().collect(); + let shared: Vec<_> = pa.iter().filter_map(|(k, v)| pb.get(k).map(|w| (v, w))).collect(); + assert!(shared.len() > 3000, "{} shared points", shared.len()); + assert!(shared.iter().all(|(v, w)| v.h == w.h && v.t == w.t)); +} + +#[test] +fn a_junction_region_meets_the_faces_beyond_its_edges_with_no_unnamed_step() { + // A T junction beside a rail 6 m off and 0.8 m lower: the rail partly agrees with both roads, and + // the region's own painter, which relates the arms, differs from the arms' faces at its edges. + let mut rail = line("railway", &[("railway", "rail")], &[[-300.0, 6.0], [300.0, 6.0]]); + rail.z = vec![499.2; 2]; + let lines = [road(&[[-300.0, 0.0], [300.0, 0.0]]), road(&[[0.0, 0.0], [0.0, -200.0]]), rail]; + // With no fade, the region's own painter steps on its edges. + let plan = include_str!("../../../../../data/trailview/plan.json"); + let at = plan.find(r#""region_fade_m": "#).unwrap() + r#""region_fade_m": "#.len(); + let end = at + plan[at..].find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap(); + let none = Rules::parse(Sections::embedded().clone(), &format!("{}1e-9{}", &plan[..at], &plan[end..])).unwrap(); + assert!(count(&built(cell(), &lines, &|_, _| 500.0, &none).scan(), Class::Unnamed) > 0); + let s = ways(&lines, &|_, _| 500.0).scan(); + assert_eq!(count(&s, Class::Unnamed), 0); + assert_eq!(count(&s, Class::Inside), 0); +} + +#[test] +fn a_level_t_junction_gets_no_berm_in_its_corners() { + // Roads at the height of flat terrain: the fills of the two arms tie along the corner, and the + // envelope of the fills must not rise above them. + let c = ways(&[road(&[[-300.0, 0.0], [300.0, 0.0]]), road(&[[0.0, 0.0], [0.0, -200.0]])], &|_, _| 500.0); + let mut highest = 0.0f64; + for i in 0..200 { + for j in 0..200 { + let h = c.h([0.5 + f64::from(i) * 0.1, -0.5 - f64::from(j) * 0.1]); + if h.kind == Kind::Slope { + highest = highest.max(h.h - 500.0); + } + } + } + assert!(highest < 0.01, "the corner rises {highest} m above the terrain"); +} + +#[test] +fn an_upper_road_beside_a_junction_above_a_lower_road_has_no_step_at_its_own_edge() { + // A T junction 3 m up (a through road and a side road) and a road at the terrain 8 m south. The + // lower road's cut rises to the budget, whose greatest fill is the through road's: at that road's + // own south edge the ground starts at the road, whatever the side road's fill adds. + let mut through = road(&[[-300.0, 0.0], [300.0, 0.0]]); + through.z = vec![503.0; 2]; + let mut side = road(&[[0.0, 0.0], [0.0, -200.0]]); + side.z = vec![503.0; 2]; + let c = ways(&[through, side, road(&[[-300.0, 8.0], [300.0, 8.0]])], &|_, _| 500.0); + let q0 = c.q([0.0, 0.0]); + let at = |q: [f64; 2]| [(q[0] - q0[0]) * mpu(), (q[1] - q0[1]) * mpu()]; + let s = c.scan(); + let steps: Vec<_> = (s.steps.iter()) + .filter(|st| { + let m = at(st.a); + m[0].abs() < 8.0 && (1.0..4.5).contains(&m[1]) && st.dh.abs() > 0.01 + }) + .map(|st| (at(st.a), st.dh)) + .collect(); + assert!(steps.is_empty(), "steps at the upper road's edge: {steps:?}"); +} + +#[test] +fn a_rail_bed_above_a_road_gives_the_road_no_wall() { + // A road at the terrain and a rail bed 1.2 m up beside it with no room for a 2:3 bank between: the + // budget comes from road surfaces only, so the step stands at the rail bed, not at the road's edge. + let mut rail = line("railway", &[("railway", "rail")], &[[-300.0, 6.0], [300.0, 6.0]]); + rail.z = vec![501.2; 2]; + let c = ways(&[road(&[[-300.0, 0.0], [300.0, 0.0]]), rail], &|_, _| 500.0); + let q0 = c.q([0.0, 0.0]); + let at = |q: [f64; 2]| [(q[0] - q0[0]) * mpu(), (q[1] - q0[1]) * mpu()]; + let s = c.scan(); + let road_edge: Vec<_> = (s.steps.iter()) + .filter(|st| { + let m = at(st.a); + m[0].abs() < 100.0 && (2.0..3.5).contains(&m[1]) && st.dh.abs() > 0.05 + }) + .map(|st| (at(st.a), st.dh)) + .collect(); + assert!(road_edge.is_empty(), "steps at the road's edge: {:?}", &road_edge[..road_edge.len().min(4)]); +} + +/// A stream (W = `level`) east to west through the centre of `cell()`. +fn stream(points: &[[f64; 2]], level: f64) -> Line { + let mut s = line("stream", &[("waterway", "stream")], points); + s.z = vec![level; points.len()]; + s +} + +/// The surface code of the label at q (none for terrain). +fn surface_at(c: &Built, m: [f64; 2]) -> Option { + find(&c.words, c.q(m)).map(|id| records::label(&c.words, id)[0] & 0xff) +} + +#[test] +fn a_stream_across_a_slope_lies_level_with_a_bank_to_its_rise_and_a_dyke_where_the_terrain_is_lower() { + // Terrain rising 0.3 per metre to the south, a stream east to west at the terrain of its line: the + // north bank's terrain lies under the rise (W + 0.4 m), the south bank's rises over it. + let c = ways(&[stream(&[[-300.0, 0.0], [300.0, 0.0]], 500.0)], &|_, y| 500.0 + 0.3 * y); + let water = crate::faces::Surface::Water as u32; + for x in [-40.0, 0.0, 33.3] { + for y in [-0.45, -0.2, 0.0, 0.3, 0.45] { + let h = c.h([x, y]); + assert_eq!((surface_at(&c, [x, y]), h.kind), (Some(water), Kind::Paved), "{x} {y}"); + assert!((h.h - 500.0).abs() < 1e-9, "{x} {y}: {}", h.h); + } + } + // The bank top on level ground: the cut cone from the waterline (0.5 m) meets the rise there. + let rules = &Rules::embedded().plan.heights; + let top = 0.5 + super::cone_reach(1.2, 0.4, rules); + assert!((c.h([0.0, top]).h - 500.4).abs() < 0.002, "south bank top {}", c.h([0.0, top]).h); + assert_eq!(surface_at(&c, [0.0, top - 0.05]), Some(crate::faces::Surface::Bank as u32)); + // North: up to the rise, level to the crest (0.6 m past the waterline), then a fill down to the terrain. + let north = |y: f64| c.h([0.0, -y]).h; + assert!((north(top) - 500.4).abs() < 0.002 && (north(1.1) - 500.4).abs() < 0.002, "{} {}", north(top), north(1.1)); + let fall = (north(1.6) - north(2.0)) / 0.4; + assert!((0.5..=2.0).contains(&fall), "the dyke falls {fall} per metre"); + assert!((north(4.0) - c.t(c.q([0.0, -4.0]))).abs() < 0.002, "{}", north(4.0)); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + assert!(edge_steps(&c.words, &c.input.terrain, c.key, 0.25).is_empty()); +} + +#[test] +fn a_road_keeps_its_paved_heights_bit_for_bit_beside_a_stream_and_the_stream_its_level() { + // A T junction 2 m over flat terrain and a stream 0.4 m under it, 5 m south of the through road and + // past the side road's end: the painter reads only its own kind. + let raise = |mut l: Line| { + l.z = vec![502.0; l.z.len()]; + l + }; + let roads = [raise(road(&[[-300.0, 0.0], [300.0, 0.0]])), raise(road(&[[0.0, 0.0], [0.0, -200.0]]))]; + let dry = ways(&roads, &|_, _| 500.0); + let mut with = roads.to_vec(); + with.push(stream(&[[-300.0, 5.0], [300.0, 5.0]], 499.6)); + let wet = ways(&with, &|_, _| 500.0); + let mut paved = 0; + for i in -60..=60 { + for j in -40..=12 { + let m = [f64::from(i) * 0.5, f64::from(j) * 0.25]; + let (a, b) = (dry.h(m), wet.h(m)); + if a.kind == Kind::Paved && surface_at(&dry, m) != Some(crate::faces::Surface::Shoulder as u32) { + paved += 1; + assert_eq!((a.h.to_bits(), a.kind), (b.h.to_bits(), b.kind), "at {m:?}"); + } + } + } + assert!(paved > 2000, "{paved} paved points"); + for x in [-20.0, 0.0, 15.0] { + let h = wet.h([x, 5.0]); + assert!(h.kind == Kind::Paved && (h.h - f64::from(499.6f32)).abs() < 1e-9, "{x}: {:?}", h); + } +} + +#[test] +fn a_crossings_approach_has_no_step_at_the_road_edge_and_a_bank_below_a_road_fill_steepens_with_no_step() { + // A road crosses a stream at a shared vertex (the road 0.2 m under W at the vertex): within the + // stream's reach past its bank, the road's edge has no step, as the stream's dyke counts for no road's + // budget. + let mut r = road(&[[-200.0, 0.0], [0.0, 0.0], [200.0, 0.0]]); + r.z = vec![500.0, 499.8, 500.0]; + let c = ways(&[r, stream(&[[0.0, -200.0], [0.0, 0.0], [0.0, 200.0]], 500.0)], &|_, _| 500.4); + let q0 = c.q([0.0, 0.0]); + let at = |q: [f64; 2]| [(q[0] - q0[0]) * mpu(), (q[1] - q0[1]) * mpu()]; + let approach = |q: [f64; 2]| { + let m = at(q); + (1.2..5.0).contains(&m[0].abs()) && m[1].abs() < 8.0 + }; + let steps: Vec<_> = c.scan().steps.into_iter().filter(|st| approach(st.a) && st.dh.abs() > 0.01).collect(); + assert!(steps.is_empty(), "{:?}", steps.iter().map(|st| (at(st.a), st.dh, st.class)).collect::>()); + assert!(edge_steps(&c.words, &c.input.terrain, c.key, 0.25).iter().all(|st| !approach(st.a))); + // A stream 6 m north of a road 1.5 m over flat terrain: the road's fill counts for the stream's budget, + // so the stream's south bank climbs toward it no steeper than its steepest slope, with no step. + let mut up = road(&[[-300.0, 0.0], [300.0, 0.0]]); + up.z = vec![501.5; 2]; + let c = ways(&[up, stream(&[[-300.0, -6.0], [300.0, -6.0]], 499.6)], &|_, _| 500.0); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + let north = |st: &&super::check::Step| at(st.a)[1] < -3.0 && st.dh.abs() > 0.01; + assert_eq!(s.steps.iter().filter(north).count(), 0, "steps at the stream"); + let bank: Vec = (0..40).map(|k| c.h([0.0, -5.5 + 0.05 * f64::from(k)]).h).collect(); + let steepest = bank.windows(2).map(|w| (w[1] - w[0]).abs() / 0.05).fold(0.0, f64::max); + assert!(steepest <= 2.0 + 0.05, "{steepest} per metre"); +} + +#[test] +fn a_confluence_blends_in_one_region_and_two_streams_that_cross_apart_meet_in_a_named_step() { + // Two streams join at a shared vertex at one level; elsewhere a stream crosses another with no + // shared vertex, 0.5 m lower. + let join = [stream(&[[-200.0, 0.0], [0.0, 0.0], [200.0, 0.0]], 500.0), stream(&[[0.0, 0.0], [0.0, -200.0]], 500.0)]; + let c = ways(&join, &|_, _| 500.4); + let region = find(&c.words, c.q([0.0, 0.0])).map(|id| records::label(&c.words, id)[0]); + assert_eq!(region.map(|w| (w & 0xff, w >> 24)), Some((crate::faces::Surface::Water as u32, 3))); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + let apart = [stream(&[[-200.0, 0.0], [200.0, 0.0]], 500.0), stream(&[[0.0, -200.0], [0.0, 200.0]], 499.5)]; + let c = ways(&apart, &|_, _| 500.4); + let s = c.scan(); + assert_eq!((count(&s, Class::Inside), count(&s, Class::Unnamed)), (0, 0)); + assert!(s.steps.iter().any(|st| st.class == Class::Named(Step::Unrelated) && (st.dh.abs() - 0.5).abs() < 0.01)); +} + +#[test] +fn an_edge_cone_with_a_crest_is_level_within_it_and_falls_at_its_slope_past_it() { + let cone = + |along: f64, out: f64, top: [f64; 2]| super::edge_cone(along, out, 4.0, top, 0.5, 1.0, [f64::NAN; 2], 2.5, 0.6); + // Across a level edge: the top within the crest, then the slope from the crest's line. + assert_eq!(cone(2.0, 0.4, [500.4; 2]), 500.4); + assert!((cone(2.0, 1.6, [500.4; 2]) - 499.9).abs() < 1e-12); + // Across a rising edge: the top at q's foot. Past a free end: the end's round cone grown by the crest. + assert!((cone(2.0, 0.3, [500.0, 500.4]) - 500.2).abs() < 1e-12); + assert!((cone(4.3, 0.4, [500.0, 500.4]) - 500.4).abs() < 1e-12); + assert!((cone(4.6, 0.8, [500.0, 500.4]) - 500.2).abs() < 1e-12); +} + +/// A rim whose cut points are rounded off its line by half a unit (0.8 mm) turns a little at every cut. The +/// cones of its ends cover the thin fans of those turns, so the ground beside it is the straight rim's: no +/// groove in a fill, no ridge in a cut. +#[test] +fn a_rim_bent_by_its_cuts_gives_the_ground_of_the_straight_rim() { + let s = 0.667; + // Metres; the slope lies on the side of −y (out of a to b on the right). + let pts: Vec<[f64; 2]> = (0..8).map(|k| [0.158 * f64::from(k), if k % 2 == 1 { 0.0008 } else { 0.0 }]).collect(); + let dir = |k: usize| super::unit(super::sub(pts[k + 1], pts[k])); + let turn = |a: [f64; 2], b: [f64; 2]| libm::atan2(super::cross(a, b), super::dot(a, b)); + let edges = pts.len() - 1; + for sign in [1.0, -1.0] { + for off in [1.0, 2.0, 5.0, 10.0] { + for i in 0..=400 { + let q = [0.2 + 0.002 * f64::from(i), -off]; + let ground = (0..edges) + .map(|k| { + let (u, v) = (dir(k), super::sub(q, pts[k])); + let len = super::norm(super::sub(pts[k + 1], pts[k])); + let t = [ + if k > 0 { turn(dir(k - 1), u) } else { f64::NAN }, + if k + 1 < edges { turn(u, dir(k + 1)) } else { f64::NAN }, + ]; + let out = -super::cross(u, v); + super::edge_cone(super::dot(v, u), out, len, [0.0; 2], s, sign, t, 2.5, 0.0) + }) + .fold(-sign * f64::INFINITY, |m, h| if sign > 0.0 { m.max(h) } else { m.min(h) }); + assert!( + (ground + sign * s * off).abs() < 1e-3, + "sign {sign} at {q:?}: {ground} for {}", + -sign * s * off + ); + } + } + } +} + +#[test] +fn a_culvert_hides_the_water_under_a_road_and_its_fill_and_leaves_a_low_mouth_where_the_water_ends() { + // A residential road (edge 2.9 m from its curve) 2.5 m over a stream 1 m under flat terrain, at 90° and 45°: + // the water ends past the verge, where the fill stands about the mouth's height over it, and the ground + // there stands at most the bank's steepest cut (2 m/m) at the half-width (0.5 m) over the water. + for deg in [90.0f64, 45.0] { + let (s, c) = (libm::sin(deg.to_radians()), libm::cos(deg.to_radians())); + let mut way = line("road", &[("highway", "residential")], &[[-200.0 * s, -200.0 * c], [200.0 * s, 200.0 * c]]); + way.z = vec![501.5; 2]; + let c = ways(&[stream(&[[0.0, -200.0], [0.0, 200.0]], 499.0), way], &|_, _| 500.0); + let water = |y: f64| surface_at(&c, [0.0, y]) == Some(crate::faces::Surface::Water as u32); + let end = (0..400).map(|k| f64::from(k) * 0.025).find(|&y| water(y)).unwrap() * s; + assert!((3.5..8.0).contains(&end), "{deg}°: the water ends {end} m from the road's curve"); + for y in [-1.0, 1.0] { + assert!(!water(y * (end / s - 0.1)) && water(y * (end / s + 0.1)), "{deg}°: the water ends at {y}"); + let mouth = c.h([0.0, y * (end / s - 0.05)]).h - 499.0; + assert!((0.5..1.3).contains(&mouth), "{deg}°: the ground {mouth} m over the water at its end"); + } + assert_eq!(count(&c.scan(), Class::Inside), 0, "{deg}°"); + } +} + +#[test] +fn a_deck_end_turned_up_to_the_flat_turn_lists_its_ceiling_in_every_bin_where_it_holds_the_ground() { + // A tertiary deck ends at a joint with a ground road that meets it at a turn up to `FLAT_TURN_DEG`, its + // stroke flat on the road's end line; the deck lies at 0, 22.5 and 45 degrees to the cell's axes. + let release = Rules::embedded().plan.heights.ceiling_release_m; + let dir = |deg: f64, m: f64| [m * libm::cos(deg.to_radians()), m * libm::sin(deg.to_radians())]; + // The most metres past the stroke, the release and HEIGHT_PAD_M behind the end that a held point lies. + let mut beyond = f64::NEG_INFINITY; + for axis in [0.0, 22.5, 45.0] { + for turn in [0.0, 20.0, 35.0, 44.0] { + let deck = line( + "road", + &[("highway", "tertiary"), ("bridge", "yes"), ("deck", "1")], + &[[0.0; 2], dir(axis, 60.0)], + ); + let c = ways(&[main_road(&[dir(axis + 180.0 + turn, 60.0), [0.0; 2]]), deck], &|_, _| 500.0); + let (b, p) = (super::Block::at(&c.words, c.q([0.0; 2])), super::HeightRules::of(&c.words)); + let ceilings: Vec = (0..c.words[3] as usize) + .map(|l| (l, b.line(l))) + .filter(|(_, ln)| ln.ceiling) + .flat_map(|(l, ln)| (0..ln.count - 1).map(move |i| l as u32 | (i as u32) << 16)) + .collect(); + assert!(!ceilings.is_empty(), "axis {axis}, turn {turn}: no ceiling line"); + let ln = b.line((ceilings[0] & 0xffff) as usize); + let reach = b.sample(&ln, 0).h + release + records::HEIGHT_PAD_M; + let u = dir(axis, 1.0); + for k in 0..180 * 180 { + let m = [-45.0 + 0.5 * f64::from(k % 180), -45.0 + 0.5 * f64::from(k / 180)]; + let q = c.q(m); + let b = super::Block::at(&c.words, q); + let Some(items) = super::bin_items(&b, q) else { continue }; + for &item in &ceilings { + let Some((out, ..)) = super::decks(&b, q, &[item], &p).next() else { continue }; + if out < release { + assert!( + items.segs.contains(&item), + "axis {axis}, turn {turn}: {m:?} held by {item:#x}, not listed" + ); + if m[0] * u[0] + m[1] * u[1] < 0.0 { + beyond = beyond.max(libm::hypot(m[0], m[1]) - reach); + } + } + } + } + } + } + // A turned flat end holds the ground farther behind the end than a segment's own reach. + assert!(beyond > 2.0, "the farthest held point lies {beyond} m past a segment's reach"); +} + +#[test] +fn two_decks_that_meet_at_a_bend_hold_the_ground_on_the_outside_of_their_joint() { + // Two deck ways meet at a joint with a bend; both strokes end on its mitre, so the joint's round lies under a + // deck: no notch on the outside of the bend. + let dir = |deg: f64, m: f64| [m * libm::cos(deg.to_radians()), m * libm::sin(deg.to_radians())]; + let deck = |depth, points: &[[f64; 2]]| { + line("road", &[("highway", "tertiary"), ("bridge", "yes"), ("deck", depth)], points) + }; + for bend in [10.0, 20.0, 45.0, 80.0] { + let c = ways(&[deck("1", &[[-60.0, 0.0], [0.0; 2]]), deck("1.5", &[[0.0; 2], dir(bend, 60.0)])], &|_, _| 500.0); + let notches = super::check::under_decks(&c.words, &c.input.terrain, c.key, 0.5)[3]; + assert_eq!(notches, 0, "bend {bend}: points at the joint under no deck"); + // The outward bisector of the two arms, out of the bend. + let w = [1.0 - libm::cos(bend.to_radians()), -libm::sin(bend.to_radians())]; + let n = libm::hypot(w[0], w[1]); + for r in [1.0, 2.0, 3.0] { + let q = c.q([w[0] / n * r, w[1] / n * r]); + assert!(super::under_deck(&c.words, q).is_some(), "bend {bend}: {r} m out of the joint under no deck"); + } + } +} diff --git a/host/obc-ground-plan/src/faces/legs.rs b/host/obc-ground-plan/src/faces/legs.rs new file mode 100644 index 0000000000..abd2b8d3c7 --- /dev/null +++ b/host/obc-ground-plan/src/faces/legs.rs @@ -0,0 +1,625 @@ +//! The legs of a way that passes beside itself. Two samples of a line are two parts of it where their +//! slope bands meet while they lie beside each other. Two parts conflict where their heights differ by +//! more than the step up to which heights blend two lines. Conflicts whose spans share samples between +//! their parts form one cluster, and the middle sample of that common span cuts the line, so no leg +//! holds both parts of a conflict. Consecutive legs share the cut sample. Each leg is a line of its own +//! in the records, with the frame of a line that ends at its cut, so the bank budget of the heights +//! sees each part's cones. Every candidate that gives the way's label, and the way's own shoulders, +//! split between its legs: the medial lines between any two legs cut it, and each piece goes to its +//! nearest leg, a tie (the outer side of a cut, where the cut sample is nearest both) to the side of +//! the cut's mitre line. So the nearest leg owns each point, and the step between two legs stands on +//! the medial line, blended where their heights agree. + +use super::geom::P; +use std::collections::BTreeMap; + +/// The cuts of a line, as ascending indices of its points `p`: `core` and `band` are the half-widths of +/// the core and of the slope band at each point (units), `z` the height (metres), `ok` the step up to +/// which two parts agree. Two parts conflict where their slope bands meet, they lie beside each other +/// (the line between them leaves both cores, and each lies more than 60° off the other's direction) +/// and their heights differ by more than `ok`. Beside: a point between them can have its feet on both, +/// as its vectors to its feet are normal to the line there. One record holding both would change its +/// cones from one part to the other at the medial line, so the bank budget needs a record per part. +pub fn cuts(p: &[P], core: &[f64], band: &[f64], z: &[f64], ok: f64) -> Vec { + spans(p, core, band, z, ok).iter().map(|&(a, b)| (a + b) / 2).collect() +} + +/// The common span (a, b) of each cut's cluster (`cuts`): no pair of the cluster lies inside it, so a +/// leg's record may run on past its cut to the sample before the span's far end. +pub fn spans(p: &[P], core: &[f64], band: &[f64], z: &[f64], ok: f64) -> Vec<(usize, usize)> { + let n = p.len(); + let widest = band.iter().fold(0.0, |m: f64, &c| m.max(c)); + // The largest distance between the centres of two parts whose slope bands meet. + let span = libm::ceil(2.0 * widest) as i64; + let dir = |i: usize| { + let (a, b) = (p[i.saturating_sub(1)], p[(i + 1).min(n - 1)]); + unit([f64::from(b[0] - a[0]), f64::from(b[1] - a[1])]) + }; + let beside = |i: usize, j: usize| { + let v = unit([f64::from(p[j][0] - p[i][0]), f64::from(p[j][1] - p[i][1])]); + let off = |t: [f64; 2]| (t[0] * v[0] + t[1] * v[1]).abs() < 0.5; + off(dir(i)) && off(dir(j)) + }; + let mut by_x: Vec = (0..n).collect(); + by_x.sort_by_key(|&i| (p[i][0], i)); + let mut pairs: Vec<(usize, usize)> = Vec::new(); + for i in 0..n { + let x = i64::from(p[i][0]); + let lo = by_x.partition_point(|&k| i64::from(p[k][0]) < x - span); + let hi = by_x.partition_point(|&k| i64::from(p[k][0]) <= x + span); + for &j in &by_x[lo..hi] { + if j < i + 2 || (z[i] - z[j]).abs() <= ok || dist(p[i], p[j]) > band[i] + band[j] { + continue; + } + if beside(i, j) && leaves(p, core, i, j) { + pairs.push((i, j)); + } + } + } + // In the order of their first part, the pairs whose spans keep a sample strictly inside all of + // them form a cluster; its cut is the middle sample of that common span. A later cluster starts + // where that span would close, past the earlier cut. + pairs.sort_unstable(); + let mut out = Vec::new(); + let mut span: Option<(usize, usize)> = None; + for (i, j) in pairs { + span = match span { + Some((a, b)) if i.max(a) + 1 < j.min(b) => Some((i.max(a), j.min(b))), + Some((a, b)) => { + out.push((a, b)); + Some((i, j)) + } + None => Some((i, j)), + }; + } + out.extend(span); + out +} + +fn dist(a: P, b: P) -> f64 { + libm::hypot(f64::from(b[0] - a[0]), f64::from(b[1] - a[1])) +} + +/// Whether the line from point i to point j leaves the discs of the core about both: a point of it lies +/// outside both. Exact per segment: the parts of a segment inside the two discs do not cover it. +fn leaves(p: &[P], core: &[f64], i: usize, j: usize) -> bool { + // The parameters of segment a b (relative to the disc's centre) inside a disc of radius r. + let inside = |a: [f64; 2], b: [f64; 2], r: f64| -> Option<(f64, f64)> { + let d = [b[0] - a[0], b[1] - a[1]]; + let qa = d[0] * d[0] + d[1] * d[1]; + let qb = d[0] * a[0] + d[1] * a[1]; + let qc = a[0] * a[0] + a[1] * a[1] - r * r; + if qa == 0.0 { + return (qc <= 0.0).then_some((0.0, 1.0)); + } + let disc = qb * qb - qa * qc; + if disc < 0.0 { + return None; + } + let s = disc.sqrt(); + let (lo, hi) = (((-qb - s) / qa).max(0.0), ((-qb + s) / qa).min(1.0)); + (lo <= hi).then_some((lo, hi)) + }; + let rel = |k: usize, c: usize| [f64::from(p[k][0] - p[c][0]), f64::from(p[k][1] - p[c][1])]; + (i..j).any(|k| { + let a = inside(rel(k, i), rel(k + 1, i), core[i]); + let b = inside(rel(k, j), rel(k + 1, j), core[j]); + match (a, b) { + (None, None) => true, + (Some((l, h)), None) | (None, Some((l, h))) => l > 0.0 || h < 1.0, + (Some(a), Some(b)) => { + let (first, second) = if a.0 <= b.0 { (a, b) } else { (b, a) }; + first.0 > 0.0 || second.0 > first.1 || first.1.max(second.1) < 1.0 + } + } + }) +} + +/// The leg of a line with `cuts` that an arm at point `at` leaves along: forward (`dir` > 0) the leg of +/// the segment from `at`, else the leg of the segment to it. A point that is not a cut lies on one leg. +pub fn leg(cuts: &[usize], at: usize, dir: i8) -> u8 { + let n = cuts.iter().filter(|&&c| if dir > 0 { c <= at } else { c < at }).count(); + crate::probe::field(crate::probe::Field::Leg, n); + n as u8 +} + +/// The first and last point of leg `leg` of a line of `n` points. +pub fn range(cuts: &[usize], n: usize, leg: u8) -> (usize, usize) { + let k = usize::from(leg); + (if k == 0 { 0 } else { cuts[k - 1] }, cuts.get(k).copied().unwrap_or(n - 1)) +} + +/// The first and last point of each leg's record of a line of `n` points with the cuts' `spans`: a +/// leg runs on past its cuts to the samples next to its spans' ends, so no leg ends at a cut and +/// the cones near a cut follow the line. +pub fn record_ranges(spans: &[(usize, usize)], cuts: &[usize], n: usize) -> Vec<(usize, usize)> { + let mut out = ranges(cuts, n); + for (k, &(a, b)) in spans.iter().enumerate() { + out[k].1 = (b - 1).max(cuts[k]); + out[k + 1].0 = (a + 1).min(cuts[k]); + } + out +} + +/// The first and last point of each leg of a line of `n` points. +pub fn ranges(cuts: &[usize], n: usize) -> Vec<(usize, usize)> { + let mut out = Vec::with_capacity(cuts.len() + 1); + let mut lo = 0; + for &c in cuts { + out.push((lo, c)); + lo = c; + } + out.push((lo, n - 1)); + out +} + +/// The distance from q to the polyline p, both relative to one origin. +fn to_line(p: &[[f64; 2]], q: [f64; 2]) -> f64 { + let mut best = f64::INFINITY; + for w in p.windows(2) { + best = best.min(to_segment(w[0], w[1], q)); + } + if p.len() == 1 { + best = libm::hypot(q[0] - p[0][0], q[1] - p[0][1]); + } + best +} + +fn to_segment(a: [f64; 2], b: [f64; 2], q: [f64; 2]) -> f64 { + let ab = [b[0] - a[0], b[1] - a[1]]; + let l2 = ab[0] * ab[0] + ab[1] * ab[1]; + let f = if l2 > 0.0 { (((q[0] - a[0]) * ab[0] + (q[1] - a[1]) * ab[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + libm::hypot(q[0] - a[0] - f * ab[0], q[1] - a[1] - f * ab[1]) +} + +fn unit(v: [f64; 2]) -> [f64; 2] { + let l = libm::hypot(v[0], v[1]); + if l > 0.0 { + [v[0] / l, v[1] / l] + } else { + [1.0, 0.0] + } +} + +/// The legs of one line in a cell: their points and the cuts with their mitre directions, in cell +/// units, and the reach of each leg from its class. Every value derives from differences to a leg's +/// or a cut's point, so two cells that hold the legs give the same results. +pub struct Legs { + /// Per leg, its points. + legs: Vec>, + /// Per leg, its points relative to its first one. + rel: Vec>, + /// Per leg, its box: [x0, y0, x1, y1]. + boxes: Vec<[f64; 4]>, + /// Per leg, twice the widest core of its class (units at its first cut): the largest distance + /// between the centres of two parts that can conflict, as their cores touch there (`cuts`). + reach: Vec, + /// Per cut, its point and the direction of the line there (the bisector of its two chords). + mitres: Vec<(P, [f64; 2])>, +} + +impl Legs { + /// The legs of points `p` at `cuts`; `reach(o)` is twice the widest core of the line's class in + /// units at o. + pub fn new(p: &[P], cuts: &[usize], reach: &dyn Fn(P) -> f64) -> Legs { + let ranges = ranges(cuts, p.len()); + let legs: Vec> = ranges.iter().map(|&(lo, hi)| p[lo..=hi].to_vec()).collect(); + let rel = (legs.iter()) + .map(|l| l.iter().map(|v| [f64::from(v[0] - l[0][0]), f64::from(v[1] - l[0][1])]).collect()) + .collect(); + let boxes = (legs.iter()) + .map(|l| { + l.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |m, v| { + let v = [f64::from(v[0]), f64::from(v[1])]; + [m[0].min(v[0]), m[1].min(v[1]), m[2].max(v[0]), m[3].max(v[1])] + }) + }) + .collect(); + // A leg's first cut: the one at its start, or for the first leg the one at its end. + let reach = (0..legs.len()).map(|k| reach(p[cuts[k.saturating_sub(1)]])).collect(); + let mitres = (cuts.iter().enumerate()) + .map(|(n, &k)| { + let o = p[k]; + let (a, b) = (legs[n][legs[n].len() - 2], legs[n + 1][1]); + let (ua, ub) = ( + unit([f64::from(o[0] - a[0]), f64::from(o[1] - a[1])]), + unit([f64::from(b[0] - o[0]), f64::from(b[1] - o[1])]), + ); + (o, unit([ua[0] + ub[0], ua[1] + ub[1]])) + }) + .collect(); + Legs { legs, rel, boxes, reach, mitres } + } + + /// The reach of legs m and n (`reach`). + fn reach(&self, m: usize, n: usize) -> f64 { + self.reach[m].max(self.reach[n]) + } + + /// The units from q to leg k. + fn to_leg(&self, k: usize, q: [f64; 2]) -> f64 { + let o = self.legs[k][0]; + to_line(&self.rel[k], [q[0] - f64::from(o[0]), q[1] - f64::from(o[1])]) + } + + /// The medial lines between any two legs, stepping `step(o)` units along a leg (o the pair's + /// cut) and reaching as far from it as their parts can conflict. + pub fn medial(&self, step: &dyn Fn(P) -> f64) -> Vec<[P; 2]> { + let mut lines = Vec::new(); + for m in 0..self.legs.len() { + for n in m + 1..self.legs.len() { + let reach = self.reach(m, n); + let (x, y, gap) = (self.boxes[m], self.boxes[n], 2.0 * reach); + if x[0] > y[2] + gap || y[0] > x[2] + gap || x[1] > y[3] + gap || y[1] > x[3] + gap { + continue; + } + // About the end of leg m: a cut, shared with leg n if they are consecutive. + let (o, t) = self.mitres[m]; + let rel = |q: &P| [f64::from(q[0] - o[0]), f64::from(q[1] - o[1])]; + let a: Vec<[f64; 2]> = self.legs[m].iter().map(rel).collect(); + let b: Vec<[f64; 2]> = self.legs[n].iter().map(rel).collect(); + for run in medial(&a, &b, (n == m + 1).then_some(t), step(o), reach) { + let pts: Vec

= run + .iter() + .map(|v| [o[0] + libm::round(v[0]) as i32, o[1] + libm::round(v[1]) as i32]) + .collect(); + lines.extend(pts.windows(2).filter(|w| w[0] != w[1]).map(|w| [w[0], w[1]])); + } + } + } + lines + } + + /// Per leg, the stretches of it whose bands can come within reach of another leg, with the leg's + /// reach: a segment one of whose ends lies within twice the reach of another leg, as a point of a + /// band lies within the reach of its leg. + pub fn runs(&self) -> Vec<(usize, Vec

, f64)> { + let mut out = Vec::new(); + for (k, leg) in self.legs.iter().enumerate() { + let near: Vec = (leg.iter()) + .map(|v| { + let q = [f64::from(v[0]), f64::from(v[1])]; + (0..self.legs.len()).any(|j| j != k && self.to_leg(j, q) <= 2.0 * self.reach(k, j)) + }) + .collect(); + let mut i = 0; + while i + 1 < leg.len() { + if !(near[i] || near[i + 1]) { + i += 1; + continue; + } + let lo = i; + while i + 1 < leg.len() && (near[i] || near[i + 1]) { + i += 1; + } + out.push((k, leg[lo..=i].to_vec(), self.reach[k])); + } + } + out + } + + /// The leg nearest q (cell units); a tie between two consecutive legs goes to the side of their + /// cut's mitre line. + pub fn nearest(&self, q: [f64; 2]) -> u8 { + let mut best = (f64::INFINITY, 0); + for k in 0..self.legs.len() { + let d = self.to_leg(k, q); + let tie = (d - best.0).abs() <= 1e-9 * d.max(1.0); + if tie && k == best.1 + 1 { + let (c, t) = self.mitres[best.1]; + let v = [q[0] - f64::from(c[0]), q[1] - f64::from(c[1])]; + if v[0] * t[0] + v[1] * t[1] >= 0.0 { + best = (d, k); + } + } else if d < best.0 && !tie { + best = (d, k); + } + } + best.1 as u8 + } +} + +/// A polyline's segments in boxes of `BOX` segments, for its nearest point to q within a pad. +struct Near<'a> { + p: &'a [[f64; 2]], + boxes: Vec<[f64; 4]>, +} + +const BOX: usize = 16; + +impl<'a> Near<'a> { + fn new(p: &'a [[f64; 2]]) -> Self { + let boxes = (0..p.len().saturating_sub(1)) + .step_by(BOX) + .map(|s| { + p[s..(s + BOX + 1).min(p.len())].iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |m, v| { + [m[0].min(v[0]), m[1].min(v[1]), m[2].max(v[0]), m[3].max(v[1])] + }) + }) + .collect(); + Near { p, boxes } + } + + /// The nearest point to q of the segments within `pad` of it, and its distance. + fn nearest(&self, q: [f64; 2], pad: f64) -> Option<(f64, [f64; 2])> { + let mut best: Option<(f64, [f64; 2])> = None; + for (k, bx) in self.boxes.iter().enumerate() { + if q[0] < bx[0] - pad || q[0] > bx[2] + pad || q[1] < bx[1] - pad || q[1] > bx[3] + pad { + continue; + } + for s in k * BOX..((k + 1) * BOX).min(self.p.len() - 1) { + let (a, b) = (self.p[s], self.p[s + 1]); + let ab = [b[0] - a[0], b[1] - a[1]]; + let l2 = ab[0] * ab[0] + ab[1] * ab[1]; + let f = + if l2 > 0.0 { (((q[0] - a[0]) * ab[0] + (q[1] - a[1]) * ab[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let c = [a[0] + f * ab[0], a[1] + f * ab[1]]; + let d = libm::hypot(q[0] - c[0], q[1] - c[1]); + if best.is_none_or(|(e, _)| d < e) { + best = Some((d, c)); + } + } + } + best + } +} + +/// The medial lines between legs A and B, relative to the end of A: the points as near to both, +/// traced in steps of `step` while they lie within `reach` of A, and on `reach` past their ends. Where +/// B starts at A's end, a cut with +/// the line's direction t there, the first line runs from `reach` out on the cut's mitre line on the +/// outer side of the turn through the cut, and on along the medial line on the inner side. Every +/// other part of the medial line starts where a point of A, searched along its normal every `step`, +/// finds one that no line passes yet, and runs both ways from it. +fn medial(a: &[[f64; 2]], b: &[[f64; 2]], t: Option<[f64; 2]>, step: f64, reach: f64) -> Vec> { + let na = a.len(); + if na < 2 || b.len() < 2 { + return Vec::new(); + } + let (near_a, near_b) = (Near::new(a), Near::new(b)); + let pad = 2.0 * reach; + let dist = |near: &Near, v: [f64; 2]| near.nearest(v, pad).map_or(f64::INFINITY, |r| r.0); + // Positive on A's side of the medial line. + let side = |v: [f64; 2]| dist(&near_b, v) - dist(&near_a, v); + // The root of h between lo and hi, where h changes sign, by the false position with the Illinois + // halving: `side` is nearly linear across the medial line. To a twentieth of a unit of `side` + // (a fortieth of a unit across): the points round to whole units. + let root = |h: &dyn Fn(f64) -> f64, mut lo: f64, mut hi: f64| { + let (mut fl, mut fh) = (h(lo), h(hi)); + let mut last = 0; + for _ in 0..60 { + if hi - lo <= 0.01 { + break; + } + let mid = if fh != fl { (lo * fh - hi * fl) / (fh - fl) } else { 0.5 * (lo + hi) }; + let mid = mid.clamp(lo, hi); + let fm = h(mid); + if fm.abs() <= 0.05 { + return mid; + } + if (fm > 0.0) == (fl > 0.0) { + (lo, fl) = (mid, fm); + if last == -1 { + fh *= 0.5; + } + last = -1; + } else { + (hi, fh) = (mid, fm); + if last == 1 { + fl *= 0.5; + } + last = 1; + } + } + 0.5 * (lo + hi) + }; + // From v along the direction d: each step ahead, the point of the medial line on the step's + // normal within two steps, until none is or it lies past `reach` from A. + let limit = + (a.windows(2).chain(b.windows(2)).map(|w| libm::hypot(w[1][0] - w[0][0], w[1][1] - w[0][1])).sum::() + / step) as usize + + 1; + let trace = |mut v: [f64; 2], mut d: [f64; 2]| -> Vec<[f64; 2]> { + let mut out = Vec::new(); + for _ in 0..limit { + let w = [v[0] + d[0] * step, v[1] + d[1] * step]; + let n = [-d[1], d[0]]; + let h = |x: f64| side([w[0] + n[0] * x, w[1] + n[1] * x]); + if (h(-2.0 * step) > 0.0) == (h(2.0 * step) > 0.0) { + break; + } + let x = root(&h, -2.0 * step, 2.0 * step); + let next = [w[0] + n[0] * x, w[1] + n[1] * x]; + if dist(&near_a, next) > reach { + break; + } + d = unit([next[0] - v[0], next[1] - v[1]]); + v = next; + out.push(v); + } + out + }; + let mut runs: Vec> = Vec::new(); + if let Some(t) = t { + // The cut's mitre line on the outer side: the side away from the turn. + let left = [-t[1], t[0]]; + let (ua, ub) = (unit([-a[na - 2][0], -a[na - 2][1]]), unit(b[1])); + let outer = if ua[0] * ub[1] - ua[1] * ub[0] > 0.0 { [-left[0], -left[1]] } else { left }; + let mut run = vec![[outer[0] * reach, outer[1] * reach], [0.0, 0.0]]; + run.extend(trace([0.0, 0.0], [-outer[0], -outer[1]])); + runs.push(run); + } + // The runs' points in bins of two steps, for the run points within two steps of a point. + let bin = |v: [f64; 2]| [libm::floor(v[0] / (2.0 * step)) as i64, libm::floor(v[1] / (2.0 * step)) as i64]; + let mut bins: BTreeMap<[i64; 2], Vec<[f64; 2]>> = BTreeMap::new(); + let add = |bins: &mut BTreeMap<[i64; 2], Vec<[f64; 2]>>, run: &[[f64; 2]]| { + for &v in run { + bins.entry(bin(v)).or_default().push(v); + } + }; + for run in &runs { + add(&mut bins, run); + } + let covered = |bins: &BTreeMap<[i64; 2], Vec<[f64; 2]>>, v: [f64; 2]| { + let c = bin(v); + (-1..=1).any(|i| { + (-1..=1).any(|j| { + (bins.get(&[c[0] + i, c[1] + j]).into_iter().flatten()) + .any(|w| libm::hypot(w[0] - v[0], w[1] - v[1]) <= 2.0 * step) + }) + }) + }; + for s in (0..na - 1).rev() { + let (p0, p1) = (a[s], a[s + 1]); + let len = libm::hypot(p1[0] - p0[0], p1[1] - p0[1]); + // A medial point within `reach` of A has B within twice that: a segment farther from B seeds + // none. + if near_b.nearest(p0, 2.0 * reach + len).is_none_or(|r| r.0 > 2.0 * reach + len) { + continue; + } + let u = unit([p1[0] - p0[0], p1[1] - p0[1]]); + let m = libm::ceil(len / step).max(1.0) as usize; + for e in (0..m).rev() { + let f = e as f64 / m as f64; + let q = [p0[0] + f * (p1[0] - p0[0]), p0[1] + f * (p1[1] - p0[1])]; + // Along A's normal on either side, the first point of the medial line: the nearer one. + let found = [1.0, -1.0] + .into_iter() + .filter_map(|sign| { + let n = [u[1] * sign, -u[0] * sign]; + let h = |x: f64| side([q[0] + n[0] * x, q[1] + n[1] * x]); + (h(reach) <= 0.0).then(|| { + let x = root(&h, 0.0, reach); + (x, [q[0] + n[0] * x, q[1] + n[1] * x]) + }) + }) + .min_by(|a, b| a.0.total_cmp(&b.0)); + let Some((_, v)) = found else { continue }; + if covered(&bins, v) { + continue; + } + // The medial line's direction there: normal to the change of `side`. + let e = step / 4.0; + let g = [side([v[0] + e, v[1]]) - side([v[0] - e, v[1]]), side([v[0], v[1] + e]) - side([v[0], v[1] - e])]; + let d = unit([-g[1], g[0]]); + let mut run: Vec<[f64; 2]> = trace(v, [-d[0], -d[1]]).into_iter().rev().collect(); + run.push(v); + run.extend(trace(v, d)); + if run.len() >= 2 { + add(&mut bins, &run); + runs.push(run); + } + } + } + // Each run goes on `reach` past its ends, where a third part of a leg ends the trace inside the + // legs' overlap; the one from a cut starts out on the mitre line already. + for (k, run) in runs.iter_mut().enumerate() { + let n = run.len(); + if n < 2 { + continue; + } + let d = unit([run[n - 1][0] - run[n - 2][0], run[n - 1][1] - run[n - 2][1]]); + run.push([run[n - 1][0] + d[0] * reach, run[n - 1][1] + d[1] * reach]); + if k > 0 || t.is_none() { + let d = unit([run[0][0] - run[1][0], run[0][1] - run[1][1]]); + run.insert(0, [run[0][0] + d[0] * reach, run[0][1] + d[1] * reach]); + } + } + runs +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A hairpin: leg A up x = −r, a half circle over the top, leg B down x = +r, rising `grade` per + /// unit along it. + fn hairpin(r: f64, legs: i32, grade: f64) -> (Vec

, Vec) { + let mut p: Vec

= (0..legs).rev().map(|k| [-r as i32, -k * 100]).collect(); + for k in 1..18 { + let a = std::f64::consts::PI * f64::from(k) / 18.0; + p.push([libm::round(-r * libm::cos(a)) as i32, libm::round(r * libm::sin(a)) as i32]); + } + p.extend((0..legs).map(|k| [r as i32, -k * 100])); + let mut z = vec![0.0]; + for w in p.windows(2) { + z.push(z.last().unwrap() + grade * dist(w[0], w[1])); + } + (p, z) + } + + #[test] + fn a_hairpin_splits_at_its_apex_and_a_level_one_or_a_wide_one_does_not() { + let (p, z) = hairpin(300.0, 20, 0.001); + let core = vec![400.0; p.len()]; + assert_eq!(cuts(&p, &core, &vec![600.0; p.len()], &z, 1.0), vec![(p.len() - 1) / 2]); + // Steeper, it still splits once: the turn lies along each leg, not beside it. + let (_, z) = hairpin(300.0, 20, 0.01); + assert_eq!(cuts(&p, &core, &vec![600.0; p.len()], &z, 1.0), vec![(p.len() - 1) / 2]); + let flat = vec![0.0; p.len()]; + assert!(cuts(&p, &core, &vec![600.0; p.len()], &flat, 1.0).is_empty()); + let (p, z) = hairpin(900.0, 20, 0.001); + assert!(cuts(&p, &core, &vec![600.0; p.len()], &z, 1.0).is_empty(), "slope bands 1,800 apart do not meet"); + } + + #[test] + fn a_steep_bend_wider_than_its_core_does_not_split() { + // A quarter circle of radius 1,000 sampled every 2°, rising 1 per 5 samples: the line between + // two samples whose cores touch stays in their discs. + let p: Vec

= (0..=45) + .map(|k| f64::from(k) * 2.0f64.to_radians()) + .map(|a| [libm::round(1000.0 * libm::cos(a)) as i32, libm::round(1000.0 * libm::sin(a)) as i32]) + .collect(); + let z: Vec = (0..p.len()).map(|k| k as f64 * 0.2).collect(); + assert!(cuts(&p, &vec![400.0; p.len()], &vec![600.0; p.len()], &z, 1.0).is_empty()); + } + + #[test] + fn a_zigzag_splits_once_per_turn_and_every_conflict_has_a_cut_between_its_parts() { + // Up x = −300, over a turn about (0, 0), down x = 300, under a turn about (600, −1,000), up + // x = 900. + let arc = |c: [f64; 2], from: f64| -> Vec

{ + (1..18) + .map(|k| from + std::f64::consts::PI * f64::from(k) / 18.0) + .map(|a| { + [libm::round(c[0] + 300.0 * libm::cos(a)) as i32, libm::round(c[1] + 300.0 * libm::sin(a)) as i32] + }) + .collect() + }; + let mut p: Vec

= (0..=10).map(|k| [-300, -1000 + 100 * k]).collect(); + p.extend(arc([0.0, 0.0], std::f64::consts::PI).into_iter().map(|v| [v[0], -v[1]])); + p.extend((0..=10).map(|k| [300, -100 * k])); + p.extend(arc([600.0, -1000.0], std::f64::consts::PI)); + p.extend((0..=10).map(|k| [900, -1000 + 100 * k])); + let mut z = vec![0.0]; + for w in p.windows(2) { + z.push(z.last().unwrap() + 0.001 * dist(w[0], w[1])); + } + let core = vec![400.0; p.len()]; + let found = cuts(&p, &core, &vec![600.0; p.len()], &z, 1.0); + assert_eq!(found.len(), 2, "{found:?}"); + assert!(found[0] < found[1]); + // Each within a sample of the top of its turn. + assert!(p[found[0]][1] >= 295, "the first cut at the top of its turn: {:?}", p[found[0]]); + assert!(p[found[1]][1] <= -1295, "the second at the bottom of its turn: {:?}", p[found[1]]); + assert!(leg(&found, found[0], 1) == 1 && leg(&found, found[0], -1) == 0); + } + + #[test] + fn the_medial_line_divides_a_hairpin_between_its_legs() { + let (p, z) = hairpin(300.0, 20, 0.001); + let core = vec![400.0; p.len()]; + let found = cuts(&p, &core, &vec![600.0; p.len()], &z, 1.0); + let legs = Legs::new(&p, &found, &|_| 1000.0); + let lines = legs.medial(&|_| 25.0); + // The medial line runs up x = 0 between the legs, and the outer side of the apex splits on the + // mitre line, which is x = 0 there too. + let off: Vec = lines.iter().flatten().filter(|v| v[1] < 0 && v[1] > -1500).map(|v| v[0].abs()).collect(); + assert!(!off.is_empty() && off.iter().all(|&x| x <= 1), "{off:?}"); + assert!(lines.iter().flatten().any(|v| v[1] > 300), "the mitre line on the outer side"); + assert_eq!(legs.nearest([-150.0, -800.0]), 0); + assert_eq!(legs.nearest([150.0, -800.0]), 1); + assert_eq!(legs.nearest([-10.0, 600.0]), 0); + assert_eq!(legs.nearest([10.0, 600.0]), 1); + } +} diff --git a/host/obc-ground-plan/src/faces/mod.rs b/host/obc-ground-plan/src/faces/mod.rs new file mode 100644 index 0000000000..82e7fbd229 --- /dev/null +++ b/host/obc-ground-plan/src/faces/mod.rs @@ -0,0 +1,1962 @@ +//! The faces of ways and junctions in one cell and level: integer strokes of the ways, a round per +//! pair of neighbouring arms at each graph point (a tangent circle and its fan), point regions that +//! relabel their arms up to straight seams, band layers as wider strokes, one integer slice of the +//! cell by all their outlines, and a label per patch by key. Every point of the cell lies in exactly +//! one face. + +pub mod check; +mod cover; +pub mod culverts; +pub mod deck; +mod geom; +pub mod heights; +pub mod legs; +mod outline; +mod platform; +mod points; +pub mod records; +pub mod rules; +mod slice; +mod stroke; +#[cfg(test)] +pub(crate) mod tests; +mod types; + +use std::collections::BTreeMap; + +pub use deck::{DeckWay, Storeys}; +pub use rules::{input_m, Mouth, Pair, PlanRules, Rank, Rules}; +pub use types::*; + +use cover::Cover; +use geom::{grid_points, inner_point, with_grid_lines, P}; +use points::{Arm, Circle, Part, Rounded}; +use slice::{on_cell_line, slice, snap_round, Loop, Map, NONE}; +use stroke::{pieces_along, union, Rings}; + +use crate::frame::{metres_per_unit, CellKey, GlobalPoint, CELL_UNITS, FRAME_BITS}; +use crate::graph::{Family, Level, Station, WayGraph}; +use crate::sections::{WaySection, HALF_MAX_M}; +use crate::CellInput; + +/// A way of the level: all its samples in cell units, with its half-width and band offsets. +pub(crate) struct WayLine<'a> { + pub way: u32, + pub sec: WaySection<'a>, + pub rail: bool, + pub p: Vec

, + /// The carriageway half-width in units. + pub h: Vec, + /// The outer offsets in units of the band layers (`LAYERS`). + pub bands: Vec<[f64; LAYERS]>, + /// The global key of the span of each sample. + pub key: Vec, + /// Per sample, the sides of the segment from it on with a sidewalk: 1 left, 2 right. + pub walk: Vec, + pub round: [bool; 2], + /// Whether each end is a deck end: a ground way's end at a joint or junction with a deck arm. + pub deck: [bool; 2], + /// The box of its carriageway: its samples' box grown by its widest half-width. + pub bbox: [i32; 4], + /// The boxes of the carriageway of each `CHUNK` segments in order. + pub chunks: Vec<[i32; 4]>, + /// The index in `p` of each of the way's graph samples: a taper adds vertices between them. + pub index: Vec, + /// The points in `p` where the line splits into legs (`legs::cuts`), and each cut's span + /// (`legs::spans`). + pub cuts: Vec, + pub spans: Vec<(usize, usize)>, + /// The height of each graph sample (metres), in the order of `index`. + pub z: Vec, +} + +/// The band layers about a carriageway, inner to outer: paved shoulder, shoulder, verge, bank, slope. +/// Read a layer by its name, never by its number. A way's bank and water's shoulders and verge are 0 wide. +pub(crate) const LAYERS: usize = 5; +/// The verge, the outer edge of a line's core. +pub(crate) const VERGE: usize = 2; +/// The slope, the outermost layer. +pub(crate) const SLOPE: usize = LAYERS - 1; + +/// Segments per box of `WayLine::chunks`: a test near one point reads only the segments of a long way +/// there. +const CHUNK: usize = 16; + +impl WayLine<'_> { + /// The segments (i, i + 1) whose carriageway can come within `pad` units of q. + pub fn near(&self, q: [f64; 2], pad: f64) -> impl Iterator + '_ { + let far = move |b: &[i32; 4]| { + q[0] < f64::from(b[0]) - pad + || q[0] > f64::from(b[2]) + pad + || q[1] < f64::from(b[1]) - pad + || q[1] > f64::from(b[3]) + pad + }; + let n = self.p.len().saturating_sub(1); + let chunks = if far(&self.bbox) { &self.chunks[..0] } else { &self.chunks[..] }; + (chunks.iter().enumerate()) + .filter(move |(_, b)| !far(b)) + .flat_map(move |(k, _)| k * CHUNK..((k + 1) * CHUNK).min(n)) + } + + /// The offsets of the layers at sample i, inner to outer: carriageway, then `LAYERS`. + pub fn offsets(&self, i: usize) -> [f64; LAYERS + 1] { + std::array::from_fn(|k| if k == 0 { self.h[i] } else { self.bands[i][k - 1] }) + } + + /// The half-width of the core (carriageway, shoulder and verge) at each sample. + pub fn core(&self) -> Vec { + self.bands.iter().map(|b| b[VERGE]).collect() + } + + /// Twice the widest core of the way's section, its carriageway widened in full at a bend + /// (metres): the reach of its legs (`legs::Legs`). + pub fn leg_reach_m(&self) -> f64 { + let s = &self.sec; + 2.0 * (s.half_m + s.widen_m + s.shoulder_m + s.verge_m) + } +} + +/// A global name that two cells give alike: a span's owner tile and feature with its start vertex, +/// or a point's position. +type Glob = [i64; 5]; + +/// The window of a cell: its square grown by `m` metres at its edge nearer the pole, in cell units. +pub fn window(cell: CellKey, m: f64) -> [i32; 4] { + let o = cell.origin(); + let pole = if o.y < 1 << (FRAME_BITS - 1) { o.y } else { o.y + CELL_UNITS }; + let w = (m / metres_per_unit(pole)).floor() as i32; + let c = CELL_UNITS as i32; + [-w, -w, c + w, c + w] +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Label { + owner: Owner, + surface: Surface, + rule: HeightRule, + material: Option, + crossing: Option, + rank: u8, + reach_m: f32, + /// The legs of `material` and `crossing` (`legs`). + legs: [u8; 2], +} + +impl Label { + fn of(f: &Face) -> Label { + let (owner, surface, rule, material, crossing, rank) = + (f.owner, f.surface, f.rule, f.material, f.crossing, f.rank); + Label { owner, surface, rule, material, crossing, rank, reach_m: f.reach_m, legs: f.legs } + } +} + +const TERRAIN: Label = Label { + owner: Owner::Terrain, + surface: Surface::Terrain, + rule: HeightRule::Terrain, + material: None, + crossing: None, + rank: u8::MAX, + reach_m: 0.0, + legs: [0, 0], +}; + +/// A candidate: rings with the NonZero rule, a label, and the key by which it wins: rank, class, +/// kind (a point before a way), then its global name (a way's at the point asked). A point's region +/// (`relabel`: the parts of its arms' lines in it, each with its seams) gives no surface: it gives its +/// label to a patch of one of its ways that lies past none of that way's seams. A point's fans give +/// a patch past one of the seams they reach across (`beyond`) the label of the face on its other side. +/// A round at a corner of the paved outline (`fill`) takes the label at its point inside the paved +/// area. +struct Cand { + rings: Rings, + label: Label, + key: (u8, u8, u8), + glob: Option, + line: usize, + relabel: Option>, + beyond: Vec<([P; 2], Label)>, + fill: Option<[i64; 2]>, + /// The circles whose discs the records leave out of the candidate, so that the records' arcs are + /// true circles where the overlay's are chords. + discs: Vec, +} + +struct Ctx<'a> { + graph: &'a WayGraph, + rules: &'a Rules, + origin: GlobalPoint, +} + +impl Ctx<'_> { + fn units(&self, m: f64, p: P) -> f64 { + m / metres_per_unit(self.origin.y + i64::from(p[1])) + } + + fn global(&self, p: P) -> [i64; 2] { + [self.origin.x + i64::from(p[0]), self.origin.y + i64::from(p[1])] + } +} + +/// Whether the storeys over the ground are built (the feature `storeys`): a build without them links none of their +/// code. +const STOREYS: bool = cfg!(feature = "storeys"); + +/// A way of storey 0. Water lies on the ground or in a tunnel, never on a deck. +fn in_level(graph: &WayGraph, way: u32) -> bool { + graph.ways[way as usize].level == Level::Ground +} + +/// The ways of a level's lines: storey 0's (`in_level`), or those of a storey over the ground (`deck::Decks`). +fn keep<'a>(graph: &'a WayGraph, decks: Option<&'a deck::Decks>, level: i8) -> impl Fn(u32) -> bool + 'a { + move |w| match decks { + Some(d) => d.storey[w as usize] == level, + None => in_level(graph, w), + } +} + +/// A deck way: a ceiling line of storey 0 (`ceiling_lines`). +fn on_deck(graph: &WayGraph, way: u32) -> bool { + let w = &graph.ways[way as usize]; + w.family != Family::Water && w.level == Level::Deck +} + +fn station_key(way: u32, dir: i8, st: &Station) -> (u32, i8, u32, u64) { + (way, dir, st.span, st.u.to_bits()) +} + +/// The lines of the ways that `keep` keeps whose centre line meets the box `bx`: the ways, then the water, so +/// the way lines are a prefix that holds no water. +fn lines<'a>( + ctx: &Ctx<'a>, + input: &CellInput, + keep: &dyn Fn(u32) -> bool, + bx: [i32; 4], +) -> (Vec>, BTreeMap) { + let g = ctx.graph; + // The round ends: free ends. A way ends square at a junction or a joint, whose face fills the + // gaps between its arms; and at a level change. + let mut ends: BTreeMap<(u32, i8, u32, u64), bool> = BTreeMap::new(); + for e in &g.ends { + ends.insert(station_key(e.arm.way, e.arm.dir, &e.arm.at), true); + } + // The deck ends: the ground arms of a joint or junction with a deck arm. + let mut decks = std::collections::BTreeSet::new(); + for arms in g.junctions.iter().map(|j| &j.arms[..]).chain(g.joints.iter().map(|j| &j.arms[..])) { + if arms.iter().any(|a| a.level == Level::Deck) { + decks.extend(arms.iter().filter(|a| a.level == Level::Ground).map(|a| station_key(a.way, a.dir, &a.at))); + } + } + let mut out = Vec::new(); + let mut of_way = BTreeMap::new(); + let (ways, water): (Vec<_>, Vec<_>) = g.ways.iter().partition(|w| w.family != Family::Water); + for way in ways.into_iter().chain(water) { + if !keep(way.id) { + continue; + } + let samples = &g.samples[way.samples.start as usize..way.samples.end as usize]; + if !samples.windows(2).any(|s| geom::meets(bx, s[0].pos, s[1].pos)) { + continue; + } + let part = &g.parts[way.part as usize]; + let feature = &input.features[part.feature.0 as usize]; + let sec = ctx.rules.sections.way(&feature.kind, &feature.tags, false); + let sh = sec.shoulder_m; + // The bank band ends at the bank top: where the bank's cut reaches its rise on level ground. + let bank = heights::cone_reach(sec.cut, sec.rise_m, &ctx.rules.plan.heights); + let mut line = WayLine { + way: way.id, + rail: way.family == Family::Rail, + p: Vec::with_capacity(samples.len()), + h: Vec::with_capacity(samples.len()), + bands: Vec::with_capacity(samples.len()), + key: Vec::with_capacity(samples.len()), + walk: samples.iter().map(|s| s.walk).collect(), + round: [ + ends.get(&station_key(way.id, 1, &way.from)).copied().unwrap_or(false), + ends.get(&station_key(way.id, -1, &way.to)).copied().unwrap_or(false), + ], + deck: [ + decks.contains(&station_key(way.id, 1, &way.from)), + decks.contains(&station_key(way.id, -1, &way.to)), + ], + bbox: [i32::MAX, i32::MAX, i32::MIN, i32::MIN], + chunks: Vec::new(), + index: (0..samples.len()).collect(), + cuts: Vec::new(), + spans: Vec::new(), + z: samples.iter().map(|s| s.z_m).collect(), + sec, + }; + for s in samples { + let u = |m: f64| ctx.units(m, s.pos); + let h = sec.half_m + s.widen_m; + line.p.push(s.pos); + line.h.push(u(h)); + let paved = if sec.shoulder_paved { sh } else { 0.0 }; + let verge = h + sh + sec.verge_m; + line.bands.push([u(h + paved), u(h + sh), u(verge), u(verge + bank), u(verge + sec.reach_m)]); + let span = s.span.min(part.spans.len() as u32 - 1) as usize; + let o = part.spans[span].owner; + let v = part.vertices[span].pos; + line.key.push([i64::from(o[0]), i64::from(o[1]), i64::from(o[2]), v[0], v[1]]); + } + // Its legs, on its graph samples: two parts beside each other whose slope bands meet at heights + // that do not agree. A way of a class without a wall between its legs stays one line. + if sec.leg_wall { + let feather = sec.reach_m.max(ctx.rules.plan.heights.feather_min_m); + let ok = heights::step_limit(sec.return_grade, feather, &ctx.rules.plan.heights) / 2.0; + let band: Vec = line.bands.iter().map(|b| b[SLOPE]).collect(); + line.spans = legs::spans(&line.p, &line.core(), &band, &line.z, ok); + line.cuts = line.spans.iter().map(|&(a, b)| (a + b) / 2).collect(); + } + of_way.insert(way.id, out.len()); + out.push(line); + } + taper(ctx, &mut out, &of_way); + for line in &mut out { + line.cuts = line.cuts.iter().map(|&k| line.index[k]).collect(); + line.spans = line.spans.iter().map(|&(a, b)| (line.index[a], line.index[b])).collect(); + } + let grow = + |b: [i32; 4], p: P, h: i32| [b[0].min(p[0] - h), b[1].min(p[1] - h), b[2].max(p[0] + h), b[3].max(p[1] + h)]; + for line in &mut out { + let h = libm::ceil(line.h.iter().copied().fold(0.0, f64::max)) as i32; + for &p in &line.p { + line.bbox = grow(line.bbox, p, h); + } + let n = line.p.len(); + line.chunks = (0..n.saturating_sub(1).div_ceil(CHUNK)) + .map(|k| { + let ids = k * CHUNK..((k + 1) * CHUNK + 1).min(n); + let h = libm::ceil(line.h[ids.clone()].iter().copied().fold(0.0, f64::max)) as i32; + ids.fold([i32::MAX, i32::MAX, i32::MIN, i32::MIN], |b, i| grow(b, line.p[i], h)) + }) + .collect(); + } + (out, of_way) +} + +/// A taper of a line's layers from a joint: from the vertex `at` along `dir`, each layer's offset +/// starts at the other arm's offset of that layer, `to`. +struct Taper { + at: usize, + dir: i8, + to: [f64; LAYERS + 1], +} + +/// At a joint, each layer edge (carriageway, then `LAYERS`) of the arm that +/// is wider there runs straight into the other arm's edge of that layer: its offset is at most the +/// other's plus a rate times the distance from the joint. So a band that the other arm lacks tapers +/// out with the carriageway. The rate is `taper_rate`, or more where the layer's own offset within +/// `extent_m` of the joint (it widens in a bend) would end the taper past `extent_m`: so the taper +/// meets the own edge within `extent_m`, with no step. A vertex is added where a taper meets the own +/// offset, so the edge turns there and at the joint only. At a junction, a guest tapers so into the +/// largest offset of each layer of the other arms; the hosts keep their widths. +fn taper(ctx: &Ctx, lines: &mut [WayLine], of_way: &BTreeMap) { + let g = ctx.graph; + let mut tapers: BTreeMap> = BTreeMap::new(); + for (pos, arms) in g.joints.iter().map(|j| (j.pos, &j.arms)) { + let (Some(&la), Some(&lb)) = (of_way.get(&arms[0].way), of_way.get(&arms[1].way)) else { continue }; + if arms[0].level != arms[1].level || la == lb { + continue; + } + let at = [sample_at(g, &lines[la], &arms[0].at, pos), sample_at(g, &lines[lb], &arms[1].at, pos)]; + let o = [lines[la].offsets(at[0]), lines[lb].offsets(at[1])]; + for (me, l) in [(0, la), (1, lb)] { + if (0..=LAYERS).any(|m| o[me][m] - o[1 - me][m] >= 1.0) { + tapers.entry(l).or_default().push(Taper { at: at[me], dir: arms[me].dir, to: o[1 - me] }); + } + } + } + // A guest's square end at the point would stand out of a narrower host's far edge. + for j in &g.junctions { + let arms: Vec<(&crate::graph::Arm, usize)> = + j.arms.iter().filter_map(|a| of_way.get(&a.way).map(|&l| (a, l))).collect(); + if arms.len() < j.arms.len() || arms.iter().any(|(a, _)| a.level != arms[0].0.level) { + continue; + } + let at: Vec = arms.iter().map(|(a, l)| sample_at(g, &lines[*l], &a.at, j.pos)).collect(); + let o: Vec<[f64; LAYERS + 1]> = arms.iter().zip(&at).map(|((_, l), &i)| lines[*l].offsets(i)).collect(); + for (k, (a, l)) in arms.iter().enumerate().filter(|(_, (a, _))| !a.host) { + let to: [f64; LAYERS + 1] = + std::array::from_fn(|m| (0..o.len()).filter(|&i| i != k).map(|i| o[i][m]).fold(0.0, f64::max)); + if (0..=LAYERS).any(|m| o[k][m] - to[m] >= 1.0) { + tapers.entry(*l).or_default().push(Taper { at: at[k], dir: a.dir, to }); + } + } + } + for (l, list) in tapers { + let line = &mut lines[l]; + let n = line.p.len(); + let extent = ctx.units(ctx.rules.plan.extent_m, line.p[list[0].at]); + let own: Vec<[f64; LAYERS + 1]> = (0..n).map(|i| line.offsets(i)).collect(); + // The distance of each vertex from each taper's joint along the line, to the first past + // `extent_m`; each taper's rate per layer. + let mut along = vec![vec![f64::INFINITY; n]; list.len()]; + let mut rate = vec![[ctx.rules.plan.taper_rate; LAYERS + 1]; list.len()]; + for (k, t) in list.iter().enumerate() { + along[k][t.at] = 0.0; + let mut widest = own[t.at]; + let mut i = t.at; + while let Some(j) = i.checked_add_signed(isize::from(t.dir)).filter(|&j| j < n) { + let (a, b) = (line.p[i], line.p[j]); + along[k][j] = along[k][i] + libm::hypot(f64::from(b[0] - a[0]), f64::from(b[1] - a[1])); + widest = std::array::from_fn(|m| widest[m].max(own[j][m])); + if along[k][j] >= extent { + break; + } + i = j; + } + for m in 0..=LAYERS { + rate[k][m] = rate[k][m].max((widest[m] - t.to[m]) / extent); + } + } + // The offsets at distances `s` from the joints: each layer at most its tapers, and no layer + // inside the one below it. + let narrowed = |o: [f64; LAYERS + 1], s: &[f64]| { + let mut r = o; + for (k, t) in list.iter().enumerate().filter(|&(k, _)| s[k].is_finite()) { + for m in 0..=LAYERS { + r[m] = r[m].min(t.to[m] + rate[k][m] * s[k]); + } + } + for m in 1..=LAYERS { + r[m] = r[m].max(r[m - 1]); + } + r + }; + // The vertices: position, offsets, key, walk. + let mut rows: Vec<(P, [f64; LAYERS + 1], Glob, u8)> = Vec::with_capacity(n); + let mut index = Vec::with_capacity(n); + for i in 0..n { + index.push(rows.len()); + let s: Vec = (0..list.len()).map(|k| along[k][i]).collect(); + rows.push((line.p[i], narrowed(own[i], &s), line.key[i], line.walk[i])); + if i + 1 == n { + break; + } + // Where a taper meets a layer's own offset inside the segment to i + 1: a vertex there. + let mut cuts: Vec = Vec::new(); + for (k, t) in list.iter().enumerate() { + let (s0, s1) = (along[k][i], along[k][i + 1]); + if !(s0.is_finite() && s1.is_finite()) { + continue; + } + for m in 0..=LAYERS { + let (o0, o1) = (own[i][m], own[i + 1][m]); + let f = |x: f64| t.to[m] + rate[k][m] * (s0 + x * (s1 - s0)) - (o0 + x * (o1 - o0)); + let (f0, f1) = (f(0.0), f(1.0)); + if (f0 < 0.0) != (f1 < 0.0) && f0 != 0.0 && f1 != 0.0 { + cuts.push(f0 / (f0 - f1)); + } + } + } + cuts.sort_by(f64::total_cmp); + let mut last = line.p[i]; + for x in cuts { + let (a, b) = (line.p[i], line.p[i + 1]); + let d = |c: usize| libm::round(x * f64::from(b[c] - a[c])) as i32; + let q = [a[0] + d(0), a[1] + d(1)]; + // As GP2 keeps no two samples closer than half its finest step: the strokes join + // segments of that length or more cleanly. The edge then misses the taper's end by at + // most the rate times that. + let gap = ctx.units(crate::graph::MIN_STEP_M / 2.0, q); + let far = |r: P| libm::hypot(f64::from(q[0] - r[0]), f64::from(q[1] - r[1])) >= gap; + if !far(last) || !far(b) { + continue; + } + last = q; + let o: [f64; LAYERS + 1] = std::array::from_fn(|m| own[i][m] + x * (own[i + 1][m] - own[i][m])); + let s: Vec = (0..list.len()).map(|k| along[k][i] + x * (along[k][i + 1] - along[k][i])).collect(); + rows.push((q, narrowed(o, &s), line.key[i], line.walk[i])); + } + } + line.p = rows.iter().map(|r| r.0).collect(); + line.h = rows.iter().map(|r| r.1[0]).collect(); + line.bands = rows.iter().map(|r| std::array::from_fn(|k| r.1[k + 1])).collect(); + line.key = rows.iter().map(|r| r.2).collect(); + line.walk = rows.iter().map(|r| r.3).collect(); + line.index = index; + } +} + +/// The sample of a line at a graph station, else the one nearest `pos`. +fn sample_at(g: &WayGraph, line: &WayLine, st: &Station, pos: P) -> usize { + let way = &g.ways[line.way as usize]; + let samples = &g.samples[way.samples.start as usize..way.samples.end as usize]; + let exact = samples.iter().position(|s| { + (s.span == st.span && (s.u - st.u).abs() < 1e-9) || (s.span == st.span + 1 && st.u >= 1.0 && s.u <= 0.0) + }); + exact.map(|k| line.index[k]).unwrap_or_else(|| { + let d = |p: P| (i64::from(p[0] - pos[0])).pow(2) + (i64::from(p[1] - pos[1])).pow(2); + (0..line.p.len()).min_by_key(|&i| d(line.p[i])).unwrap_or(0) + }) +} + +/// A graph point: its position, the arms of the level, the round radius in metres, and its face's +/// label and key. +struct Point { + pos: P, + arms: Vec, + /// Neighbouring arms (as indices into `arms`), the first turning counter-clockwise to the second + /// through their sector, with the radius of their corner in metres. + pairs: Vec<(usize, usize, f64)>, + /// A junction or a joint: its arms belong to its face up to their seams. + seams: bool, + label: Label, + key: (u8, u8, u8), + glob: Glob, +} + +/// The key of a way's carriageway or rail bed candidate. +fn way_key(rules: &Rules, line: &WayLine) -> (u8, u8, u8) { + (way_label(rules, line, 0).1, line.sec.rank as u8, 3) +} + +fn way_label(rules: &Rules, line: &WayLine, leg: u8) -> (Label, u8) { + let (rank, surface) = match (line.sec.water, line.rail) { + (true, _) => (Rank::WaterLine, Surface::Water), + (false, true) => (Rank::RailBed, Surface::RailBed), + (false, false) => (Rank::Carriageway, Surface::Carriageway), + }; + let rank = rules.plan.rank(rank); + let label = Label { + owner: Owner::Way(line.way), + surface, + rule: HeightRule::Owner, + material: Some(line.way), + crossing: None, + rank, + reach_m: line.sec.reach_m as f32, + legs: [leg, 0], + }; + (label, rank) +} + +/// The samples where a line's stroke turns tighter than the inner radius `r[i]` (units) on its inner +/// edge: the edge at the half-width on the side the line turns to, with a concave corner at each +/// sample that turns that way. Corners with no turn the other way between them form one corner where +/// their rounds of radius r would overlap or where they lie less than `support` units apart along the +/// edge, as the kink check groups them. A corner's length along the edge is the centre line's less +/// the half-width's share of each turn: an edge that folds over a turn tighter than the half-width +/// has none. A corner whose length (at least `support`) over its summed turn is under r gets a round +/// at its sharpest sample. +fn turns(line: &WayLine, r: &[f64], support: f64) -> Vec { + let n = line.p.len(); + let mut s = vec![0.0; n]; + for i in 1..n { + let (a, b) = (line.p[i - 1], line.p[i]); + let (dx, dy) = (f64::from(b[0] - a[0]), f64::from(b[1] - a[1])); + s[i] = s[i - 1] + (dx * dx + dy * dy).sqrt(); + } + // The signed turn at each sample, toward the left normal positive. + let turn: Vec = (0..n) + .map(|i| { + let (Some(u), Some(v)) = ( + i.checked_sub(1).and_then(|h| stroke::unit(line.p[h], line.p[i])), + line.p.get(i + 1).and_then(|&q| stroke::unit(line.p[i], q)), + ) else { + return 0.0; + }; + libm::atan2(u[0] * v[1] - u[1] * v[0], u[0] * v[0] + u[1] * v[1]) + }) + .collect(); + let mut out = Vec::new(); + for side in [1.0, -1.0] { + let t = |k: usize| (side * turn[k]).max(0.0); + // The edge a corner takes from each side, and the reach of its round along the edge. + let cut = |k: usize| line.h[k] * libm::tan(t(k) / 2.0); + let reach = |k: usize| r[k] * libm::tan(t(k) / 2.0); + let mut i = 1; + while i + 1 < n { + if t(i) == 0.0 { + i += 1; + continue; + } + let (mut sum, mut length, mut last, mut sharpest) = (t(i), 0.0, i, i); + while last + 2 < n && t(last + 1) > 0.0 { + let j = last + 1; + let gap = s[j] - s[last] - cut(last) - cut(j); + if gap >= support.max(reach(last) + reach(j)) { + break; + } + (sum, length, last) = (sum + t(j), length + gap, j); + if t(j) > t(sharpest) { + sharpest = j; + } + } + if length.max(support) / sum < r[sharpest] { + out.push(sharpest); + } + i = last + 1; + } + } + out.sort_unstable(); + out +} + +/// Whether an arm's first segment has a sidewalk on its right, seen from the point, else on its left. +fn sidewalk(line: &WayLine, arm: Arm, right: bool) -> bool { + let seg = if arm.dir > 0 { Some(arm.at) } else { arm.at.checked_sub(1) }; + let bit = if (arm.dir > 0) == right { 2 } else { 1 }; + seg.is_some_and(|s| s + 1 < line.walk.len() && line.walk[s] & bit != 0) +} + +/// The junctions and joints whose faces reach the window. A junction with an arm that goes on at another level +/// (`elsewhere`) is no point of this level: each of its arms here ends there, open (`deck::Decks`), as at a joint. +fn graph_points( + ctx: &Ctx, + lines: &[WayLine], + of_way: &BTreeMap, + elsewhere: &dyn Fn(u32) -> bool, + bx: [i32; 4], +) -> Vec { + let g = ctx.graph; + let near = |p: P| p[0] >= bx[0] && p[0] <= bx[2] && p[1] >= bx[1] && p[1] <= bx[3]; + let mut out = Vec::new(); + let class = |l: usize| lines[l].sec.rank as u8; + for (id, j) in g.junctions.iter().enumerate() { + let arms: Vec<(&crate::graph::Arm, usize)> = + j.arms.iter().filter_map(|a| of_way.get(&a.way).map(|&l| (a, l))).collect(); + if arms.len() < 2 || !near(j.pos) || j.arms.iter().any(|a| elsewhere(a.way)) { + continue; + } + // The material: the arm of the best class, a road or path before a rail, a host before a guest. + let rail = arms.iter().all(|(_, l)| lines[*l].rail); + let best = arms.iter().min_by_key(|(a, l)| (lines[*l].rail != rail, class(*l), !a.host, a.way)).unwrap(); + let at = sample_at(g, &lines[best.1], &best.0.at, j.pos); + let (mut label, rank) = way_label(ctx.rules, &lines[best.1], legs::leg(&lines[best.1].cuts, at, best.0.dir)); + label.owner = Owner::Junction(id as u32); + label.rule = HeightRule::Blend; + let pts: Vec = arms + .iter() + .map(|(a, l)| Arm { line: *l, at: sample_at(g, &lines[*l], &a.at, j.pos), dir: a.dir }) + .collect(); + // Each two neighbouring arms, the first turning counter-clockwise to the second through their + // sector, so that the sector lies on the first's right and the second's left. Their corner + // takes the lesser radius of their classes, the sidewalk one where either has a sidewalk there. + let pairs = (0..pts.len()) + .map(|k| { + let (a, b) = (pts[k], pts[(k + 1) % pts.len()]); + let walk = sidewalk(&lines[a.line], a, true) || sidewalk(&lines[b.line], b, false); + let radius = |l: usize| { + let sec = &lines[l].sec; + if walk { + sec.corner_radius_walk_m + } else { + sec.corner_radius_m + } + }; + (k, (k + 1) % pts.len(), radius(a.line).min(radius(b.line))) + }) + .collect(); + let gp = ctx.global(j.pos); + out.push(Point { + pos: j.pos, + arms: pts, + pairs, + seams: true, + label, + key: (rank, class(best.1), 0), + glob: [gp[0], gp[1], 0, 0, 0], + }); + } + for j in &g.joints { + let (Some(&la), Some(&lb)) = (of_way.get(&j.arms[0].way), of_way.get(&j.arms[1].way)) else { continue }; + if !near(j.pos) || j.arms[0].level != j.arms[1].level { + continue; + } + let at = [sample_at(g, &lines[la], &j.arms[0].at, j.pos), sample_at(g, &lines[lb], &j.arms[1].at, j.pos)]; + // The face takes the label of the lesser key at the joint. + let ka = (class(la), lines[la].key[at[0]]); + let kb = (class(lb), lines[lb].key[at[1]]); + let (owner, k) = if ka <= kb { (la, 0) } else { (lb, 1) }; + let (label, rank) = way_label(ctx.rules, &lines[owner], legs::leg(&lines[owner].cuts, at[k], j.arms[k].dir)); + let radius = lines[la].sec.inner_radius_m.min(lines[lb].sec.inner_radius_m); + let gp = ctx.global(j.pos); + out.push(Point { + pos: j.pos, + arms: vec![ + Arm { line: la, at: at[0], dir: j.arms[0].dir }, + Arm { line: lb, at: at[1], dir: j.arms[1].dir }, + ], + pairs: vec![(0, 1, radius), (1, 0, radius)], + seams: true, + label, + key: (rank, class(owner), 1), + glob: [gp[0], gp[1], 0, 0, 0], + }); + } + out +} + +/// The tight turns of single ways whose faces reach the window, except at a sample on a part of a +/// junction's or joint's region (`taken`, per line): that point's rounds shape it. +fn turn_points(ctx: &Ctx, lines: &[WayLine], taken: &[Vec<(f64, f64)>], bx: [i32; 4]) -> Vec { + let near = |p: P| p[0] >= bx[0] && p[0] <= bx[2] && p[1] >= bx[1] && p[1] <= bx[3]; + let mut out = Vec::new(); + for (li, line) in lines.iter().enumerate() { + let r_m = line.sec.inner_radius_m; + if r_m <= 0.0 || line.rail { + continue; + } + let r: Vec = line.p.iter().map(|&p| ctx.units(r_m, p)).collect(); + for i in turns(line, &r, ctx.units(check::SUPPORT_M, line.p[0])) { + if !near(line.p[i]) || taken[li].iter().any(|&(lo, hi)| (lo..=hi).contains(&(i as f64))) { + continue; + } + let (label, rank) = way_label(ctx.rules, line, legs::leg(&line.cuts, i, -1)); + out.push(Point { + pos: line.p[i], + arms: vec![Arm { line: li, at: i, dir: 1 }, Arm { line: li, at: i, dir: -1 }], + pairs: vec![(0, 1, r_m)], + seams: false, + label, + key: (rank, line.sec.rank as u8, 2), + glob: { + let gp = ctx.global(line.p[i]); + [gp[0], gp[1], 0, 0, 0] + }, + }); + } + } + out +} + +/// A vertex less than 2 units off a cell line moves onto it: the overlay's 1-unit snap then cannot +/// bend the cell line toward a vertex beside it. +fn snap(p: P) -> P { + let c = CELL_UNITS as i32; + let snap = |v: i32| { + let m = v.rem_euclid(c); + if m != 0 && m < 2 { + v - m + } else if m != 0 && c - m < 2 { + v + (c - m) + } else { + v + } + }; + [snap(p[0]), snap(p[1])] +} + +/// Each ring's vertices snapped to the cell lines, with a vertex where it crosses one. +fn prepare(rings: &Rings) -> Rings { + rings + .iter() + .map(|r| { + let mut s: Vec

= r.iter().map(|&p| snap(p)).collect(); + s.dedup(); + if s.len() > 1 && s[0] == s[s.len() - 1] { + s.pop(); + } + with_grid_lines(&s, CELL_UNITS) + }) + .filter(|r| r.len() >= 3) + .collect() +} + +/// Crossings of a cell line closer than this many units along it are one point. +const MERGE: i32 = 4; + +/// The crossings of the cell's lines by candidate edges and seams, closer than `MERGE` units along +/// a line, move to one point: a cell corner in the run, else its least. Two edges that cross each other +/// beside a cell line then cross on it, so no cell holds a sliver of their wedge that the next cell +/// sees as a whole patch. +fn merge_crossings(square: [i32; 4], rings: &mut [&mut Rings], seams: &mut Vec<[P; 2]>) { + let c = CELL_UNITS as i32; + for axis in 0..2 { + for line in [square[axis], square[axis + 2]] { + let on = |p: &P| p[axis] == line; + let mut along: Vec = (rings.iter().flat_map(|r| r.iter().flatten())) + .chain(seams.iter().flatten()) + .filter(|p| on(p)) + .map(|p| p[1 - axis]) + .collect(); + along.sort_unstable(); + along.dedup(); + let mut to: BTreeMap = BTreeMap::new(); + let mut start = 0; + for k in 1..=along.len() { + if k < along.len() && along[k] - along[k - 1] < MERGE { + continue; + } + let run = &along[start..k]; + if run.len() > 1 { + let target = run.iter().copied().find(|v| v.rem_euclid(c) == 0).unwrap_or(run[0]); + to.extend(run.iter().map(|&v| (v, target))); + } + start = k; + } + if to.is_empty() { + continue; + } + let shift = |p: &mut P| { + if on(p) { + if let Some(&v) = to.get(&p[1 - axis]) { + p[1 - axis] = v; + } + } + }; + for ring in rings.iter_mut().flat_map(|r| r.iter_mut()) { + ring.iter_mut().for_each(shift); + ring.dedup(); + while ring.len() > 1 && ring.first() == ring.last() { + ring.pop(); + } + } + seams.iter_mut().flatten().for_each(shift); + } + } + for r in rings.iter_mut() { + r.retain(|ring| ring.len() >= 3); + } + seams.retain(|s| s[0] != s[1]); +} + +/// The box within which `candidates` reads a reach of `m` metres past the cell: with `records`, +/// `records::MARGIN_M` and a unit more. +fn grown(cell: CellKey, m: f64, records: bool) -> [i32; 4] { + let (margin, unit) = if records { (records::MARGIN_M, 1) } else { (0.0, 0) }; + let w = window(cell, m + margin); + [w[0] - unit, w[1] - unit, w[2] + unit, w[3] + unit] +} + +/// The way lines of a cell's records: the prefix of the lines of `candidates` with `records`, on the +/// ground level, that holds no water. +pub(crate) fn record_lines<'a>( + graph: &'a WayGraph, + input: &CellInput, + rules: &'a Rules, + cell: CellKey, +) -> Vec> { + let ctx = Ctx { graph, rules, origin: cell.origin() }; + let mut lines = + lines(&ctx, input, &|w| in_level(graph, w), grown(cell, rules::ways_m(&rules.plan, &rules.sections), true)).0; + lines.retain(|l| !l.sec.water); + lines +} + +/// The ceiling lines of a cell's records: its deck ways whose ceiling reaches a bin of the cell (at most +/// `records::ceiling_end_reach` from the centre line), each one leg, with the half-width of the deck's stroke: its +/// paved layers' and `edge_band_m`. +pub(crate) fn ceiling_lines<'a>( + graph: &'a WayGraph, + input: &CellInput, + rules: &'a Rules, + cell: CellKey, +) -> Vec> { + let ctx = Ctx { graph, rules, origin: cell.origin() }; + let half = HALF_MAX_M + rules.structures.edge_band_m; + let m = records::ceiling_end_reach(half, rules.plan.heights.ceiling_release_m) + records::HEIGHT_PAD_M; + let mut out = lines(&ctx, input, &|w| on_deck(graph, w), grown(cell, m, true)).0; + for line in &mut out { + line.cuts.clear(); + line.spans.clear(); + for i in 0..line.p.len() { + line.h[i] = line.bands[i][VERGE] + ctx.units(rules.structures.edge_band_m, line.p[i]); + } + } + out +} + +/// The lines of a cell's level whose faces reach its window: within `input_m`. +pub(crate) fn level_lines<'a>( + graph: &'a WayGraph, + input: &CellInput, + rules: &'a Rules, + cell: CellKey, + level: i8, +) -> Vec> { + let ctx = Ctx { graph, rules, origin: cell.origin() }; + let decks = (STOREYS && level > 0).then(|| deck::Decks::of(graph, input)); + let mut out = + lines(&ctx, input, &keep(graph, decks.as_ref(), level), window(cell, input_m(&rules.plan, &rules.sections))).0; + if STOREYS && decks.is_some() { + for line in &mut out { + deck::deck_bands(line, &|p| ctx.units(rules.structures.edge_band_m, p)); + } + } + out +} + +/// The candidates of a cell and level, the one source of its shapes: the overlay slices and labels +/// them into faces, and the records evaluate them per point by the same `decide`. +struct Candidates<'a> { + lines: Vec>, + /// The way lines: a prefix of `lines`, which the far level reads. + ways: usize, + cands: Vec, + seams: Vec<[P; 2]>, + win: [i32; 4], + cover: Cover, + corners: Vec, + mouths: Vec, + /// The end lines on which storey 0 and a deck meet: the end point, the unit direction into the line and the + /// half-width of its stroke there (units). A face edge on one is a `DeckEdge`. + ends: Vec<[f64; 5]>, + stats: FaceStats, +} + +/// The face plan of one cell and level. `slopes = false` leaves out storey 0's slope layer; a storey over the +/// ground holds its decks' edge band there. +pub fn build(graph: &WayGraph, input: &CellInput, rules: &Rules, cell: CellKey, level: i8, slopes: bool) -> FacePlan { + let c = candidates(graph, input, rules, cell, level, if slopes || level > 0 { LAYERS } else { SLOPE }, false); + Sliced::new(&c).cell(&c, cell, level) +} + +/// The slice's window: the cell grown by one tile. Every neighbour's slice cuts on the tile's sides +/// too, so near the cell both cut alike, and the window's frame lies far from the cell. +const GROW: i32 = slice::TILE as i32; + +/// One slice of the candidates' window by all their outlines, a label per patch. +struct Sliced { + patches: Vec>>, + labels: Vec

], f64)> = + own.into_iter().chain(far.iter().map(|&j| (rounded[j].fans.as_slice(), -1.0))).collect(); + points::grow(cut, &fans) + }; + for &j in std::iter::once(&i).chain(&far) { + points::replace_cut(&mut rounded[j], cut, grown); + } + if let Some(j) = other { + beyond[i].push((grown, points[j].label)); + } + for &j in &far { + beyond[j].push(([grown[1], grown[0]], points[i].label)); + } + let key = (l, [snap(grown[0].min(grown[1])), snap(grown[0].max(grown[1]))]); + seam_points.insert(key, std::iter::once(i).chain(far).collect()); + } + } + let mut cands: Vec = Vec::new(); + let mut mouths = Vec::new(); + // The ways' carriageways and the band layers, on the run of samples near the window. A way with + // legs keeps its own layers of the owner rule (its shoulders): `split_legs` gives each piece in a + // leg's near zone that leg's line as its host, as for the carriageway. + let mut layers: [Vec>; LAYERS] = Default::default(); + let mut own_layers: BTreeMap>; LAYERS]> = BTreeMap::new(); + // The carriageways on the runs that only the outline rounds read. + let mut outer_paved: Vec> = Vec::new(); + for (li, line) in lines.iter().enumerate() { + // The samples of the segments that meet a box. + let run = |bx: [i32; 4]| { + let meets = |i: &usize| geom::meets(bx, line.p[*i], line.p[i + 1]); + let n = line.p.len() - 1; + Some(((0..n).find(meets)?, (0..n).rfind(meets)? + 2)) + }; + // The cuts at the first and the last sample of layer k (0 the carriageway). + let cut = |i: usize, k: usize| end_cuts.get(&(li, i)).cloned().unwrap_or_else(|| line.offsets(i)[..k].to_vec()); + let carriageway = |(first, last): (usize, usize)| { + let ends = [line.round[0] && first == 0, line.round[1] && last == line.p.len()]; + let mut own = Vec::new(); + let (p, h) = (&line.p[first..last], &line.h[first..last]); + pieces_along(p, h, &[], [&cut(first, 0), &cut(last - 1, 0)], ends, false, &mut own); + own + }; + // The paved outline holds no water. + let outer = if line.sec.water { None } else { run(lx) }; + let Some((first, last)) = run(bx) else { + outer_paved.extend(outer.map(|r| prepare(&union(&carriageway(r), [0, 0]))).unwrap_or_default()); + continue; + }; + if outer != Some((first, last)) { + outer_paved.extend(outer.map(|r| prepare(&union(&carriageway(r), [0, 0]))).unwrap_or_default()); + } + let ends = [line.round[0] && first == 0, line.round[1] && last == line.p.len()]; + let p = &line.p[first..last]; + let own = carriageway((first, last)); + cands.push(Cand { + rings: union(&own, [0, 0]), + label: way_label(rules, line, legs::leg(&line.cuts, first, 1)).0, + key: way_key(rules, line), + glob: None, + line: li, + relabel: None, + beyond: Vec::new(), + fill: None, + discs: Vec::new(), + }); + // A deck's band layers are its own: the slab's edge band names its way. + let mut own = (!line.cuts.is_empty() || decks.is_some()).then(|| own_layers.entry(li).or_default()); + // At a deck end the slope takes the round end of a free end, so its bank runs round the end: the + // paved layers end square on the end line. + let deck = [line.deck[0] && first == 0, line.deck[1] && last == line.p.len()]; + for k in 0..bands { + let inner = |i: usize| if k == 0 { line.h[i] } else { line.bands[i][k - 1] }; + let d: Vec = (first..last).map(|i| line.bands[i][k]).collect(); + if (first..last).all(|i| line.bands[i][k] <= inner(i)) { + continue; + } + let cuts = [&cut(first, k + 1)[..], &cut(last - 1, k + 1)[..]]; + let layer = match own.as_deref_mut() { + Some(own) if decks.is_some() || BAND_LABELS[k].2 == HeightRule::Owner => &mut own[k], + _ => &mut layers[k], + }; + let ends = if k == SLOPE { [ends[0] || deck[0], ends[1] || deck[1]] } else { ends }; + pieces_along(p, &d, &[], cuts, ends, false, layer); + } + } + stats.ways = lines.len() as u32; + if level == 0 { + cands.extend(platform::candidates(&ctx, input, bx, &mut stats)); + // A culvert's zone lies within `REACH_M` of its crossing. + let (zones, found) = culverts::candidates(&ctx, &lines, reach(culverts::REACH_M)); + cands.extend(zones); + mouths = found; + } + // The points' fans and regions, and the band fans. + let mut fan_of: Vec> = vec![None; points.len()]; + for (i, (pt, r)) in points.iter().zip(&rounded).enumerate() { + let glob = Some(pt.glob); + if !r.fans.is_empty() { + fan_of[i] = Some(cands.len()); + cands.push(Cand { + rings: union(&r.fans, pt.pos), + label: pt.label, + // A round paves land only: its fan loses to every carriageway and rail bed, so it + // never lies over another way, and its arms' carriageways reach the point's face + // through its region. + key: (plan.rank(Rank::RailBed), pt.key.1, pt.key.2), + glob, + line: 0, + relabel: None, + beyond: std::mem::take(&mut beyond[i]), + fill: None, + discs: r.circles.iter().filter(|c| c.radius > 0.0).cloned().collect(), + }); + } + if !r.region.is_empty() { + let rings = union(&r.region, pt.pos); + let spans = Some(r.spans.clone()); + let beyond = Vec::new(); + let (key, discs) = (pt.key, Vec::new()); + cands.push(Cand { rings, label: pt.label, key, glob, line: 0, relabel: spans, beyond, fill: None, discs }); + } + // A point's rings belong to the one way with legs among its arms, if there is one; on a deck, to the way + // of its label. + let mut legged: Vec = pt.arms.iter().map(|a| a.line).filter(|&l| !lines[l].cuts.is_empty()).collect(); + legged.sort_unstable(); + legged.dedup(); + let deck_owner = pt.label.material.and_then(|m| of_way.get(&m).copied()).filter(|_| STOREYS && decks.is_some()); + for k in 0..bands { + let layer = match (deck_owner, &legged[..]) { + (Some(l), _) => &mut own_layers.entry(l).or_default()[k], + (None, [l]) if BAND_LABELS[k].2 == HeightRule::Owner => &mut own_layers.entry(*l).or_default()[k], + _ => &mut layers[k], + }; + layer.extend(r.rings[k].iter().cloned()); + } + } + // A way's own band layers win over the others where they overlap: the way's shoulder is its own. + let owned = own_layers.iter().flat_map(|(&l, layers)| layers.iter().enumerate().map(move |(k, r)| (Some(l), k, r))); + for (line, k, layer) in layers.iter().enumerate().map(|(k, r)| (None, k, r)).chain(owned) { + if layer.is_empty() { + continue; + } + let (rank, surface, rule) = band_label(k, STOREYS && decks.is_some()); + let rank = plan.rank(rank); + let material = line.map(|l| lines[l].way); + let label = Label { rank, surface, rule, material, ..TERRAIN }; + cands.push(Cand { + rings: union(layer, [0, 0]), + label, + key: (rank, u8::from(line.is_none()), 0), + glob: Some([0; 5]), + line: line.unwrap_or(0), + relabel: None, + beyond: Vec::new(), + fill: None, + discs: Vec::new(), + }); + } + for c in &mut cands { + c.rings = prepare(&c.rings); + } + let pieces = split_legs(&ctx, &lines, &of_way, &mut cands); + // The rounds at the corners of the paved outline that no point's round shapes. Their key loses + // to every carriageway and rail bed, so a round paves land only. `lines_m` holds their reach. + let mut paved: Vec> = (cands.iter()) + .filter(|c| c.relabel.is_none() && matches!(c.label.surface, Surface::Carriageway | Surface::RailBed)) + .flat_map(|c| c.rings.iter().cloned()) + .collect(); + paved.extend(outer_paved); + let circles: Vec<(P, f64)> = rounded.iter().flat_map(|r| r.circles.iter().map(|c| (c.centre, c.radius))).collect(); + let r_max = rules::inner_max_m(&rules.sections); + let near_win = reach(0.0); + let beyond = |p: P| { + let w = near_win; + let d = (w[0] - p[0]).max(p[0] - w[2]).max(w[1] - p[1]).max(p[1] - w[3]).max(0); + f64::from(d) * metres_per_unit(ctx.origin.y + i64::from(p[1])) + }; + let units = |m: f64, p: P| ctx.units(m, p); + let fills = outline::rounds(&union(&paved, [0, 0]), &lines, &circles, &beyond, &units, plan.extent_m / 2.0, r_max); + let fill_key = (plan.rank(Rank::RailBed), u8::MAX, u8::MAX); + for (k, &(rank, surface, rule)) in BAND_LABELS.iter().enumerate() { + let rings: Vec> = fills.iter().flat_map(|f| f.bands[k].iter().cloned()).collect(); + // A deck's band layers are its ways' own: a round's shared band would name no way. + if rings.is_empty() || k >= bands || (STOREYS && decks.is_some()) { + continue; + } + let rank = plan.rank(rank); + let label = Label { rank, surface, rule, ..TERRAIN }; + let (rings, glob, beyond) = (prepare(&rings), Some([0; 5]), Vec::new()); + let (key, discs) = ((rank, 1, 0), Vec::new()); + cands.push(Cand { rings, label, key, glob, line: 0, relabel: None, beyond, fill: None, discs }); + } + for f in &fills { + let gc = ctx.global(f.circle.centre); + cands.push(Cand { + rings: prepare(&vec![f.ring.clone()]), + label: TERRAIN, + key: fill_key, + glob: Some([gc[0], gc[1], 0, 0, 0]), + line: 0, + relabel: None, + beyond: Vec::new(), + fill: Some(f.inside), + discs: vec![f.circle.clone()], + }); + } + // Each seam cuts its line's carriageway and the fans that reach across it. + let mut seams: Vec<(usize, [P; 2], Vec)> = (seam_points.into_iter()) + .map(|((l, s), pts)| (l, s, pts.iter().filter_map(|&p| fan_of[p]).flat_map(|c| pieces[c].clone()).collect())) + .collect(); + // A seam off the window cuts nothing of it. + seams.retain(|&(_, [a, b], _)| geom::meets(win, a, b)); + let seams = seams_on_carriageways(&mut cands, &seams); + // The seams and rings split at grid lines of `step`, as `grid_points` puts their points. + let split = |seams: &[[P; 2]], step: i64| -> Vec<[P; 2]> { + (seams.iter()) + .flat_map(|&[a, b]| { + let mut pts = vec![a]; + grid_points(a, b, step, &mut pts); + pts.push(b); + pts.dedup(); + pts.windows(2).map(|w| [w[0], w[1]]).collect::>() + }) + .collect() + }; + // A seam meets the cell lines where the carriageway's ring does. + let mut seams = split(&seams, CELL_UNITS); + let square = window(cell, 0.0); + merge_crossings(square, &mut cands.iter_mut().map(|c| &mut c.rings).collect::>(), &mut seams); + cands.retain(|c| !c.rings.is_empty()); + // The last change of the rings and seams: a vertex at each tile line they cross. No tile of the slice + // then rounds a crossing of its own side, which the overlay would snap onto a tile corner that the + // next cell holds without the ring, and the cover and the labels read the edges that the slice cuts. + for c in &mut cands { + c.rings = c.rings.iter().map(|r| with_grid_lines(r, slice::TILE)).collect(); + } + let seams = split(&seams, slice::TILE); + stats.candidates = cands.len() as u32; + let rings: Vec<&[Vec

]> = cands.iter().map(|c| c.rings.as_slice()).collect(); + let cover = Cover::new(win, &rings); + for k in 0..cands.len() { + if let Some(q) = cands[k].fill { + let at: Vec = cover.at(q).into_iter().filter(|&c| cands[c as usize].fill.is_none()).collect(); + cands[k].label = decide(&cands, &lines, at, q); + } + } + let mpu = |p: P| metres_per_unit(ctx.origin.y + i64::from(p[1])); + let mut corners: Vec = (points.iter().zip(&rounded)) + .filter(|(pt, _)| own(pt.pos)) + .flat_map(|(pt, r)| r.circles.iter().map(|c| CornerArc::new(pt.label.owner, c, mpu(c.centre)))) + .collect(); + let fill_label = |f: &outline::Fill| cands.iter().find(|c| c.fill == Some(f.inside)).map(|c| c.label); + for f in &fills { + if let Some(l) = fill_label(f).filter(|l| l.surface != Surface::Terrain) { + corners.push(CornerArc::new(l.owner, &f.circle, mpu(f.circle.centre))); + } + } + let ways = lines.iter().take_while(|l| !l.sec.water).count(); + let ends: Vec<[f64; 5]> = match &decks { + Some(d) => lines.iter().flat_map(|l| deck::open_ends(l, d.open[l.way as usize])).collect(), + None => lines.iter().flat_map(deck_ends).collect(), + }; + Candidates { lines, ways, cands, seams, win, cover, corners, mouths, ends, stats } +} + +/// Splits every candidate that gives the label of a way with legs (`legs`), or that is one of its own +/// band layers: the medial lines between its legs cut it, each piece goes to its nearest leg, whose line +/// is its host, and each leg's part is the union of its pieces, which share their vertices. Where two +/// legs overlap, the nearest one owns the ground, and the step between them stands on the medial line +/// (blended where they agree). A candidate keeps its place with its first leg's part; the others go to +/// the end. Returns per candidate the places of its parts. +fn split_legs(ctx: &Ctx, lines: &[WayLine], of_way: &BTreeMap, cands: &mut Vec) -> Vec> { + let mut parts: Vec> = (0..cands.len()).map(|c| vec![c]).collect(); + // Per line, its legs, the medial lines between them, the near zone of each leg (`Legs::runs`), and + // the medial lines with the zones' edges. + type Cuts = (legs::Legs, Vec<[P; 2]>, Vec, Vec<[P; 2]>); + let mut legs_of: Vec> = (0..lines.len()).map(|_| None).collect(); + for c in 0..parts.len() { + let w = match cands[c].label { + Label { owner: Owner::Way(w), .. } | Label { owner: Owner::Terrain, material: Some(w), .. } => w, + _ => continue, + }; + let Some(&l) = of_way.get(&w).filter(|&&l| !lines[l].cuts.is_empty()) else { continue }; + if cands[c].relabel.is_some() { + continue; + } + let line = &lines[l]; + // The origin of the integer cuts and unions only: they do not depend on it. + let anchor = line.p[line.cuts[0]]; + let (legs, medial, zones, edges) = legs_of[l].get_or_insert_with(|| { + let legs = legs::Legs::new(&line.p, &line.cuts, &|o| ctx.units(line.leg_reach_m(), o)); + let medial = legs.medial(&|o| ctx.units(LEG_STEP_M, o)); + // A leg's near zone: its stretches' strokes, as wide as its reach, with round ends, so the + // zones of two legs leave no gap about their cut. + let mut strokes = vec![Vec::new(); line.cuts.len() + 1]; + for (k, run, r) in legs.runs() { + stroke::pieces_along(&run, &vec![r; run.len()], &[], [&[], &[]], [true, true], false, &mut strokes[k]); + } + let zones: Vec = strokes.iter().map(|s| prepare(&union(s, anchor))).collect(); + let mut edges = medial.clone(); + for r in zones.iter().flatten() { + edges.extend((0..r.len()).map(|i| [r[i], r[(i + 1) % r.len()]])); + } + (legs, medial, zones, edges) + }); + // A band also splits at the edge of the near zone: its pieces in the zone take their nearest + // leg's line as their host, and any piece outside stays plain, so its label does not depend on a + // cut that another cell may not see. + let band = cands[c].label.owner == Owner::Terrain; + let label = cands[c].label; + let mut by_label: Vec<(Label, Rings)> = Vec::new(); + for piece in stroke::cut(&cands[c].rings, if band { edges } else { medial }, anchor) { + let q = inner_point(&piece).unwrap_or_else(|| { + let n = piece[0].len() as i64; + let sum = piece[0].iter().fold([0i64; 2], |s, p| [s[0] + i64::from(p[0]), s[1] + i64::from(p[1])]); + [(2 * sum[0]).div_euclid(n), (2 * sum[1]).div_euclid(n)] + }); + let leg = legs.nearest([q[0] as f64 / 2.0, q[1] as f64 / 2.0]); + let part = match band && zones.iter().all(|z| geom::winding(z, q) == 0) { + true => Label { material: None, ..label }, + false => Label { legs: [leg, label.legs[1]], ..label }, + }; + match by_label.iter_mut().find(|(l, _)| *l == part) { + Some((_, rings)) => rings.extend(piece), + None => by_label.push((part, piece)), + } + } + if by_label.len() < 2 { + cands[c].label = by_label.first().map_or(label, |s| s.0); + continue; + } + let split: Vec<(Label, Rings)> = + by_label.into_iter().map(|(l, rings)| (l, prepare(&union(&rings, anchor)))).collect(); + for (k, (part_label, rings)) in split.into_iter().enumerate() { + let o = &cands[c]; + let part = Cand { + rings, + label: part_label, + key: o.key, + glob: o.glob, + line: o.line, + relabel: None, + beyond: o.beyond.clone(), + fill: o.fill, + discs: o.discs.clone(), + }; + if k == 0 { + cands[c] = part; + } else { + parts[c].push(cands.len()); + cands.push(part); + } + } + } + parts +} + +/// The label of each band layer (`LAYERS`). A way with legs keeps its layers of the owner rule as its +/// own, and the nearest leg hosts each of their pieces (`split_legs`). +const BAND_LABELS: [(Rank, Surface, HeightRule); LAYERS] = [ + (Rank::ShoulderPaved, Surface::Shoulder, HeightRule::Owner), + (Rank::Shoulder, Surface::Shoulder, HeightRule::Owner), + (Rank::Verge, Surface::Verge, HeightRule::Slope), + (Rank::Bank, Surface::Bank, HeightRule::Slope), + (Rank::Slope, Surface::Slope, HeightRule::Slope), +]; + +/// The label of band layer k; on a deck, the slope's place holds the deck's edge band, of the sheet's lowest rank, +/// at its way's height. +fn band_label(k: usize, deck: bool) -> (Rank, Surface, HeightRule) { + if deck && k == SLOPE { + (Rank::Slope, Surface::DeckEdge, HeightRule::Owner) + } else { + BAND_LABELS[k] + } +} + +/// The step of a medial line between two legs along a leg. +const LEG_STEP_M: f64 = 0.5; + +/// The global name of a way's leg near a point (doubled): the key of its sample nearest the point. +fn way_glob(line: &WayLine, leg: u8, q: [i64; 2]) -> Glob { + let (lo, hi) = legs::range(&line.cuts, line.p.len(), leg); + let d = |p: P| (2 * i64::from(p[0]) - q[0]).pow(2) + (2 * i64::from(p[1]) - q[1]).pow(2); + let i = (lo..=hi).min_by_key(|&i| (d(line.p[i]), i)).unwrap_or(lo); + line.key[i] +} + +/// A crossing of a seam's line by a ring: its fraction along the seam, the candidate (as an index +/// into the seam's list), ring and segment, its place along the segment in millionths, and +1 where +/// the line enters the candidate, −1 where it leaves. +type Crossing = (f64, usize, usize, usize, i64, i32); + +/// Each seam as a cut of the paved outline it splits: its way's carriageway and the fans that reach +/// across it, from edge to edge of their union about the seam's middle. Each crossing of a ring on +/// the way becomes a vertex of that ring, so the cut ends on an edge of the slice: past it a cut +/// would only split one face and leave a slit, and an edge that a cut crosses between its vertices +/// would bend by a unit there. A seam along an edge of the carriageway (a square end of the way) is +/// that edge already. A seam whose union runs past an end keeps that end. +fn seams_on_carriageways(cands: &mut [Cand], seams: &[(usize, [P; 2], Vec)]) -> Vec<[P; 2]> { + // Per (candidate, ring, segment): the points to insert, by their place along the segment. + let mut inserts: BTreeMap<(usize, usize, usize), Vec<(i64, P)>> = BTreeMap::new(); + let mut out = Vec::with_capacity(seams.len()); + for (l, [a, b], fans) in seams { + let (a, b) = (*a, *b); + // The way's carriageway: one candidate per leg. + let ways: Vec = (0..cands.len()) + .filter(|&c| cands[c].relabel.is_none() && cands[c].glob.is_none() && cands[c].line == *l) + .collect(); + if ways.is_empty() { + out.push([a, b]); + continue; + } + let (fa, fb) = ([f64::from(a[0]), f64::from(a[1])], [f64::from(b[0]), f64::from(b[1])]); + let r = [fb[0] - fa[0], fb[1] - fa[1]]; + let len = (r[0] * r[0] + r[1] * r[1]).sqrt(); + if len == 0.0 { + continue; + } + let off = |x: [f64; 2]| ((x[0] - fa[0]) * r[1] - (x[1] - fa[1]) * r[0]).abs() / len; + let along = |x: [f64; 2]| ((x[0] - fa[0]) * r[0] + (x[1] - fa[1]) * r[1]) / (len * len); + let on_edge = ways.iter().flat_map(|&ci| &cands[ci].rings).any(|ring| { + (0..ring.len()).any(|si| { + let (p, q) = (ring[si], ring[(si + 1) % ring.len()]); + let (fp, fq) = ([f64::from(p[0]), f64::from(p[1])], [f64::from(q[0]), f64::from(q[1])]); + off(fp) <= 1.0 && off(fq) <= 1.0 && along(fp).max(along(fq)) > 0.0 && along(fp).min(along(fq)) < 1.0 + }) + }); + if on_edge { + continue; + } + // The crossings of the whole line, so the windings start at zero; a vertex on the line lies + // on its left. + let set: Vec = ways.iter().chain(fans).copied().collect(); + let left = |p: P| geom::cross(a, b, p) >= 0; + let mut xs: Vec = Vec::new(); + for (slot, &c) in set.iter().enumerate() { + for (ri, ring) in cands[c].rings.iter().enumerate() { + for (si, &p) in ring.iter().enumerate() { + let q = ring[(si + 1) % ring.len()]; + if left(p) == left(q) { + continue; + } + let d = [f64::from(q[0] - p[0]), f64::from(q[1] - p[1])]; + let den = r[0] * d[1] - r[1] * d[0]; + let (x, y) = (f64::from(p[0]) - fa[0], f64::from(p[1]) - fa[1]); + let (t, u) = ((x * d[1] - y * d[0]) / den, (x * r[1] - y * r[0]) / den); + // Rings turn counter-clockwise: the line enters where it crosses an edge from + // the edge's right. + let sign = if den < 0.0 { 1 } else { -1 }; + xs.push((t, slot, ri, si, geom::round(u.clamp(0.0, 1.0) * 1e6), sign)); + } + } + } + xs.sort_by(|x, y| x.0.total_cmp(&y.0).then((x.1, x.2, x.3).cmp(&(y.1, y.2, y.3)))); + // Crossings within half a unit along the line are one: per group, its crossings and the + // count of candidates that cover the line after it. + let mut groups: Vec<(usize, usize, usize)> = Vec::new(); + let mut wind = vec![0i32; set.len()]; + let mut start = 0; + for k in 1..=xs.len() { + if k < xs.len() && (xs[k].0 - xs[start].0) * len < 0.5 { + continue; + } + for x in &xs[start..k] { + wind[x.1] += x.5; + } + groups.push((start, k, wind.iter().filter(|&&w| w != 0).count())); + start = k; + } + let Some(mid) = groups.iter().rposition(|g| xs[g.0].0 <= 0.5).filter(|&g| groups[g].2 > 0) else { + out.push([a, b]); + continue; + }; + let mut lo = mid; + while lo > 0 && groups[lo - 1].2 > 0 { + lo -= 1; + } + let hi = (mid + 1..groups.len()).find(|&g| groups[g].2 == 0); + // The seam runs through one vertex per group of crossings in the union, each a vertex of + // every ring of its group: rings that run together across the seam (two fans' sides on one + // centre line) then meet it at one point, not a unit apart. + let mut pts = Vec::new(); + if xs[groups[lo].0].0 < 0.0 { + pts.push(a); + } + for &(i, j, _) in &groups[lo..=hi.unwrap_or(groups.len() - 1)] { + let t = xs[i].0; + if !(0.0..=1.0).contains(&t) { + continue; + } + // The crossing point; within 2 units of an end of its segment it is that end: a point + // inserted there could fold the ring back. + let (_, slot, ri, si, _, _) = xs[i]; + let ring = &cands[set[slot]].rings[ri]; + let (p, q) = (ring[si], ring[(si + 1) % ring.len()]); + let mut at = [geom::round(fa[0] + t * r[0]) as i32, geom::round(fa[1] + t * r[1]) as i32]; + let d2 = |x: P, y: P| (i64::from(x[0] - y[0])).pow(2) + (i64::from(x[1] - y[1])).pow(2); + if d2(at, p) <= 4 { + at = p; + } else if d2(at, q) <= 4 { + at = q; + } + pts.push(at); + for x in &xs[i..j] { + inserts.entry((set[x.1], x.2, x.3)).or_default().push((x.4, at)); + } + } + if hi.is_none_or(|g| xs[groups[g].0].0 > 1.0) { + pts.push(b); + } + pts.dedup(); + out.extend(pts.windows(2).map(|w| [w[0], w[1]])); + } + // From the last segment of a ring back, so the earlier indices stay valid. + for ((ci, ri, si), mut pts) in inserts.into_iter().rev() { + pts.sort_unstable(); + let ring = &mut cands[ci].rings[ri]; + let (p, q) = (ring[si], ring[(si + 1) % ring.len()]); + let mut add: Vec

= pts.into_iter().map(|(_, x)| x).filter(|&x| x != p && x != q).collect(); + add.dedup(); + ring.splice(si + 1..si + 1, add); + } + out.retain(|s| s[0] != s[1]); + out +} + +/// Whether a doubled point lies past a seam: on the far side of its cut line, exactly as the slice +/// holds it, and within its length. The seam is an edge of the slice, so every patch lies on one +/// side of it. +fn past(cut: &[P; 2], q: [i64; 2]) -> bool { + let (a, b) = (snap(cut[0]), snap(cut[1])); + let (a, b) = ([2 * i128::from(a[0]), 2 * i128::from(a[1])], [2 * i128::from(b[0]), 2 * i128::from(b[1])]); + let (u, v) = ([b[0] - a[0], b[1] - a[1]], [i128::from(q[0]) - a[0], i128::from(q[1]) - a[1]]); + let along = u[0] * v[0] + u[1] * v[1]; + u[0] * v[1] - u[1] * v[0] < 0 && (0..=u[0] * u[0] + u[1] * u[1]).contains(&along) +} + +/// Whether a doubled point lies past one of a part's seams. +fn past_seam(part: &Part, q: [i64; 2]) -> bool { + part.cuts.iter().flatten().any(|cut| past(cut, q)) +} + +/// The label of a patch: the least key among the candidates that cover its inner point, else +/// terrain; a carriageway over a rail bed is a crossing. +/// The label of a patch; `far` leaves out the band layers. +fn label(cands: &[Cand], cover: &Cover, lines: &[WayLine], patch: &[Vec

], far: bool) -> Label { + let mut at = match inner_point(patch) { + Some(q) => cover.at(q), + None => { + let mut all: Vec = + patch[0].iter().flat_map(|p| cover.at([2 * i64::from(p[0]), 2 * i64::from(p[1])])).collect(); + all.sort_unstable(); + all.dedup(); + all + } + }; + if far { + at.retain(|&c| !near_only(&cands[c as usize])); + } + // A patch with no inner point reads its seams at the mean of its vertices: a vertex of it can + // lie on a seam. + let q = inner_point(patch).unwrap_or_else(|| { + let n = patch[0].len() as i64; + let sum = patch[0].iter().fold([0i64; 2], |s, p| [s[0] + i64::from(p[0]), s[1] + i64::from(p[1])]); + [(2 * sum[0]).div_euclid(n), (2 * sum[1]).div_euclid(n)] + }); + let label = decide(cands, lines, at.clone(), q); + if label.surface != Surface::Crossing { + return label; + } + // A carriageway over a rail bed is a crossing where the rail runs through it: its centre line + // enters the patch, or a carriageway covers the centre line's point nearest the patch (a rail in + // a street). Else the two ways only run side by side, and the bed wins. + let bed = (at.iter().map(|&c| &cands[c as usize])) + .filter(|c| c.label.surface == Surface::RailBed && matches!(c.label.owner, Owner::Way(_))) + .min_by_key(|c| c.key); + let Some(bed) = bed else { return label }; + let rail = &lines[bed.line].p; + let ring = &patch[0]; + let (lo, hi) = ring.iter().fold(([i32::MAX; 2], [i32::MIN; 2]), |(lo, hi), p| { + ([lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])]) + }); + let meets = |a: P, b: P| { + a[0].max(b[0]) >= lo[0] && a[0].min(b[0]) <= hi[0] && a[1].max(b[1]) >= lo[1] && a[1].min(b[1]) <= hi[1] + }; + let crosses = |a: P, b: P, c: P, d: P| { + let s = |x: i128| x.signum(); + s(geom::cross(a, b, c)) * s(geom::cross(a, b, d)) < 0 && s(geom::cross(c, d, a)) * s(geom::cross(c, d, b)) < 0 + }; + let enters = rail.windows(2).filter(|w| meets(w[0], w[1])).any(|w| { + geom::winding(patch, [2 * i64::from(w[0][0]), 2 * i64::from(w[0][1])]) != 0 + || (0..ring.len()).any(|i| crosses(w[0], w[1], ring[i], ring[(i + 1) % ring.len()])) + }); + let nearest = rail.windows(2).map(|w| geom::nearest_on(w[0], w[1], q)).min_by_key(|&(d, _)| d).map(|(_, c)| c); + let street = nearest.is_some_and(|c| { + cover.at(c).iter().any(|&k| { + let k = &cands[k as usize]; + k.relabel.is_none() && k.label.surface == Surface::Carriageway + }) + }); + if enters || street { + label + } else { + bed.label + } +} + +/// Whether a label's material way is line water. +fn of_water(lines: &[WayLine], l: &Label) -> bool { + l.material.is_some_and(|m| lines.iter().any(|x| x.way == m && x.sec.water)) +} + +/// The label at a doubled point q that the candidates `at` cover. Where a zone covers q, a candidate of line +/// water does not count: the water ends at the zone. +fn decide(cands: &[Cand], lines: &[WayLine], mut at: Vec, q: [i64; 2]) -> Label { + if at.iter().any(|&c| cands[c as usize].label.surface == Surface::Zone) { + at.retain(|&c| !of_water(lines, &cands[c as usize].label)); + } + let regions: Vec = at.iter().copied().filter(|&c| cands[c as usize].relabel.is_some()).collect(); + at.retain(|&c| cands[c as usize].relabel.is_none()); + let Some(&first) = at.iter().min_by_key(|&&c| cands[c as usize].key) else { return TERRAIN }; + let best = cands[first as usize].key; + at.retain(|&c| cands[c as usize].key == best || cands[c as usize].label.surface == Surface::RailBed); + let glob = |c: &Cand| c.glob.unwrap_or_else(|| way_glob(&lines[c.line], c.label.legs[0], q)); + let win = (at.iter().map(|&c| &cands[c as usize])).filter(|c| c.key == best).min_by_key(|c| glob(c)).unwrap(); + // A round at a corner of the paved outline keeps the label decided at its corner, whole. + if win.fill.is_some() { + return win.label; + } + let mut label = win.label; + let across = win.beyond.iter().find(|(cut, _)| past(cut, q)); + if let Some(&(_, other)) = across { + label = other; + } + // A patch of a way of the point in its region takes the point's label, unless it lies past one + // of the way's seams. A zone keeps itself. + if let (Owner::Way(w), None, false) = (label.owner, across, label.surface == Surface::Zone) { + let of = (regions.iter().map(|&c| &cands[c as usize])) + .filter(|c| { + let mut parts = c.relabel.iter().flatten().filter(|part| lines[part.line].way == w).peekable(); + parts.peek().is_some() && parts.all(|part| !past_seam(part, q)) + }) + .min_by_key(|c| (c.key, glob(c))); + if let Some(region) = of { + label = region.label; + } + } + if label.surface == Surface::Carriageway { + if let Some(rail) = at.iter().map(|&c| &cands[c as usize]).find(|c| c.label.surface == Surface::RailBed) { + label.surface = Surface::Crossing; + label.crossing = rail.label.material; + label.legs[1] = rail.label.legs[0]; + } + } + label +} + +/// The faces from the labelled patches: patches of one label that share an edge, not across a cell +/// line, form a face. +fn output(cell: CellKey, level: i8, map: &Map, labels: &[Label], mut stats: FaceStats) -> FacePlan { + let mut ids: Vec

{ lp.1.iter().map(|&v| map.point(v)).collect() }; + let mut shapes: Vec<(u32, Loop, Vec)> = Vec::new(); + for (g, (outers, holes)) in by_group { + let first = shapes.len(); + shapes.extend(outers.into_iter().map(|o| (g, o, Vec::new()))); + for h in holes { + let (a, b) = (map.point(h.1[0]), map.point(h.1[1])); + let mid = [i64::from(a[0]) + i64::from(b[0]), i64::from(a[1]) + i64::from(b[1])]; + let home = (first..shapes.len()) + .filter(|&k| shapes.len() == first + 1 || geom::winding(&[points(&shapes[k].1)], mid) != 0) + .min_by_key(|&k| shapes[k].1 .2); + if let Some(k) = home { + shapes[k].2.push(h); + } + } + } + let mut used: Vec = + shapes.iter().flat_map(|(_, o, hs)| o.1.iter().chain(hs.iter().flat_map(|h| &h.1)).copied()).collect(); + used.sort_unstable(); + used.dedup(); + let index = |v: u32| used.binary_search(&v).unwrap() as u32; + let c = CELL_UNITS as i32; + let mut faces: Vec<(Vec, Face)> = shapes + .into_iter() + .map(|(g, outer, holes)| { + let l = labels[g as usize]; + let ring = |lp: &[u32]| { + let mut r: Vec = lp.iter().map(|&v| index(v)).collect(); + let start = (0..r.len()).min_by_key(|&i| r[i]).unwrap_or(0); + r.rotate_left(start); + r + }; + let mut rings = vec![ring(&outer.1)]; + rings.extend(holes.iter().map(|h| ring(&h.1))); + let inside = + outer.1.iter().map(|&v| map.point(v)).all(|p| (0..=c).contains(&p[0]) && (0..=c).contains(&p[1])); + let halves: Vec = outer.3.iter().chain(holes.iter().flat_map(|h| &h.3)).copied().collect(); + let face = Face { + id: 0, + owner: l.owner, + surface: l.surface, + level, + rule: l.rule, + material: l.material, + crossing: l.crossing, + rank: l.rank, + inside, + reach_m: l.reach_m, + legs: l.legs, + rings, + }; + (halves, face) + }) + .collect(); + faces.sort_by_key(|(_, f)| (f.surface, f.owner, f.rings[0].first().copied())); + let mut face_of = vec![OUTSIDE; map.half.len()]; + for (id, (halves, f)) in faces.iter_mut().enumerate() { + f.id = id as u32; + for &h in halves.iter() { + face_of[h as usize] = id as u32; + } + } + let faces: Vec = faces.into_iter().map(|(_, f)| f).collect(); + let mut edges = Vec::new(); + for (h, e) in map.half.iter().enumerate() { + if !map.bounds(&groups, h as u32) || face_of[h] == OUTSIDE { + continue; + } + let (a, b) = (index(e.a), index(e.b)); + let right = if e.twin == NONE { OUTSIDE } else { face_of[e.twin as usize] }; + if right != OUTSIDE && a > b { + continue; + } + let left = face_of[h]; + let (a, b, left, right) = if a < b { (a, b, left, right) } else { (b, a, right, left) }; + let kind = + if on_cell_line(map.point(e.a), map.point(e.b)) { EdgeKind::CellBorder } else { EdgeKind::Continuous }; + edges.push(Edge { a, b, left, right, kind, flags: 0 }); + } + edges.sort_by_key(|e| (e.a, e.b)); + stats.faces = faces.len() as u32; + stats.vertices = used.len() as u32; + stats.edges = edges.len() as u32; + FacePlan { + cell, + level, + vertices: used.iter().map(|&v| map.point(v)).collect(), + faces, + edges, + corners: Vec::new(), + mouths: Vec::new(), + stats, + } +} diff --git a/host/obc-ground-plan/src/faces/outline.rs b/host/obc-ground-plan/src/faces/outline.rs new file mode 100644 index 0000000000..6beebf30b9 --- /dev/null +++ b/host/obc-ground-plan/src/faces/outline.rs @@ -0,0 +1,248 @@ +//! The rounds at the inward corners of the paved outline that no point's round shapes: where two +//! ways' carriageways meet without a graph point between them, where a third piece lies between a +//! point's two arms, and where a way turns inside a point's region. A corner tighter than the least +//! inner radius of the ways whose edges form it gets the circle tangent to its two edges, off the +//! paved area, of that radius or the largest of the ladder that fits. + +use std::cell::OnceCell; + +use super::check::{place, radii, turn_at, KINK_SHARE, SUPPORT_M}; +use super::geom::P; +use super::points::{corner_round, Circle}; +use super::stroke::Rings; +use super::{WayLine, LAYERS}; + +/// A way forms a corner where its carriageway's edge runs within this many units of the corner: the +/// overlay's snap (1 unit) and the rounding of the centre line's samples and of the edge to the unit +/// grid (0.71 units each) move a corner off its edge by under 3 units. +const ON_EDGE: f64 = 4.0; + +/// The ways at a point: the least `inner_radius_m` and the greatest `sag_plan_m` of the ways whose +/// carriageway edge runs through q, if any. The paved outline holds no water. +pub fn at_corner(lines: &[WayLine], q: P) -> Option<(f64, f64)> { + let (x, y) = (f64::from(q[0]), f64::from(q[1])); + let mut out: Option<(f64, f64)> = None; + for line in lines.iter().filter(|l| !l.sec.water) { + let touches = line.near([x, y], ON_EDGE).any(|i| { + let (a, c) = (line.p[i], line.p[i + 1]); + let (ax, ay) = (f64::from(a[0]), f64::from(a[1])); + let (u, v) = ([f64::from(c[0]) - ax, f64::from(c[1]) - ay], [x - ax, y - ay]); + let l2 = u[0] * u[0] + u[1] * u[1]; + let t = if l2 > 0.0 { ((v[0] * u[0] + v[1] * u[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let (dx, dy) = (v[0] - t * u[0], v[1] - t * u[1]); + (dx * dx + dy * dy).sqrt() - (line.h[i] + t * (line.h[i + 1] - line.h[i])) <= ON_EDGE + }); + if touches { + let (r, s) = (line.sec.inner_radius_m, line.sec.sag_plan_m); + out = Some(out.map_or((r, s), |(r0, s0)| (r0.min(r), s0.max(s)))); + } + } + out +} + +/// The way whose carriageway edge runs nearest q (an index into `lines`, `usize::MAX` for none), with +/// its band layers' outer offsets past that edge (units, `LAYERS`). A water line is no way. +fn bands_at(lines: &[WayLine], q: [f64; 2]) -> (usize, [f64; LAYERS]) { + let mut best = (f64::INFINITY, usize::MAX, [0.0; LAYERS]); + for (l, line) in lines.iter().enumerate().filter(|(_, l)| !l.sec.water) { + let b = line.bbox; + let pad = f64::from(ON_EDGE as i32) + 1.0; + if q[0] < f64::from(b[0]) - pad + || q[0] > f64::from(b[2]) + pad + || q[1] < f64::from(b[1]) - pad + || q[1] > f64::from(b[3]) + pad + { + continue; + } + for i in 0..line.p.len().saturating_sub(1) { + let (a, c) = (line.p[i], line.p[i + 1]); + let (ax, ay) = (f64::from(a[0]), f64::from(a[1])); + let (u, v) = ([f64::from(c[0]) - ax, f64::from(c[1]) - ay], [q[0] - ax, q[1] - ay]); + let l2 = u[0] * u[0] + u[1] * u[1]; + let t = if l2 > 0.0 { ((v[0] * u[0] + v[1] * u[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let h = line.h[i] + t * (line.h[i + 1] - line.h[i]); + let off = (libm::hypot(v[0] - t * u[0], v[1] - t * u[1]) - h).abs(); + if off < best.0 { + let w = std::array::from_fn(|k| line.bands[i][k] + t * (line.bands[i + 1][k] - line.bands[i][k]) - h); + best = (off, l, w); + } + } + } + (best.1, best.2) +} + +/// A round at a corner of the paved outline: its ring, its circle, and a point inside the paved area +/// at the corner (doubled), whose label the ring takes. +pub struct Fill { + pub ring: Vec

, + /// Its band rings (`LAYERS`). + pub bands: [Vec>; LAYERS], + pub circle: Circle, + pub inside: [i64; 2], +} + +/// Whether every segment lies at least d from point c. +fn clear(segments: &[[P; 2]], c: [f64; 2], d: f64) -> bool { + segments.iter().all(|&[a, b]| { + let (ax, ay) = (f64::from(a[0]), f64::from(a[1])); + let (u, v) = ([f64::from(b[0]) - ax, f64::from(b[1]) - ay], [c[0] - ax, c[1] - ay]); + let l2 = u[0] * u[0] + u[1] * u[1]; + let t = if l2 > 0.0 { ((v[0] * u[0] + v[1] * u[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let (dx, dy) = (v[0] - t * u[0], v[1] - t * u[1]); + dx * dx + dy * dy >= d * d + }) +} + +/// A place of the paved outline: a vertex whose round the rule decides. +struct Place { + ring: usize, + at: usize, + v: P, + /// Its own turn (negative: toward the right) and the next vertex, the keys of its order. + turn: f64, + next: P, + /// The least radius of the corner about it (units). + radius: f64, +} + +/// The rounds at the corners of the paved outline `paved` (outer rings counter-clockwise, holes +/// clockwise: the paved side on the left). A place gets the circle tangent to the outline's two +/// edges from it, off the paved area, unless it lies on a round of `circles` (centre, radius in +/// units) or the round of a sharper place within `len_m` that is first: a place is first if it lies +/// on the round of no sharper place within `len_m`. So a place's round depends on the places within +/// twice `len_m` only, in no order of rings. The rounds of the places within `len_m` + `r_max` of +/// the window can reach it; `beyond(p)` is the distance of p past the window (metres). `units(m, p)` +/// turns metres into units at p; `r_max` is the greatest inner radius (metres). +pub fn rounds( + paved: &Rings, + lines: &[WayLine], + circles: &[(P, f64)], + beyond: &dyn Fn(P) -> f64, + units: &dyn Fn(f64, P) -> f64, + len_m: f64, + r_max: f64, +) -> Vec { + let reach_m = len_m + r_max; + let mut places: Vec = Vec::new(); + for (k, ring) in paved.iter().enumerate() { + let n = ring.len(); + if n < 3 { + continue; + } + let turn: Vec = (0..n).map(|i| turn_at(ring, i)).collect(); + let some: Vec> = turn.iter().map(|&t| Some(t)).collect(); + let radius = radii(ring, &some, &|p| units(SUPPORT_M, p)); + // A ring that is one corner all round has no edge to run a round into. + if radius.iter().all(Option::is_some) { + continue; + } + for at in 0..n { + let v = ring[at]; + if beyond(v) > reach_m + 2.0 * len_m { + continue; + } + if let Some(radius) = place(ring, &some, &radius, at, units(len_m, v)) { + places.push(Place { ring: k, at, v, turn: turn[at], next: ring[(at + 1) % n], radius }); + } + } + } + places.sort_by(|a, b| a.turn.total_cmp(&b.turn).then(a.v.cmp(&b.v)).then(a.next.cmp(&b.next))); + let on = |o: P, rho: f64, v: P| { + let d = libm::hypot(f64::from(o[0] - v[0]), f64::from(o[1] - v[1])); + (d - rho).abs() < units(0.1, v) + }; + // A place on a point's round has its round, as the kink check reads it: within 0.1 m of its + // circle, over that check's tolerance for most classes (`sag_plan_m` 0.05 m and twice the + // precision, 0.06 m). A place's round is made when a decision reads it. + let fills: Vec>> = places.iter().map(|_| OnceCell::new()).collect(); + let fill = |j: usize| { + fills[j] + .get_or_init(|| { + let p = &places[j]; + if circles.iter().any(|&(o, rho)| on(o, rho, p.v)) { + return None; + } + round_at(paved, lines, &paved[p.ring], p.at, p.radius, units, len_m, r_max) + }) + .as_ref() + }; + // Whether a sharper place within `len_m` of place j and accepted by `ok` rounds it: j lies on + // its circle, or has the same circle (two places of one bend). + let covered = |j: usize, ok: &dyn Fn(usize) -> bool| { + let q = &places[j]; + (0..j).any(|i| { + let p = &places[i]; + let close = libm::hypot(f64::from(p.v[0] - q.v[0]), f64::from(p.v[1] - q.v[1])) <= units(len_m, q.v); + close + && fill(i).is_some_and(|f| { + let c = &f.circle; + let same = fill(j) + .is_some_and(|g| g.circle.centre == c.centre && (g.circle.radius - c.radius).abs() < 0.5); + (on(c.centre, c.radius, q.v) || same) && ok(i) + }) + }) + }; + let first: Vec> = places.iter().map(|_| OnceCell::new()).collect(); + let is_first = |i: usize| *first[i].get_or_init(|| fill(i).is_some() && !covered(i, &|_| true)); + let made: Vec = (0..places.len()) + .filter(|&j| beyond(places[j].v) <= reach_m && fill(j).is_some() && !covered(j, &is_first)) + .collect(); + let mut fills = fills; + made.into_iter().filter_map(|j| fills[j].take().flatten()).collect() +} + +/// The round at place `at` of a ring of the paved outline, at a corner of radius `radius` (units). +#[allow(clippy::too_many_arguments)] +fn round_at( + paved: &Rings, + lines: &[WayLine], + ring: &[P], + at: usize, + radius: f64, + units: &dyn Fn(f64, P) -> f64, + len_m: f64, + r_max: f64, +) -> Option { + let n = ring.len(); + let v = ring[at]; + if radius >= KINK_SHARE * units(r_max, v) { + return None; + } + let (inner, sag) = at_corner(lines, v)?; + let r = units(inner, v); + if radius >= KINK_SHARE * r { + return None; + } + let len = units(len_m, v); + // The outline's edges from the corner: walked backward, and ahead, past `len` along them. + let walk = |dir: isize| { + let mut chain = vec![v]; + let mut s = 0.0; + for k in 1..n as isize { + let p = ring[(at as isize + dir * k).rem_euclid(n as isize) as usize]; + let q = chain[chain.len() - 1]; + s += libm::hypot(f64::from(p[0] - q[0]), f64::from(p[1] - q[1])); + chain.push(p); + if s >= len { + break; + } + } + chain + }; + // The outline's segments that a circle about the corner can meet: its centre lies within `len` + // and its radius of the corner. A centre off them by its radius lies in land: it lies on the land + // side of both edges. + let reach = len + 2.0 * r; + let (x0, y0, x1, y1) = (v[0] as f64 - reach, v[1] as f64 - reach, v[0] as f64 + reach, v[1] as f64 + reach); + let segments: Vec<[P; 2]> = (paved.iter()) + .flat_map(|ring| (0..ring.len()).map(move |i| [ring[i], ring[(i + 1) % ring.len()]])) + .filter(|&[a, b]| { + let (lo_x, hi_x) = (f64::from(a[0].min(b[0])), f64::from(a[0].max(b[0]))); + let (lo_y, hi_y) = (f64::from(a[1].min(b[1])), f64::from(a[1].max(b[1]))); + hi_x >= x0 && lo_x <= x1 && hi_y >= y0 && lo_y <= y1 + }) + .collect(); + let tol = units(sag, v); + let off = |q: [f64; 2], rho: f64| clear(&segments, [f64::from(v[0]) + q[0], f64::from(v[1]) + q[1]], rho - tol); + corner_round(v, &walk(-1), &walk(1), r, tol, len, &off, &|q| bands_at(lines, q)) +} diff --git a/host/obc-ground-plan/src/faces/platform.rs b/host/obc-ground-plan/src/faces/platform.rs new file mode 100644 index 0000000000..50d6d6621a --- /dev/null +++ b/host/obc-ground-plan/src/faces/platform.rs @@ -0,0 +1,80 @@ +//! The platforms' candidates: an area's rings, or a line's stroke of half-width `width / 2`, else +//! `platform_half_m`. A platform beats the rail bed, so the heights can stand a wall at their edge. + +use super::geom::area2; +use super::stroke::{pieces_along, union}; +use super::{Cand, Ctx, Label, Rank}; +use crate::faces::{FaceStats, HeightRule, Owner, Surface}; +use crate::sections::leading_number; +use crate::tile::Geometry; +use crate::CellInput; + +/// The candidates of the input's platforms that reach the window `bx`. A platform without vertex +/// heights is skipped: the heights have no level for it. +pub(super) fn candidates(ctx: &Ctx, input: &CellInput, bx: [i32; 4], stats: &mut FaceStats) -> Vec { + let plan = &ctx.rules.plan; + let mut out = Vec::new(); + for (index, f) in input.features.iter().enumerate() { + let area = match (f.kind.as_str(), f.geometry) { + ("platform", Geometry::Area) => true, + ("platform-line", Geometry::Line) => false, + _ => continue, + }; + let local = |p: &crate::frame::GlobalPoint| [(p.x - ctx.origin.x) as i32, (p.y - ctx.origin.y) as i32]; + let near = |p: &[i32; 2]| p[0] >= bx[0] && p[0] <= bx[2] && p[1] >= bx[1] && p[1] <= bx[3]; + let parts: Vec> = f.parts.iter().map(|part| part.points.iter().map(local).collect()).collect(); + let (Some(first), true) = (f.parts.first(), parts.iter().flatten().any(near)) else { continue }; + if !f.parts.iter().all(|p| p.heights.as_ref().is_some_and(|h| h.iter().any(Option::is_some))) { + stats.platforms_skipped += 1; + continue; + } + let rings = if area { + // The winding of a ring has no meaning in the tiles: an outer ring turns positive, a + // hole negative, for the NonZero rule. + let mut rings = parts.clone(); + for (ring, part) in rings.iter_mut().zip(&f.parts) { + if (area2(ring) > 0) != part.outer { + ring.reverse(); + } + } + rings + } else { + let half_m = f.tags.get("width").and_then(|w| leading_number(w)).map_or(plan.platform_half_m, |w| w / 2.0); + let mut pieces = Vec::new(); + for p in &parts { + let d: Vec = p.iter().map(|&q| ctx.units(half_m, q)).collect(); + pieces_along(p, &d, &[], [&[], &[]], [false, false], false, &mut pieces); + } + pieces + }; + let anchor = parts_anchor(&rings); + let label = Label { + owner: Owner::Platform(index as u32), + surface: Surface::Platform, + rule: HeightRule::Owner, + material: None, + crossing: None, + rank: plan.rank(Rank::Platform), + reach_m: plan.platform_reach_m as f32, + legs: [0, 0], + }; + let p0 = first.points[0]; + out.push(Cand { + rings: union(&rings, anchor), + label, + key: (plan.rank(Rank::Platform), 0, 3), + glob: Some([i64::from(first.tile.0), i64::from(first.tile.1), i64::from(f.index), p0.x, p0.y]), + line: 0, + relabel: None, + beyond: Vec::new(), + fill: None, + discs: Vec::new(), + }); + } + out +} + +/// A vertex of the rings that every cell finds alike: the least. +fn parts_anchor(rings: &[Vec<[i32; 2]>]) -> [i32; 2] { + rings.iter().flatten().copied().min().unwrap_or([0, 0]) +} diff --git a/host/obc-ground-plan/src/faces/points.rs b/host/obc-ground-plan/src/faces/points.rs new file mode 100644 index 0000000000..1fae044d7f --- /dev/null +++ b/host/obc-ground-plan/src/faces/points.rs @@ -0,0 +1,1146 @@ +//! The rounds where ways meet or turn. Per graph point (a junction, a joint, or a tight turn of one +//! way) and pair of neighbouring arms, a circle of the pair's radius or the largest smaller one that +//! fits: tangent to the two facing carriageway edges where they cross, else tangent to one arm's edge +//! where it leaves the point's other pieces (another arm's square end, a gap fill). Its fan: the arms' +//! centre lines up to the circle's feet and the arc between. A junction's or joint's region: per arm, +//! a stub up to a straight seam past the farthest foot or overlap. Ways that do not meet at a point +//! are never joined. + +use super::geom::P; +use super::stroke::{left as left_of, off, pie_between, pieces_along, push_positive, unit as unit_of, Rings, STEPS}; +use super::{WayLine, LAYERS}; + +/// A fan's straight sides lie this many units inside the carriageway or the band it joins, so its +/// arc crosses their edge at an angle and no sliver is left between two edges that run together. +const INSET: f64 = 3.0; + +/// The sides of a round at a corner of the paved outline run this many units inside the paved side: +/// closer, they would run along its edges within the overlay's snap, and the slice splits such +/// near-coincident edges again and again. +const FILL_INSET: f64 = 32.0; + +/// The unit mean of two unit vectors. +fn mean(a: [f64; 2], b: [f64; 2]) -> [f64; 2] { + let m = [a[0] + b[0], a[1] + b[1]]; + let l = (m[0] * m[0] + m[1] * m[1]).sqrt(); + if l > 0.0 { + [m[0] / l, m[1] / l] + } else { + a + } +} + +/// A round smaller than this many units is none: the corner stays sharp. Below it an arc step is +/// under 11 units long, and the rounding of its ends to the unit grid turns it by up to 8°, near the +/// 10° of the step itself. The value is in units, as its reason is the unit grid. +const MIN_RADIUS: f64 = 60.0; + +/// A circle touches an edge where its distance from the centre line is at most this many units over +/// the half-width plus its radius: the edge's samples and the circle's centre each lie up to 0.71 +/// units off their exact place on the unit grid. +const TOUCH: f64 = 2.0; + +/// The halvings of the scan for the place where an edge leaves the other pieces. +const SEARCH: usize = 10; + +/// Each radius of the search for the largest round that fits is this share of the one before: a +/// round that wins is under the next radius up, which does not fit, by at most 15 %, and a 9 m +/// round tries at most 28 radii at 47° N. +const LADDER: f64 = 0.85; + +/// The radii that a round of radius r tries, largest first, down to `MIN_RADIUS`. Whether a circle +/// fits is no monotonic function of its radius (a smaller circle can meet a piece that a larger one +/// clears), so each radius is tested in full and the first that fits wins. +fn ladder(r: f64) -> impl Iterator { + std::iter::successors(Some(r), |&rho| Some(rho * LADDER)).take_while(|&rho| rho >= MIN_RADIUS) +} + +/// A stub of a point's region is this much wider than the carriageway on each side, in units (0.48 m +/// at 47° N, 0.35 m at 60° N): a margin for the strokes' mitres and tapers past the samples' +/// half-widths. The region relabels only its arms' carriageways, so a wider stub changes no other +/// face; a seam reaches as far past the carriageway before it grows across the fans (`grow`). +const STUB_PAD: f64 = 300.0; + +/// An arm: a way's line from the point's sample, toward `dir` (+1 or −1 in sample order). +#[derive(Clone, Copy, Debug)] +pub struct Arm { + pub line: usize, + pub at: usize, + pub dir: i8, +} + +pub struct Rounded { + /// One fan per round: the arms' centre lines to the feet, the round's arc between. + pub fans: Vec>, + /// The band fans: paved shoulder, shoulder, verge, slope. + pub rings: [Rings; LAYERS], + /// The point's region up to its seams (junctions and joints): it relabels its arms' carriageways. + pub region: Rings, + /// The parts of the arms' lines in the region. The arms of a way that runs on through the point + /// form one part. + pub spans: Vec, + /// Per arm, its seam: a cut across its carriageway and past it on both sides, from the arm's + /// right to its left (past the cut lies away from the point). + pub seams: Vec>, + /// The circle of each round. + pub circles: Vec, + /// Per arm, its run and the station of the farthest foot of a round or crossing of facing edges. + runs: Vec>, + pub far: Vec, +} + +/// A round's circle: its centre and radius in units, its feet (the tangent points on the two edges +/// it joins: the ends of its arc), and its arc's points at the global directions strictly between +/// the feet, as its fan has them. A sharp corner is a circle of radius 0 with the corner as its +/// centre, its feet and its arc. Per foot, the line of that edge (`usize::MAX` for none): the heights +/// relate a fan's two arms so. +#[derive(Clone, Debug)] +pub struct Circle { + pub centre: P, + pub radius: f64, + pub feet: [P; 2], + pub arc: Vec

, + pub lines: [usize; 2], +} + +impl Circle { + /// The circle about c (relative, `abs` makes it absolute) of radius rho whose arc runs from + /// angle a0 through `sweep` radians. + fn new(abs: &dyn Fn([f64; 2]) -> P, c: [f64; 2], rho: f64, a0: f64, sweep: f64) -> Self { + let at = |a: f64| abs([c[0] + rho * libm::cos(a), c[1] + rho * libm::sin(a)]); + let arc = arc(c, rho, a0, sweep).into_iter().map(abs).collect(); + Circle { centre: abs(c), radius: rho, feet: [at(a0), at(a0 + sweep)], arc, lines: [usize::MAX; 2] } + } + + fn sharp(k: P) -> Self { + Circle { centre: k, radius: 0.0, feet: [k, k], arc: vec![k], lines: [usize::MAX; 2] } + } + + /// The circle with the line at each foot. + fn at_edges(self, lines: [usize; 2]) -> Self { + Circle { lines, ..self } + } +} + +/// A part of a line in a point's region, between fractional sample indices `lo` and `hi`, and the +/// seam at each end (none at the point where the way ends). +#[derive(Clone, Copy, Debug)] +pub struct Part { + pub line: usize, + pub lo: f64, + pub hi: f64, + pub cuts: [Option<[P; 2]>; 2], +} + +/// A seam that two points share on the link between them: its point, the link's direction there in +/// sample order, its half-length, and its place as a fractional sample index. +#[derive(Clone, Copy, Debug)] +pub struct Seam { + p: P, + u: [f64; 2], + w: f64, + x: f64, +} + +/// A seam's cut grown so that it crosses every fan that reaches past it: `fans` by the side each +/// lies on (+1 the cut's own point's, −1 the far side). Past its seam a fan belongs to the face on +/// the other side, so the cut must split it from edge to edge. The cut grows by whole multiples of +/// its half, so it stays on the line of the stub's end that it was. +pub fn grow(cut: [P; 2], fans: &[(&[Vec

], f64)]) -> [P; 2] { + let end = [(cut[0][0] + cut[1][0]) / 2, (cut[0][1] + cut[1][1]) / 2]; + let e = [cut[1][0] - end[0], cut[1][1] - end[1]]; + let half = (f64::from(e[0]) * f64::from(e[0]) + f64::from(e[1]) * f64::from(e[1])).sqrt(); + if half == 0.0 { + return cut; + } + // Along the cut, and past it: the cut runs from the arm's right to its left. + let n = [f64::from(e[0]) / half, f64::from(e[1]) / half]; + let out = [n[1], -n[0]]; + let rel = |v: P| [f64::from(v[0] - end[0]), f64::from(v[1] - end[1])]; + let dot = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1]; + let mut reach = half; + for &(rings, side) in fans { + for ring in rings { + for (i, &v) in ring.iter().enumerate() { + let (a, b) = (rel(v), rel(ring[(i + 1) % ring.len()])); + let (sa, sb) = (side * dot(a, out), side * dot(b, out)); + if sa > 0.0 { + reach = reach.max(dot(a, n).abs() + INSET); + } + if (sa > 0.0) != (sb > 0.0) { + reach = reach.max(dot(lerp(a, b, sa / (sa - sb)), n).abs() + INSET); + } + } + } + } + let k = libm::ceil(reach / half) as i32; + [[end[0] - k * e[0], end[1] - k * e[1]], [end[0] + k * e[0], end[1] + k * e[1]]] +} + +/// Each cut `old` of a point's seams and parts, as `new`; the same cut seen from the far side (a +/// shared seam's other point) reversed. +pub fn replace_cut(r: &mut Rounded, old: [P; 2], new: [P; 2]) { + let swap = |c: &mut [P; 2]| { + if *c == old { + *c = new; + } else if *c == [old[1], old[0]] { + *c = [new[1], new[0]]; + } + }; + r.seams.iter_mut().flatten().for_each(swap); + r.spans.iter_mut().flat_map(|p| p.cuts.iter_mut().flatten()).for_each(swap); +} + +/// The seam that two points at samples `a` < `b` of a line share when their own seams (`seam` past +/// the farthest feet `far`, from a and from b) would overlap: in the middle of the part between +/// the feet. It is computed from the line in sample order, so both points get the same cut. +pub fn link_seam(line: &WayLine, a: usize, b: usize, far: [f64; 2], seam: f64) -> Option { + let q = |i: usize| [f64::from(line.p[i][0]), f64::from(line.p[i][1])]; + let len: f64 = (a..b).map(|i| dist(q(i), q(i + 1))).sum(); + if far[0] + far[1] + 2.0 * seam <= len { + return None; + } + let m = (0.5 * (far[0] + len - far[1])).clamp(0.0, len); + let mut s0 = 0.0; + for i in a..b { + let l = dist(q(i), q(i + 1)); + if s0 + l >= m && l > 0.0 { + let t = (m - s0) / l; + let at = lerp(q(i), q(i + 1), t); + let p = [libm::round(at[0]) as i32, libm::round(at[1]) as i32]; + let w = line.h[i] + t * (line.h[i + 1] - line.h[i]) + STUB_PAD; + return Some(Seam { p, u: unit(q(i), q(i + 1)), w, x: i as f64 + t }); + } + s0 += l; + } + None +} + +/// A point of an arm's run, about the graph point: its place as a fractional sample index, its +/// point, half-width and band offsets. +#[derive(Clone, Copy, Debug)] +struct RunPoint { + x: f64, + q: [f64; 2], + h: f64, + bands: [f64; LAYERS], +} + +/// The run of an arm: from the point along its way for `len` units, ending early at another point's +/// sample (`stops`, sorted). +fn run(line: &WayLine, arm: Arm, pos: P, len: f64, stops: &[usize]) -> Vec { + let rel = |p: P| [f64::from(p[0] - pos[0]), f64::from(p[1] - pos[1])]; + let mut out = + vec![RunPoint { x: arm.at as f64, q: rel(line.p[arm.at]), h: line.h[arm.at], bands: line.bands[arm.at] }]; + let mut i = arm.at as isize; + let mut s = 0.0; + loop { + let j = i + isize::from(arm.dir); + if j < 0 || j as usize >= line.p.len() { + break; + } + let (a, b) = (out.last().unwrap().q, rel(line.p[j as usize])); + let seg = dist(a, b); + let (bi, bj) = (line.bands[i as usize], line.bands[j as usize]); + if s + seg >= len && seg > 0.0 { + let g = (len - s) / seg; + let h = line.h[i as usize] + g * (line.h[j as usize] - line.h[i as usize]); + let bands = std::array::from_fn(|k| bi[k] + g * (bj[k] - bi[k])); + out.push(RunPoint { x: i as f64 + f64::from(arm.dir) * g, q: lerp(a, b, g), h, bands }); + break; + } + s += seg; + if seg > 0.0 { + out.push(RunPoint { x: j as f64, q: b, h: line.h[j as usize], bands: bj }); + } + if stops.binary_search(&(j as usize)).is_ok() { + break; + } + i = j; + } + out +} + +fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { + let (x, y) = (b[0] - a[0], b[1] - a[1]); + (x * x + y * y).sqrt() +} + +fn lerp(a: [f64; 2], b: [f64; 2], t: f64) -> [f64; 2] { + [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])] +} + +fn unit(a: [f64; 2], b: [f64; 2]) -> [f64; 2] { + let d = dist(a, b); + if d > 0.0 { + [(b[0] - a[0]) / d, (b[1] - a[1]) / d] + } else { + [1.0, 0.0] + } +} + +/// The left normal (a quarter turn toward +y: toward a greater angle). +fn left(u: [f64; 2]) -> [f64; 2] { + [-u[1], u[0]] +} + +/// The run's length. +fn length(run: &[RunPoint]) -> f64 { + run.windows(2).map(|w| dist(w[0].q, w[1].q)).sum() +} + +/// The foot of q on a run: its station, the foot point, the half-width and band offsets there, and its +/// distance from q. +struct Foot { + s: f64, + at: [f64; 2], + h: f64, + bands: [f64; LAYERS], + dist: f64, +} + +fn foot(run: &[RunPoint], q: [f64; 2]) -> Foot { + let mut best = Foot { s: 0.0, at: run[0].q, h: run[0].h, bands: run[0].bands, dist: f64::INFINITY }; + let mut s0 = 0.0; + for w in run.windows(2) { + let (a, b) = (w[0].q, w[1].q); + let len = dist(a, b); + let t = if len > 0.0 { + (((q[0] - a[0]) * (b[0] - a[0]) + (q[1] - a[1]) * (b[1] - a[1])) / (len * len)).clamp(0.0, 1.0) + } else { + 0.0 + }; + let at = lerp(a, b, t); + let d = dist(at, q); + if d < best.dist { + let bands = std::array::from_fn(|k| w[0].bands[k] + t * (w[1].bands[k] - w[0].bands[k])); + best = Foot { s: s0 + t * len, at, h: w[0].h + t * (w[1].h - w[0].h), bands, dist: d }; + } + s0 += len; + } + best +} + +/// The station of fractional sample index x on a run. +fn station(run: &[RunPoint], x: f64) -> f64 { + let mut s0 = 0.0; + for w in run.windows(2) { + let len = dist(w[0].q, w[1].q); + if w[0].x != w[1].x && (x - w[0].x) * (w[1].x - x) >= 0.0 { + return s0 + (x - w[0].x) / (w[1].x - w[0].x) * len; + } + s0 += len; + } + s0 +} + +/// The fractional sample index at station s of a run. +fn place(run: &[RunPoint], s: f64) -> f64 { + let mut s0 = 0.0; + for w in run.windows(2) { + let len = dist(w[0].q, w[1].q); + if s0 + len >= s && len > 0.0 { + return w[0].x + (s - s0) / len * (w[1].x - w[0].x); + } + s0 += len; + } + run.last().map_or(0.0, |r| r.x) +} + +/// The run's points up to station s, the point there last. +fn up_to(run: &[RunPoint], s: f64) -> Vec<[f64; 2]> { + let mut out = vec![run[0].q]; + let mut s0 = 0.0; + for w in run.windows(2) { + let len = dist(w[0].q, w[1].q); + if s0 + len >= s { + let t = if len > 0.0 { ((s - s0) / len).clamp(0.0, 1.0) } else { 0.0 }; + out.push(lerp(w[0].q, w[1].q, t)); + return out; + } + out.push(w[1].q); + s0 += len; + } + out +} + +/// The segments of a run's edge on `side` (+1 left, −1 right) at the half-width plus `extra`: one per +/// segment, and a chord over the gap at each joint that turns away from that side. +fn edge(run: &[RunPoint], side: f64, extra: f64) -> Vec<[[f64; 2]; 2]> { + let mut out: Vec<[[f64; 2]; 2]> = Vec::new(); + for w in run.windows(2) { + let n = left(unit(w[0].q, w[1].q)); + let off = |r: &RunPoint| [r.q[0] + side * (r.h + extra) * n[0], r.q[1] + side * (r.h + extra) * n[1]]; + let seg = [off(&w[0]), off(&w[1])]; + if let Some(last) = out.last() { + if dist(last[1], seg[0]) > 0.0 { + out.push([last[1], seg[0]]); + } + } + out.push(seg); + } + out +} + +/// The crossing of segments ab and cd as fractions (t on ab, u on cd). +fn crossing(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> Option<(f64, f64)> { + let (r, s) = ([b[0] - a[0], b[1] - a[1]], [d[0] - c[0], d[1] - c[1]]); + let den = r[0] * s[1] - r[1] * s[0]; + if den == 0.0 { + return None; + } + let (qx, qy) = (c[0] - a[0], c[1] - a[1]); + let t = (qx * s[1] - qy * s[0]) / den; + let u = (qx * r[1] - qy * r[0]) / den; + ((0.0..=1.0).contains(&t) && (0.0..=1.0).contains(&u)).then_some((t, u)) +} + +/// The crossings of the facing edges of arms a (left side) and b (right side) at the half-width +/// plus `extra`, by summed distance from the point. On the inner side of a sharp turn an edge +/// crosses itself, so a later crossing can be the corner's. +fn crossings(ra: &[RunPoint], rb: &[RunPoint], extra: f64) -> Vec<(f64, [f64; 2])> { + let (ea, eb) = (edge(ra, 1.0, extra), edge(rb, -1.0, extra)); + let mut out = Vec::new(); + let mut sa = 0.0; + for x in &ea { + let mut sb = 0.0; + for y in &eb { + if let Some((t, u)) = crossing(x[0], x[1], y[0], y[1]) { + out.push((sa + t * dist(x[0], x[1]) + sb + u * dist(y[0], y[1]), lerp(x[0], x[1], t))); + } + sb += dist(y[0], y[1]); + } + sa += dist(x[0], x[1]); + } + out.sort_by(|p, q| p.0.total_cmp(&q.0)); + out +} + +/// A round of radius rho between arms a and b: its centre, if the circle touches both facing +/// carriageway edges at feet inside their runs and lies off every arm's carriageway (square at the +/// point) and off the point's gap fills and the other carriageways (`off`). It may cut `tol` units +/// into the arms' strokes: their chords leave the curve by as much. +fn round_at( + runs: &[Vec], + a: usize, + b: usize, + rho: f64, + tol: f64, + off: &dyn Fn([f64; 2], f64) -> bool, +) -> Option<([f64; 2], Foot, Foot)> { + // A foot at a joint whose two edges leave a gap is no tangent point: the circle misses the edge. + let inside = |f: &Foot, run: &[RunPoint]| { + let d = f.dist - f.h - rho; + f.s > 0.0 && f.s < length(run) - 1.0 && d <= TOUCH && d >= -tol + }; + crossings(&runs[a], &runs[b], rho).into_iter().find_map(|(_, c)| { + let (fa, fb) = (foot(&runs[a], c), foot(&runs[b], c)); + let clear = (0..runs.len()).all(|k| to_piece(runs, k, c).d >= rho - tol); + (inside(&fa, &runs[a]) && inside(&fb, &runs[b]) && clear && off(c, rho)).then_some((c, fa, fb)) + }) +} + +/// Whether a circle about c (relative to the point at `pos`) of radius rho lies off the carriageways +/// of the `lines` of kind `water` (a point's arms are all water or all ways) but for the parts of its +/// arms' lines on their runs (`own`: line, first and last sample index). Water and ways overlap by rank. +fn off_lines(lines: &[WayLine], water: bool, pos: P, own: &[(usize, f64, f64)], c: [f64; 2], rho: f64) -> bool { + let q = [f64::from(pos[0]) + c[0], f64::from(pos[1]) + c[1]]; + lines.iter().enumerate().filter(|(_, line)| line.sec.water == water).all(|(li, line)| { + let mine = |i: usize| own.iter().any(|&(l, lo, hi)| l == li && i as f64 + 1.0 > lo && (i as f64) < hi); + line.near(q, rho).filter(|&i| !mine(i)).all(|i| { + let (a, b) = (line.p[i], line.p[i + 1]); + let (a, b) = ([f64::from(a[0]), f64::from(a[1])], [f64::from(b[0]), f64::from(b[1])]); + let (u, v) = ([b[0] - a[0], b[1] - a[1]], [q[0] - a[0], q[1] - a[1]]); + let l2 = u[0] * u[0] + u[1] * u[1]; + let t = if l2 > 0.0 { ((v[0] * u[0] + v[1] * u[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + dist(lerp(a, b, t), q) >= line.h[i] + t * (line.h[i + 1] - line.h[i]) + rho - 1.0 + }) + }) +} + +/// The nearest point of a piece to a point outside it: the distance (0 inside), the point, whether +/// it is a vertex of the piece's outline, and its arm and station (none on a fill). +#[derive(Clone, Copy)] +struct Near { + d: f64, + at: [f64; 2], + vertex: bool, + arm: Option<(usize, f64)>, +} + +/// The nearest point of arm k's carriageway piece: its stroke along the run, square at the point. +fn to_piece(runs: &[Vec], k: usize, q: [f64; 2]) -> Near { + let run = &runs[k]; + let f = foot(run, q); + if f.s > 0.0 { + let n = unit(f.at, q); + let at = [f.at[0] + f.h * n[0], f.at[1] + f.h * n[1]]; + return Near { d: (f.dist - f.h).max(0.0), at, vertex: false, arm: Some((k, f.s)) }; + } + let (p, n, h) = (run[0].q, left(unit(run[0].q, run[1].q)), run[0].h); + let e = ((q[0] - p[0]) * n[0] + (q[1] - p[1]) * n[1]).clamp(-h, h); + let at = [p[0] + e * n[0], p[1] + e * n[1]]; + Near { d: dist(at, q), at, vertex: e.abs() == h, arm: Some((k, 0.0)) } +} + +/// The nearest point of a ring. +fn to_ring(ring: &[[f64; 2]], q: [f64; 2]) -> Near { + let (mut best, mut inside) = (Near { d: f64::INFINITY, at: q, vertex: false, arm: None }, false); + for i in 0..ring.len() { + let (a, b) = (ring[i], ring[(i + 1) % ring.len()]); + let (u, v) = ([b[0] - a[0], b[1] - a[1]], [q[0] - a[0], q[1] - a[1]]); + if (a[1] > q[1]) != (b[1] > q[1]) && v[0] < v[1] / u[1] * u[0] { + inside = !inside; + } + let l2 = u[0] * u[0] + u[1] * u[1]; + let t = if l2 > 0.0 { ((v[0] * u[0] + v[1] * u[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let at = lerp(a, b, t); + if dist(at, q) < best.d { + best = Near { d: dist(at, q), at, vertex: t == 0.0 || t == 1.0, arm: None }; + } + } + if inside { + best.d = 0.0; + } + best +} + +/// The distance from q to the point's pieces other than arm k: the other arms' carriageways and the +/// gap fills. With the nearest point, and its arm and station (none on a fill). +fn to_others(runs: &[Vec], fills: &[Vec<[f64; 2]>], k: usize, q: [f64; 2]) -> Near { + let arms = (0..runs.len()).filter(|&j| j != k).map(|j| to_piece(runs, j, q)); + let fills = fills.iter().map(|f| to_ring(f, q)); + arms.chain(fills).min_by(|x, y| x.d.total_cmp(&y.d)).unwrap_or(Near { + d: f64::INFINITY, + at: q, + vertex: false, + arm: None, + }) +} + +/// The point at station s on a run's edge on `side`, `extra` units out. +fn edge_at(run: &[RunPoint], s: f64, side: f64, extra: f64) -> [f64; 2] { + let mut s0 = 0.0; + for (i, w) in run.windows(2).enumerate() { + let len = dist(w[0].q, w[1].q); + if s0 + len >= s || i + 2 == run.len() { + let t = if len > 0.0 { ((s - s0) / len).clamp(0.0, 1.0) } else { 0.0 }; + let (q, n) = (lerp(w[0].q, w[1].q, t), left(unit(w[0].q, w[1].q))); + let d = side * (w[0].h + t * (w[1].h - w[0].h) + extra); + return [q[0] + d * n[0], q[1] + d * n[1]]; + } + s0 += len; + } + run[0].q +} + +/// A round where an arm's edge leaves the point's other pieces: its centre, the arm whose edge it +/// touches and the foot there, and where it touches the other pieces. +struct Leave { + c: [f64; 2], + k: usize, + foot: Foot, + touch: Near, +} + +/// The scan step along an edge for the place where it leaves the other pieces, in units (0.2 m at +/// 47° N, a fifth of `SUPPORT_M`): an edge that leaves the pieces for less and comes back reads as +/// not leaving, a shape under the length over which the kink check reads a corner. +const SCAN: f64 = 128.0; + +/// The round of radius rho on arm k's edge on `side` where that edge leaves the point's other pieces +/// (`fills` and the other arms' carriageways, square at the point): the circle tangent to the edge +/// at the first station where it lies rho off them. None where the edge starts clear of them (no +/// corner), or where the circle leaves past an arm's run or meets the arm's own carriageway or +/// another one (`off`). +fn leave( + runs: &[Vec], + fills: &[Vec<[f64; 2]>], + k: usize, + side: f64, + rho: f64, + tol: f64, + off: &dyn Fn([f64; 2], f64) -> bool, +) -> Option { + let run = &runs[k]; + let total = length(run); + let gap = |s: f64| to_others(runs, fills, k, edge_at(run, s, side, rho)).d - rho; + if gap(0.0) > -TOUCH { + return None; + } + let (mut lo, mut hi) = (0.0, SCAN); + while gap(hi) < 0.0 { + lo = hi; + hi += SCAN; + if hi >= total - 1.0 { + return None; + } + } + for _ in 0..SEARCH + 2 { + let mid = 0.5 * (lo + hi); + if gap(mid) < 0.0 { + lo = mid; + } else { + hi = mid; + } + } + let c = edge_at(run, hi, side, rho); + let near = to_others(runs, fills, k, c); + if to_piece(runs, k, c).d < rho - tol || near.arm.is_some_and(|(j, s)| s >= length(&runs[j]) - 1.0) || !off(c, rho) + { + return None; + } + Some(Leave { c, k, foot: foot(run, c), touch: near }) +} + +/// The fan of a round where an arm's edge leaves the other pieces: the arm's centre line to the foot, +/// the arc that faces the corner (under half a turn), and back through the touched piece to the +/// point. Its chords run into the two pieces, or end on the touched piece's corner itself, so no step +/// is left beside it. With the arc's start angle and sweep. None for an arc under one arc step: that +/// corner stays sharp, as the strokes mitre such a join. +fn leave_fan(runs: &[Vec], l: &Leave, rho: f64) -> Option<(Vec<[f64; 2]>, f64, f64)> { + let pi = std::f64::consts::PI; + let n = unit(l.foot.at, l.c); + let t = [l.foot.at[0] + l.foot.h * n[0], l.foot.at[1] + l.foot.h * n[1]]; + let into = |p: [f64; 2]| { + let u = unit(l.c, p); + [p[0] + INSET * u[0], p[1] + INSET * u[1]] + }; + let a0 = angle([t[0] - l.c[0], t[1] - l.c[1]]); + let a1 = angle([l.touch.at[0] - l.c[0], l.touch.at[1] - l.c[1]]); + let sweep = (a1 - a0 + pi).rem_euclid(2.0 * pi) - pi; + if sweep.abs() < 2.0 * pi / f64::from(STEPS) { + return None; + } + let mut fan = up_to(&runs[l.k], l.foot.s); + fan.push(into(t)); + fan.extend(arc(l.c, rho, a0, sweep)); + fan.push(if l.touch.vertex { l.touch.at } else { into(l.touch.at) }); + match l.touch.arm { + Some((j, s)) => fan.extend(up_to(&runs[j], s).into_iter().rev()), + None => fan.push([0.0, 0.0]), + } + Some((fan, a0, sweep)) +} + +/// A round's circle: tangent to the facing edges of both arms, or to one arm's edge where it leaves +/// the point's other pieces. +enum Fit { + Edges([f64; 2], Foot, Foot), + Leaves(Leave), +} + +/// The angle of v. +fn angle(v: [f64; 2]) -> f64 { + libm::atan2(v[1], v[0]) +} + +/// The arc about c of radius rho from angle a0 sweeping `sweep` radians (signed): its points at the +/// global directions strictly between its ends (36 steps, as the strokes'). Its ends, the tangent +/// points on an edge, are left out: a rounded tangent point lies a unit off the stroke's own edge +/// and would leave a step there. The fan's chord from inside the edge to the first point crosses +/// the edge at an angle instead. +fn arc(c: [f64; 2], rho: f64, a0: f64, sweep: f64) -> Vec<[f64; 2]> { + arc_angles(a0, sweep).into_iter().map(|a| [c[0] + rho * libm::cos(a), c[1] + rho * libm::sin(a)]).collect() +} + +/// The global directions strictly between angle a0 and a0 + sweep, in order from a0. +fn arc_angles(a0: f64, sweep: f64) -> Vec { + let step = 2.0 * std::f64::consts::PI / f64::from(STEPS); + let mut out = Vec::new(); + let a1 = a0 + sweep; + let eps = 0.01; + if sweep >= 0.0 { + let mut k = libm::floor(a0 / step) as i64 + 1; + while (k as f64) * step < a1 - eps { + if (k as f64) * step > a0 + eps { + out.push(k as f64 * step); + } + k += 1; + } + } else { + let mut k = libm::ceil(a0 / step) as i64 - 1; + while (k as f64) * step > a1 + eps { + if (k as f64) * step < a0 - eps { + out.push(k as f64 * step); + } + k -= 1; + } + } + out +} + +/// The arc of a round about c (relative to its point) between its feet that faces the point: its +/// start angle and signed sweep. +fn facing(c: [f64; 2], fa: &Foot, fb: &Foot) -> (f64, f64) { + let (na, nb) = (unit(fa.at, c), unit(fb.at, c)); + let (a0, a1) = (angle([-na[0], -na[1]]), angle([-nb[0], -nb[1]])); + (a0, sweep_toward(a0, a1, angle([-c[0], -c[1]]))) +} + +/// The signed sweep from angle a0 to a1 that passes the direction `toward`. +fn sweep_toward(a0: f64, a1: f64, toward: f64) -> f64 { + let tau = 2.0 * std::f64::consts::PI; + let ccw = (a1 - a0).rem_euclid(tau); + let mid = (toward - a0).rem_euclid(tau); + if mid <= ccw { + ccw + } else { + ccw - tau + } +} + +/// One side of a round: the path from the corner to its tangent point on the paved side, and the +/// band layers' outer offsets past the carriageway's edge there. +struct Side { + path: Vec<[f64; 2]>, + w: [f64; LAYERS], +} + +/// The band rings of a round about c of radius rho, its arc from angle a0 turning `sweep`: per layer +/// (paved shoulder, shoulder, verge, slope), the arc at an offset that runs from the first side's own +/// band to the second side's, so each end meets its side's band smoothly and a band that one side +/// lacks tapers out along the arc. None for a layer no wider than +/// the layer inside it on both sides, or as wide as the round. +fn band_rings(c: [f64; 2], rho: f64, a0: f64, sweep: f64, sides: [&Side; 2]) -> [Option>; LAYERS] { + let [a, b] = sides; + // Each layer's own width past the layer inside it, per side. + let own = |s: &Side, k: usize| (s.w[k] - if k == 0 { 0.0 } else { s.w[k - 1] }).max(0.0); + // The width of a layer at the share t of the arc: a cubic with no slope at a side that has the + // layer (it meets that band's edge smoothly) and the straight slope at a side that has none (a + // taper with an angle). + let width = |k: usize, t: f64| { + let (wa, wb) = (own(a, k), own(b, k)); + let (ma, mb) = (if wa > 0.0 { 0.0 } else { wb - wa }, if wb > 0.0 { 0.0 } else { wb - wa }); + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * wa + (t3 - 2.0 * t2 + t) * ma + (-2.0 * t3 + 3.0 * t2) * wb + (t3 - t2) * mb + }; + std::array::from_fn(|k| { + let outer = a.w[k].max(b.w[k]); + if outer <= 0.0 || rho - outer < INSET || (own(a, k) <= 0.0 && own(b, k) <= 0.0) { + return None; + } + let at = |phi: f64| { + let t = ((phi - a0) / sweep).clamp(0.0, 1.0); + let r = rho - (0..=k).map(|j| width(j, t)).sum::(); + [c[0] + r * libm::cos(phi), c[1] + r * libm::sin(phi)] + }; + let mut ring = a.path.clone(); + ring.push(at(a0)); + ring.extend(arc_angles(a0, sweep).into_iter().map(at)); + ring.push(at(a0 + sweep)); + ring.extend(b.path.iter().rev()); + Some(ring) + }) +} + +/// The fills between the square ends of a point's arms where two neighbouring arms open by half a +/// turn or more: a fan about the point from one arm's corner to the other's, built from the strokes' +/// own corner points. An arm whose square end lies inside the other arms' layer is no neighbour: it +/// splits no gap between them. +fn fill_gaps(lines: &[WayLine], pos: P, arms: &[Arm], layer: usize, out: &mut Vec>) { + let tau = 2.0 * std::f64::consts::PI; + let cuts = cuts(lines, arms); + let by: Vec<(f64, [f64; 2], [f64; LAYERS + 1], Arm)> = arms + .iter() + .filter_map(|&a| { + let line = &lines[a.line]; + let next = line.p.get(a.at.checked_add_signed(isize::from(a.dir))?)?; + let u = unit_of(pos, *next)?; + Some((libm::atan2(u[1], u[0]), u, line.offsets(a.at), a)) + }) + .collect(); + let inside = |q: [f64; 2], k: usize| { + let (u, w) = (by[k].1, by[k].2[layer]); + q[0] * u[0] + q[1] * u[1] > 1.0 && (q[0] * u[1] - q[1] * u[0]).abs() < w - 1.0 + }; + let buried: Vec = (0..by.len()) + .map(|k| { + let (n, w) = (left_of(by[k].1), by[k].2[layer]); + [1.0, -1.0].iter().all(|&side| { + let q = [side * w * n[0], side * w * n[1]]; + (0..by.len()).any(|j| j != k && inside(q, j)) + }) + }) + .collect(); + let mut by: Vec<_> = by.iter().zip(&buried).filter(|(_, &b)| !b).map(|(a, _)| *a).collect(); + by.sort_by(|x, y| x.0.total_cmp(&y.0)); + for k in 0..by.len() { + let (a, b) = (by[k], by[(k + 1) % by.len()]); + let sector = if by.len() == 1 { tau } else { (b.0 - a.0).rem_euclid(tau) }; + // A way that runs on through the point joins its own segments. + let through = a.3.line == b.3.line && a.3.at == b.3.at; + if sector < std::f64::consts::PI || through { + continue; + } + let (na, nb) = (left_of(a.1), left_of(b.1)); + let (wa, wb) = (a.2[layer], b.2[layer]); + // A band no wider than the layer inside it on both arms is none. + if layer > 0 && wa <= a.2[layer - 1] && wb <= b.2[layer - 1] { + continue; + } + let sweep = sector - std::f64::consts::PI; + if sweep >= tau / f64::from(STEPS) { + pie_between(pos, wa, wb, na, [-nb[0], -nb[1]], sweep, [&cuts, &cuts], out); + continue; + } + // A gap under one arc step: each arm's layers up to the gap's bisector. A taper over so + // small a turn would be a needle. + let (c, s) = (libm::cos(sweep / 2.0), libm::sin(sweep / 2.0)); + let mid = [c * na[0] - s * na[1], s * na[0] + c * na[1]]; + pie_between(pos, wa, wa, na, mid, sweep / 2.0, [&cuts, &cuts], out); + pie_between(pos, wb, wb, mid, [-nb[0], -nb[1]], sweep / 2.0, [&cuts, &cuts], out); + } +} + +/// The layer offsets of all arms of a point, ascending: every square end at the point and every +/// side of a gap between its arms passes their corners, so two ends on one line, or a gap side and +/// an end, share their vertices. +pub fn cuts(lines: &[WayLine], arms: &[Arm]) -> Vec { + let mut all: Vec = arms.iter().flat_map(|a| lines[a.line].offsets(a.at)).collect(); + all.sort_by(f64::total_cmp); + all.dedup(); + all +} + +/// The rounding of a point at `pos` with its arms, the arm length `len` (units) and the pairs (a, b, +/// r, tol) of neighbouring arms, a turning counter-clockwise to b through their sector (at a way's +/// own turn, the inner side), with the radius and how far the round may cut into the arms' strokes. +/// With `gaps`, a fill between square ends of arms that open by half a turn or more (junctions and +/// joints). +#[allow(clippy::too_many_arguments)] +pub fn round( + lines: &[WayLine], + stops: &[Vec], + pos: P, + arms: &[Arm], + pairs: &[(usize, usize, f64, f64)], + len: f64, + gaps: bool, +) -> Rounded { + let runs: Vec> = arms + .iter() + .map(|&a| { + let own: Vec = stops[a.line].iter().copied().filter(|&s| s != a.at).collect(); + run(&lines[a.line], a, pos, len, &own) + }) + .collect(); + let mut out = Rounded { + fans: Vec::new(), + rings: Default::default(), + region: Vec::new(), + spans: Vec::new(), + seams: vec![None; arms.len()], + circles: Vec::new(), + runs: Vec::new(), + far: vec![0.0; arms.len()], + }; + if runs.iter().any(|r| r.len() < 2) { + return out; + } + let abs = |q: [f64; 2]| [pos[0] + libm::round(q[0]) as i32, pos[1] + libm::round(q[1]) as i32]; + let heading = |k: usize| angle(unit(runs[k][0].q, runs[k][1].q)); + let mut far = vec![0.0f64; arms.len()]; + if gaps { + fill_gaps(lines, pos, arms, 0, &mut out.fans); + for (k, ring) in out.rings.iter_mut().enumerate() { + fill_gaps(lines, pos, arms, k + 1, ring); + } + } + // A round lies off every carriageway: its arms' runs, and the other lines but for those runs. + let own: Vec<(usize, f64, f64)> = (runs.iter().zip(arms)) + .map(|(r, a)| { + let (x0, x1) = (r[0].x, r[r.len() - 1].x); + (a.line, x0.min(x1), x0.max(x1)) + }) + .collect(); + // The gap fills about the point: a round where an arm's edge leaves them touches them. + let fills: Vec> = (out.fans.iter()) + .map(|r| r.iter().map(|p| [f64::from(p[0] - pos[0]), f64::from(p[1] - pos[1])]).collect()) + .collect(); + let off = |c: [f64; 2], rho: f64| { + let water = lines[arms[0].line].sec.water; + fills.iter().all(|f| to_ring(f, c).d >= rho - 1.0) && off_lines(lines, water, pos, &own, c, rho) + }; + let (tau, step) = (2.0 * std::f64::consts::PI, 2.0 * std::f64::consts::PI / f64::from(STEPS)); + for &(i, j, r, tol) in pairs { + // a turns counter-clockwise to b through the pair's sector: as given at a junction or a + // joint, the inner side at a way's own turn. + let (a, b) = + if gaps || (heading(j) - heading(i)).rem_euclid(tau) <= std::f64::consts::PI { (i, j) } else { (j, i) }; + // Under half a turn the arms' carriageways meet; past it a gap fill or the stroke's own join + // lies between them, and only an arm's edge that leaves a fill has a corner. + let open = (heading(b) - heading(a)).rem_euclid(tau) < std::f64::consts::PI; + let through = arms[a].line == arms[b].line && arms[a].at == arms[b].at; + if !open && (through || !gaps) { + continue; + } + let corner = if open { crossings(&runs[a], &runs[b], 0.0).first().map(|&(_, k)| k) } else { None }; + if let Some(k) = corner { + far[a] = far[a].max(foot(&runs[a], k).s); + far[b] = far[b].max(foot(&runs[b], k).s); + } + let leaves = |rho: f64| { + leave(&runs, &fills, a, 1.0, rho, tol, &off).or_else(|| leave(&runs, &fills, b, -1.0, rho, tol, &off)) + }; + if r < MIN_RADIUS { + // A pair of no radius keeps its sharp corner: a circle of radius 0 there. + if let Some(k) = corner.or_else(|| leaves(2.0 * TOUCH).map(|l| l.touch.at)).filter(|_| r == 0.0) { + out.circles.push(Circle::sharp(abs(k))); + } + continue; + } + // Facing edges that cross make the corner; else one arm's edge leaves the other pieces. + // An arc that faced its corner over half a turn or more would pave a disc past the point. + let fit = |rho: f64| match corner { + Some(_) => round_at(&runs, a, b, rho, tol, &off) + .filter(|(c, fa, fb)| facing(*c, fa, fb).1.abs() < std::f64::consts::PI) + .map(|(c, fa, fb)| Fit::Edges(c, fa, fb)), + None => leaves(rho).map(Fit::Leaves), + }; + let Some((rho, fit)) = ladder(r).find_map(|rho| fit(rho).map(|f| (rho, f))) else { continue }; + let (c, fa, fb) = match fit { + Fit::Edges(c, fa, fb) => (c, fa, fb), + Fit::Leaves(l) => { + if let Some((fan, a0, sweep)) = leave_fan(&runs, &l, rho) { + far[l.k] = far[l.k].max(l.foot.s); + if let Some((j, s)) = l.touch.arm { + far[j] = far[j].max(s); + } + let lines = [arms[l.k].line, l.touch.arm.map_or(usize::MAX, |(j, _)| arms[j].line)]; + out.circles.push(Circle::new(&abs, l.c, rho, a0, sweep).at_edges(lines)); + push_positive(fan.iter().map(|&q| abs(q)).collect(), &mut out.fans); + } + continue; + } + }; + // The arc faces the point. A corner that turns less than one arc step stays sharp, as the + // strokes mitre such a join. + let (a0, sweep) = facing(c, &fa, &fb); + let (na, nb) = (unit(fa.at, c), unit(fb.at, c)); + if sweep.abs() < step { + continue; + } + far[a] = far[a].max(fa.s); + far[b] = far[b].max(fb.s); + out.circles.push(Circle::new(&abs, c, rho, a0, sweep).at_edges([arms[a].line, arms[b].line])); + let side_a = up_to(&runs[a], fa.s); + let side_b = up_to(&runs[b], fb.s); + let mut fan: Vec<[f64; 2]> = side_a.clone(); + let edge_point = |f: &Foot, n: [f64; 2], d: f64| [f.at[0] + d * n[0], f.at[1] + d * n[1]]; + fan.push(edge_point(&fa, na, fa.h - INSET)); + fan.extend(arc(c, rho, a0, sweep)); + fan.push(edge_point(&fb, nb, fb.h - INSET)); + fan.extend(side_b.iter().rev()); + push_positive(fan.iter().map(|&q| abs(q)).collect(), &mut out.fans); + let side = |path: Vec<[f64; 2]>, f: &Foot| Side { path, w: std::array::from_fn(|k| f.bands[k] - f.h) }; + let rings = band_rings(c, rho, a0, sweep, [&side(side_a, &fa), &side(side_b, &fb)]); + for (k, ring) in rings.into_iter().enumerate() { + if let Some(ring) = ring { + push_positive(ring.iter().map(|&q| abs(q)).collect(), &mut out.rings[k]); + } + } + } + // An arm belongs to the point's face as far as a fan of the point lies over its carriageway: a + // fan of two other arms can reach over an arm that runs close beside one of them. + for fan in &out.fans { + for &v in fan { + let q = [f64::from(v[0] - pos[0]), f64::from(v[1] - pos[1])]; + for (k, run) in runs.iter().enumerate() { + let f = foot(run, q); + if f.s > 0.0 && f.dist < f.h - INSET { + far[k] = far[k].max(f.s); + } + } + } + } + out.far = far; + out.runs = runs; + out +} + +/// The round at a corner `v` of the paved outline: the circle tangent to the outline's edge before +/// the corner (`back`, walked backward from it, the land on its left) and the edge after it (`ahead`, +/// the land on its right), off the paved area (`off`), with its feet within `reach` along the edges, +/// of radius r or the first of the ladder that fits, with the way and the band offsets of the edge at a +/// point (`edge`). Its ring: the corner, the edges to the feet and +/// the arc between, with the corner and edges `FILL_INSET` units into the paved side, so its sides +/// run inside the paved area and leave no sliver beside its edges. None where the arc would turn +/// less than one arc step. +#[allow(clippy::too_many_arguments)] +pub fn corner_round( + v: P, + back: &[P], + ahead: &[P], + r: f64, + tol: f64, + reach: f64, + off: &dyn Fn([f64; 2], f64) -> bool, + edge: &dyn Fn([f64; 2]) -> (usize, [f64; LAYERS]), +) -> Option { + let bands = |q: [f64; 2]| edge(q).1; + let run = |chain: &[P]| -> Vec { + (chain.iter().enumerate()) + .map(|(k, p)| RunPoint { + x: k as f64, + q: [f64::from(p[0] - v[0]), f64::from(p[1] - v[1])], + h: 0.0, + bands: [0.0; LAYERS], + }) + .collect() + }; + let runs = [run(back), run(ahead)]; + if runs.iter().any(|r| r.len() < 2) { + return None; + } + // The arc faces the corner and turns less than half a turn: the land between two edges that + // meet at a corner is narrower than a half plane. A circle may cut into the edges by `tol` (their + // chords leave the curve by as much), at most a quarter of its radius: an edge then crosses the + // circle within 41° (acos 0.75) of its tangent. + let arc_of = |rho: f64| { + let (c, fa, fb) = round_at(&runs, 0, 1, rho, tol.min(rho / 4.0), off)?; + if fa.s > reach || fb.s > reach { + return None; + } + let (a0, a1) = (angle([fa.at[0] - c[0], fa.at[1] - c[1]]), angle([fb.at[0] - c[0], fb.at[1] - c[1]])); + let sweep = sweep_toward(a0, a1, angle([-c[0], -c[1]])); + (sweep.abs() < std::f64::consts::PI).then_some((rho, c, fa, fb, a0, sweep)) + }; + let (rho, c, fa, fb, a0, sweep) = ladder(r).find_map(arc_of)?; + if sweep.abs() < 2.0 * std::f64::consts::PI / f64::from(STEPS) { + return None; + } + // Each edge to its foot, moved `FILL_INSET` units into the paved side along its normals: the + // land lies on the left of `back` and on the right of `ahead`. + let side = |chain: Vec<[f64; 2]>, land: f64| -> Vec<[f64; 2]> { + let normal = |a: [f64; 2], b: [f64; 2]| { + let n = left(unit(a, b)); + [-land * n[0], -land * n[1]] + }; + let m = chain.len(); + (1..m) + .map(|k| { + let n0 = normal(chain[k - 1], chain[k]); + let n = if k + 1 < m { mean(n0, normal(chain[k], chain[k + 1])) } else { n0 }; + [chain[k][0] + FILL_INSET * n[0], chain[k][1] + FILL_INSET * n[1]] + }) + .collect() + }; + let (a_side, b_side) = (side(up_to(&runs[0], fa.s), 1.0), side(up_to(&runs[1], fb.s), -1.0)); + let at = |q: [f64; 2]| [f64::from(v[0]) + q[0], f64::from(v[1]) + q[1]]; + let first = |run: &[RunPoint], land: f64| { + let n = left(unit(run[0].q, run[1].q)); + [-land * n[0], -land * n[1]] + }; + let nv = mean(first(&runs[0], 1.0), first(&runs[1], -1.0)); + let corner = [FILL_INSET * nv[0], FILL_INSET * nv[1]]; + // The band rings about the arc, at the band offsets of the edges at the feet, as a point's round + // has them. + let edge_side = |path: &[[f64; 2]], f: &Foot| { + let mut path = path.to_vec(); + path.insert(0, corner); + Side { path, w: bands(at(f.at)) } + }; + let band = band_rings(c, rho, a0, sweep, [&edge_side(&a_side, &fa), &edge_side(&b_side, &fb)]); + let mut ring = vec![corner]; + ring.extend(a_side); + ring.extend(arc(c, rho, a0, sweep)); + ring.extend(b_side.into_iter().rev()); + let abs = |q: [f64; 2]| [v[0] + libm::round(q[0]) as i32, v[1] + libm::round(q[1]) as i32]; + let mut pts: Vec

= ring.iter().map(|&q| abs(q)).collect(); + pts.dedup(); + let mut rings = Vec::new(); + push_positive(pts, &mut rings); + // The label comes from the face along the edge before the corner, halfway to its foot: at the + // corner itself faces of other ways can meet. + let inside = edge_at(&runs[0], fa.s / 2.0, -1.0, 2.0 * FILL_INSET); + let abs_ring = |ring: Vec<[f64; 2]>| { + let mut out = Vec::new(); + push_positive(ring.iter().map(|&q| abs(q)).collect(), &mut out); + out + }; + Some(super::outline::Fill { + ring: rings.pop()?, + bands: band.map(|ring| ring.map(abs_ring).unwrap_or_default()), + circle: Circle::new(&abs, c, rho, a0, sweep).at_edges([&fa, &fb].map(|f| edge(at(f.at)).0)), + inside: [ + 2 * i64::from(v[0]) + libm::round(2.0 * inside[0]) as i64, + 2 * i64::from(v[1]) + libm::round(2.0 * inside[1]) as i64, + ], + }) +} + +/// The region of a junction or joint: per arm, a stub round about the point up to its seam, `seam` +/// units past the farthest foot on the arm or at the seam it shares with the next point (`shared`). +/// A seam is a straight cut across the arm, square to the run's own direction there. +pub fn region(pos: P, arms: &[Arm], r: &mut Rounded, seam: f64, shared: &[Option]) { + let abs = |q: [f64; 2]| [pos[0] + libm::round(q[0]) as i32, pos[1] + libm::round(q[1]) as i32]; + for (k, run) in r.runs.iter().enumerate() { + let s = match shared[k] { + Some(sm) => station(run, sm.x), + None => (r.far[k] + seam).min(length(run)), + }; + let rel = up_to(run, s); + let mut stub: Vec

= rel.iter().map(|&q| abs(q)).collect(); + let mut d: Vec = rel.iter().map(|&q| foot(run, q).h + STUB_PAD).collect(); + let mut dirs: Vec> = rel.windows(2).map(|w| Some(unit(w[0], w[1]))).collect(); + let mut x = place(run, s); + if let Some(sm) = shared[k] { + // The shared cut: the same end point, half-length and direction from both points. + let dir = f64::from(arms[k].dir); + stub.pop(); + d.pop(); + dirs.pop(); + if stub.last() == Some(&sm.p) { + stub.pop(); + d.pop(); + dirs.pop(); + } + stub.push(sm.p); + d.push(sm.w); + dirs.push(Some([dir * sm.u[0], dir * sm.u[1]])); + x = sm.x; + } + if stub.len() < 2 { + continue; + } + pieces_along(&stub, &d, &dirs, [&[], &[]], [true, false], false, &mut r.region); + let (end, n) = (stub[stub.len() - 1], left(dirs.last().copied().flatten().unwrap_or([1.0, 0.0]))); + let w = d[d.len() - 1]; + let cut = [off(end, w, [-n[0], -n[1]]), off(end, w, n)]; + r.seams[k] = Some(cut); + let (line, at) = (arms[k].line, run[0].x); + r.spans.push(match x > at { + true => Part { line, lo: at, hi: x, cuts: [None, Some(cut)] }, + false => Part { line, lo: x, hi: at, cuts: [Some(cut), None] }, + }); + } + r.spans.sort_by(|a, b| (a.line, a.lo).partial_cmp(&(b.line, b.lo)).unwrap()); + r.spans.dedup_by(|b, a| { + let joins = a.line == b.line && b.lo <= a.hi; + if joins && b.hi > a.hi { + a.hi = b.hi; + a.cuts[1] = b.cuts[1]; + } + joins + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_sweep_toward_a_direction_takes_the_arc_through_it() { + let q = std::f64::consts::FRAC_PI_2; + assert!((sweep_toward(0.0, q, q / 2.0) - q).abs() < 1e-12); + assert!((sweep_toward(0.0, q, -q) - (q - 4.0 * q)).abs() < 1e-12); + } + + #[test] + fn segments_cross_inside_both() { + let x = crossing([0.0, 0.0], [2.0, 0.0], [1.0, -1.0], [1.0, 1.0]).unwrap(); + assert_eq!(x, (0.5, 0.5)); + assert!(crossing([0.0, 0.0], [2.0, 0.0], [3.0, -1.0], [3.0, 1.0]).is_none()); + } +} diff --git a/host/obc-ground-plan/src/faces/records/check.rs b/host/obc-ground-plan/src/faces/records/check.rs new file mode 100644 index 0000000000..a0906fa811 --- /dev/null +++ b/host/obc-ground-plan/src/faces/records/check.rs @@ -0,0 +1,657 @@ +//! The checks of a cell's records: the label of sampled points against the face plan's, the far +//! level against the near one, the far block against the near records, and two cells on their shared +//! line by global names: the labels and the blend edges near each point. + +use std::collections::{BTreeMap, BTreeSet}; + +use super::far::{MAGIC_FAR, MASK_M, PAD, WINDOW}; +use super::{ + blend_edges, find, label, outline_units, BINS, BIN_UNITS, CAND, CEILING, DISC, HEAD, JUNCTION, LEG_SHIFT, LINE, + MARGIN_M, PLATFORM, RAIL, SAMPLE, WATER, WAY, WAY_OWNER, +}; +use crate::faces::check::owner_name; +use crate::faces::geom::winding; +use crate::faces::heights::HeightRules; +use crate::faces::{candidates, decide, Candidates, FacePlan, Label, Owner, Rules, Surface, LAYERS, SLOPE}; +use crate::frame::{metres_per_unit, metres_per_unit_at, CellKey, CELL_UNITS}; +use crate::graph::WayGraph; +use crate::CellInput; + +/// A label as surface, owner kind, rank and rule; owner id; material way; crossing way. Terrain is +/// all zero. +pub type Name = [u32; 4]; + +const TERRAIN: Name = [0, 0, u32::MAX, u32::MAX]; + +/// Two cells' distances to a blend edge agree within this, in units. An edge that the two cells split +/// at different vertices past `MARGIN_M` snaps to a different path in each; each path stays in the +/// snap squares of the exact edge, which span up to 2 · PRECISION at the cell lines, so within +/// √2 · PRECISION of it, possibly on opposite sides. +const BLEND_TOL: f64 = 2.0 * std::f64::consts::SQRT_2 * crate::faces::slice::PRECISION as f64; + +/// The arc steps of the overlay's polygons: 10°. +const STEP: f64 = std::f64::consts::PI / 18.0; + +/// The name of label `id` of a block, its lines as ways. +pub fn records_name(words: &[u32], id: Option) -> Name { + let Some(l) = id.map(|id| label(words, id)) else { return TERRAIN }; + if l[0] & 0xff == Surface::Terrain as u32 { + return TERRAIN; + } + let way = |line: u32| if line == u32::MAX { u32::MAX } else { words[words[6] as usize + LINE * line as usize] }; + [l[0], super::owner(words, id.unwrap()), way(l[2]), way(l[3])] +} + +fn name(l: &Label) -> Name { + if l.surface == Surface::Terrain { + return TERRAIN; + } + let w = super::label_words(l); + [w[0], w[1], w[2], w[3]] +} + +fn face_name(plan: &FacePlan, face: Option) -> Name { + face.map_or(TERRAIN, |k| name(&Label::of(&plan.faces[k]))) +} + +/// The overlay's decision at one point, as the overlay reads it at a patch's inner point. +pub struct Overlay<'a>(Candidates<'a>); + +impl<'a> Overlay<'a> { + pub fn new(graph: &'a WayGraph, input: &CellInput, rules: &'a Rules, cell: CellKey, slopes: bool) -> Self { + Overlay(candidates(graph, input, rules, cell, 0, if slopes { LAYERS } else { SLOPE }, true)) + } + + /// The name of the overlay's label at q, a point on the half-unit grid. + pub fn name(&self, q: [f64; 2]) -> Name { + let d = [(2.0 * q[0]) as i64, (2.0 * q[1]) as i64]; + name(&decide(&self.0.cands, &self.0.lines, self.0.cover.at(d), d)) + } +} + +/// The faces of a plan by bin, for the face at a point. +struct Index<'a> { + plan: &'a FacePlan, + rings: Vec>>, + bins: Vec>, + /// The edges between two names by bin, grown by `grow` units. + edges: Vec>, + names: Vec, +} + +fn bin_range(lo: i32, hi: i32, grow: i32) -> std::ops::RangeInclusive { + ((lo - grow).div_euclid(BIN_UNITS)).max(0)..=((hi + grow).div_euclid(BIN_UNITS)).min(BINS - 1) +} + +impl<'a> Index<'a> { + fn new(plan: &'a FacePlan, grow: i32) -> Self { + let n = (BINS * BINS) as usize; + let rings: Vec>> = (plan.faces.iter()) + .map(|f| f.rings.iter().map(|r| r.iter().map(|&v| plan.vertices[v as usize]).collect()).collect()) + .collect(); + let mut bins = vec![Vec::new(); n]; + for (k, r) in rings.iter().enumerate() { + let (lo, hi) = r[0].iter().fold(([i32::MAX; 2], [i32::MIN; 2]), |(lo, hi), p| { + ([lo[0].min(p[0]), lo[1].min(p[1])], [hi[0].max(p[0]), hi[1].max(p[1])]) + }); + for row in bin_range(lo[1], hi[1], 0) { + for col in bin_range(lo[0], hi[0], 0) { + bins[(row * BINS + col) as usize].push(k); + } + } + } + let names: Vec = (0..plan.faces.len()).map(|k| face_name(plan, Some(k))).collect(); + let mut edges = vec![Vec::new(); n]; + for (i, e) in plan.edges.iter().enumerate() { + let name = |f: u32| names.get(f as usize).copied().unwrap_or(TERRAIN); + if name(e.left) == name(e.right) { + continue; + } + let (a, b) = (plan.vertices[e.a as usize], plan.vertices[e.b as usize]); + for row in bin_range(a[1].min(b[1]), a[1].max(b[1]), grow) { + for col in bin_range(a[0].min(b[0]), a[0].max(b[0]), grow) { + edges[(row * BINS + col) as usize].push(i); + } + } + } + Index { plan, rings, bins, edges, names } + } + + fn bin(q: [f64; 2]) -> usize { + let b = |v: f64| ((v / f64::from(BIN_UNITS)).floor() as i32).clamp(0, BINS - 1); + (b(q[1]) * BINS + b(q[0])) as usize + } + + /// The name of the face at q, a point on the half-unit grid off the vertices. + fn name(&self, q: [f64; 2]) -> Name { + let d = [(2.0 * q[0]) as i64, (2.0 * q[1]) as i64]; + let face = self.bins[Self::bin(q)].iter().copied().find(|&k| winding(&self.rings[k], d) != 0); + face.map_or(TERRAIN, |k| self.names[k]) + } + + /// The distance in units from q to the nearest edge between two names, up to the index's growth. + fn to_edge(&self, q: [f64; 2]) -> f64 { + let p = |v: u32| self.plan.vertices[v as usize].map(f64::from); + (self.edges[Self::bin(q)].iter()) + .map(|&i| seg_dist(p(self.plan.edges[i].a), p(self.plan.edges[i].b), q)) + .fold(f64::INFINITY, f64::min) + } +} + +fn seg_dist(a: [f64; 2], b: [f64; 2], q: [f64; 2]) -> f64 { + let u = [b[0] - a[0], b[1] - a[1]]; + let t = (((q[0] - a[0]) * u[0] + (q[1] - a[1]) * u[1]) / (u[0] * u[0] + u[1] * u[1]).max(1e-12)).clamp(0.0, 1.0); + libm::hypot(q[0] - a[0] - t * u[0], q[1] - a[1] - t * u[1]) +} + +/// Whether q lies inside a disc of the block's candidates, between the circle and its chords of +/// one arc step, rounded to units: where the records' true arc and the overlay's polygon differ. +fn on_arc(words: &[u32], q: [f64; 2]) -> bool { + let extras = &words[words[8] as usize..]; + (0..words[1] as usize).any(|ci| { + let k = &words[words[4] as usize + CAND * ci..][..CAND]; + (0..k[6] as usize).any(|d| { + let e = &extras[k[5] as usize + DISC * d..]; + let r = f64::from(f32::from_bits(e[2])); + let to = libm::hypot(q[0] - f64::from(e[0] as i32), q[1] - f64::from(e[1] as i32)); + to < r && to >= r * libm::cos(STEP / 2.0) - 1.0 + }) + }) +} + +/// A sampled point where the records' label differs from the face's. +#[derive(Clone, Debug)] +pub struct Miss { + pub q: [f64; 2], + pub face: Name, + pub records: Name, + /// The distance to the nearest edge between two names, in units. + pub edge: f64, +} + +#[derive(Clone, Debug, Default)] +pub struct Agreement { + pub points: u64, + /// Misses within `edge_units` of an edge between two names. + pub edge: u64, + /// Misses between a disc's circle and its chords. + pub arc: u64, + /// Misses where `find` gives the overlay's decision at the point, and the overlay gives the + /// patch the decision at its inner point: past a cut where the slice holds only a part of it, + /// and the rail bed beside a road (the rule of `faces::label`). Of them, the rail beds. + pub patch: u64, + pub rail: u64, + /// The other misses: faults of the records. + pub area: Vec, +} + +/// The sample points of the bins with a candidate item: `n`² points of each on the half-unit grid. +/// A bin with none holds no edge of a candidate, so its points are terrain. +fn samples(words: &[u32], n: i32) -> impl Iterator + '_ { + let at = move |i: i32, base: i32| f64::from(base * BIN_UNITS + (2 * i + 1) * BIN_UNITS / (2 * n)) + 0.5; + (0..BINS * BINS) + .filter(move |&b| words[words[9] as usize + super::HEADER * b as usize + 1] >> 16 > 0) + .flat_map(move |b| (0..n * n).map(move |k| [at(k % n, b % BINS), at(k / n, b / BINS)])) +} + +/// The records' labels against the plan's faces at n² points of every bin with a candidate: a miss +/// within `edge_units` of an edge between two names, between a round's circle and its chords, or +/// where `find` is the overlay's own decision at the point, is counted; any other is listed. +pub fn agreement(words: &[u32], plan: &FacePlan, overlay: &Overlay, n: i32, edge_units: f64) -> Agreement { + let index = Index::new(plan, edge_units.ceil() as i32); + let mut out = Agreement::default(); + for q in samples(words, n) { + out.points += 1; + let (face, records) = (index.name(q), records_name(words, find(words, q))); + if face == records { + continue; + } + let edge = index.to_edge(q); + if edge < edge_units { + out.edge += 1; + } else if on_arc(words, q) { + out.arc += 1; + } else if overlay.name(q) == records { + out.patch += 1; + out.rail += u64::from(face[0] & 0xff == Surface::RailBed as u32); + } else { + out.area.push(Miss { q, face, records, edge }); + } + } + out +} + +/// The far level against the near one at n² points of every bin: the points whose near label is no +/// band layer and no water, and of them those whose far label differs. +pub fn far_agreement(near: &[u32], far: &[u32], n: i32) -> [u64; 2] { + let band = [Surface::Shoulder, Surface::Verge, Surface::Bank, Surface::Slope, Surface::Water, Surface::Zone] + .map(|s| s as u32); + let mut count = [0u64; 2]; + // By name: the far block numbers its junction records without the water's. + for q in samples(near, n) { + let a = records_name(near, find(near, q)); + if band.contains(&(a[0] & 0xff)) { + continue; + } + count[0] += 1; + count[1] += u64::from(records_name(far, find(far, q)) != a); + } + count +} + +/// The far block against the near records of one build (`far`). Its head and rules are the near +/// block's; its record lines are a subsequence of the near ones, matched by way and leg, with every +/// leg of a kept way and every word but the first sample and the count; its samples are a run of the +/// near line's, every word but 4 equal, and word 4 keeps their order; a key is the near way +/// candidate's. The far block holds no water. Every segment of every near way leg that reaches the cell a unit within its line's reach +/// (`reach` of `far`, read from the near words) has its leg in the far block, with every sample in its +/// run that its stroke and `h_segment` read; and `h_segment`'s branches there are the full leg's. The +/// faults, and the counts of what the check saw. +pub fn far_matches_near(near: &[u32], far: &[u32], cell: CellKey) -> (Vec, BTreeMap<&'static str, usize>) { + let mut faults = Vec::new(); + let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new(); + let rules = HEAD + crate::faces::heights::RULES; + let len = far.len() as u32; + let lines_end = (rules + LINE * far[3] as usize) as u32; + let head = [MAGIC_FAR, 0, 0, far[3], rules as u32, rules as u32, rules as u32, lines_end, far[8], far[9], near[10]]; + if far[..11] != head + || [far[11], far[12], far[13], far[14]] != [len, len, 0, len] + || far[HEAD..rules] != near[HEAD..rules] + { + return (vec![format!("the head {:?} or the rules differ", &far[..HEAD])], counts); + } + let line = |w: &[u32], l: usize| -> Vec { w[w[6] as usize + LINE * l..][..LINE].to_vec() }; + let sample = |w: &[u32], ln: &[u32], i: usize| -> Vec { + w[w[7] as usize + SAMPLE * (ln[2] as usize + i)..][..SAMPLE].to_vec() + }; + let id = |ln: &[u32]| (ln[0], ln[1] >> LEG_SHIFT); + let (n_near, n_far) = (near[3] as usize, far[3] as usize); + let n_samples = (far[8] - far[7]) as usize / SAMPLE; + if !((far[8] - far[7]) as usize).is_multiple_of(SAMPLE) + || far[9] - far[8] != far[3] + || (len - far[9]) as usize != 2 * n_samples + { + faults.push(format!( + "{n_far} lines and {n_samples} samples, but {} keys and {} sides", + far[9] - far[8], + len - far[9] + )); + } + counts.insert("lines", n_far); + counts.insert("samples", n_samples); + let keys: BTreeMap = (0..near[1] as usize) + .map(|ci| &near[near[4] as usize + CAND * ci..][..CAND]) + .filter(|c| c[0] == WAY) + .map(|c| (c[4], c[1])) + .collect(); + // Per near line matched by a far line: the far line's count of samples and its run's offset. + let mut runs: BTreeMap)> = BTreeMap::new(); + let (mut ways, mut order) = (BTreeSet::new(), Vec::new()); + let (mut at, mut first) = (0, 0u32); + for l in 0..n_far { + let fl = line(far, l); + let Some(k) = (at..n_near).find(|&k| id(&line(near, k)) == id(&fl)) else { + faults.push(format!("far line {l} (way {}, leg {}) follows no later near line", fl[0], fl[1] >> LEG_SHIFT)); + break; + }; + at = k + 1; + let nl = line(near, k); + ways.insert(fl[0]); + if (0..LINE).any(|w| w != 2 && w != 3 && fl[w] != nl[w]) || fl[2] != first { + faults.push(format!("far line {l}: {fl:?} against near line {k}: {nl:?}")); + } + first += fl[3]; + if keys.get(&(k as u32)).is_some_and(|&key| far[far[8] as usize + l] != key) { + faults.push(format!("far line {l}: key {:#x}, near {:#x}", far[far[8] as usize + l], keys[&(k as u32)])); + } + let (m, n) = (fl[3] as usize, nl[3] as usize); + let same = |i: usize, j: usize| { + let (a, b) = (sample(far, &fl, i), sample(near, &nl, j)); + (0..SAMPLE).all(|w| w == 4 || a[w] == b[w]) + }; + let a = (m > 0 && m <= n).then(|| (0..=n - m).find(|&a| (0..m).all(|i| same(i, a + i)))).flatten(); + if m > 0 && a.is_none() { + faults.push(format!("far line {l}: its {m} samples are no run of near line {k}")); + } + if let Some(a) = a { + order.extend((0..m).map(|i| (sample(far, &fl, i)[4], sample(near, &nl, a + i)[4]))); + } + runs.insert(k, (m, a)); + let ends = (n > 0).then(|| [sample(near, &nl, 0), sample(near, &nl, n - 1)]); + for (case, yes) in [ + ("rails", fl[1] & RAIL != 0), + ("empty", m == 0), + ("single", n == 2), + ("rings", n > 2 && ends.is_some_and(|[a, b]| a[..2] == b[..2])), + ] { + *counts.entry(case).or_default() += usize::from(yes); + } + } + if first as usize != n_samples { + faults.push(format!("the lines count {first} samples, the block holds {n_samples}")); + } + for k in (0..n_near).filter(|k| !runs.contains_key(k) && ways.contains(&line(near, *k)[0])) { + faults.push(format!("near line {k}: a leg of a kept way is missing")); + } + order.sort_unstable(); + if order.windows(2).any(|w| (w[0].0 == w[1].0) != (w[0].1 == w[1].1) || w[0].1 > w[1].1) { + faults.push("the samples' word 4 does not keep the near order".into()); + } + // A way's widest carriageway in metres over all its legs. + let origin = cell.origin(); + let mut half: BTreeMap = BTreeMap::new(); + for k in 0..n_near { + let nl = line(near, k); + for i in 0..nl[3] as usize { + let s = sample(near, &nl, i); + let m = f64::from(f32::from_bits(s[2])) * metres_per_unit(origin.y + i64::from(s[1] as i32)); + let h = half.entry(nl[0]).or_insert(0.0); + *h = h.max(m); + } + } + // Every near way leg: its segments in reach, and in the far block the samples that their strokes read. A + // ceiling line is no leg of storey 0. + let f32m = |w: u32| f64::from(f32::from_bits(w)); + let cell_u = f64::from(CELL_UNITS as i32); + for k in 0..n_near { + let nl = line(near, k); + if nl[1] & (WATER | CEILING) != 0 { + continue; + } + let n = nl[3] as usize; + let reach = half[&nl[0]] + (f32m(nl[8]) + f32m(nl[9]) + f32m(nl[6])).max(MASK_M) + 1.0; + let p = |i: usize| { + let s = sample(near, &nl, i); + [f64::from(s[0] as i32), f64::from(s[1] as i32)] + }; + let meets = |s: usize, r: f64| { + let (u, v) = (p(s), p(s + 1)); + (0..2).all(|k| u[k].min(v[k]) - r <= cell_u && u[k].max(v[k]) + r >= 0.0) + }; + let r = outline_units(cell, reach) - 1.0; + let in_reach: Vec = (0..n.saturating_sub(1)).filter(|&s| meets(s, r)).collect(); + if in_reach.is_empty() { + continue; + } + *counts.entry("in_reach").or_default() += in_reach.len(); + *counts.entry("twice").or_default() += usize::from(in_reach.windows(2).any(|w| w[1] > w[0] + 1)); + *counts.entry("touch").or_default() += usize::from(!in_reach.iter().any(|&s| meets(s, 0.0))); + let (m, a) = match runs.get(&k) { + Some(&(m, Some(a))) => (m, a), + Some(&(_, None)) => { + faults.push(format!("near line {k}: {} segments in reach, its far line holds none", in_reach.len())); + continue; + } + None => { + faults.push(format!("near line {k}: {} segments in reach, no far line", in_reach.len())); + continue; + } + }; + for s in in_reach { + if s.saturating_sub(PAD) < a || (s + PAD + 1).min(n - 1) >= a + m { + faults.push(format!("near line {k}: segment {s} in reach, its run {a}..{}", a + m)); + continue; + } + for j in s.saturating_sub(WINDOW)..=(s + WINDOW).min(n - 2) { + let b = |j: usize, n: usize| [j == 0, j + 2 == n, j > 0, j + 2 < n]; + if b(j, n) != b(j - a, m) { + faults.push(format!("near line {k}: h_segment of segment {j} takes other branches")); + } + } + } + } + (faults, counts) +} + +/// A cell for the border check: its records, its graph and its input's `feature_names`. +pub type Cell<'a> = (&'a [u32], &'a WayGraph, &'a [[u32; 3]]); + +/// The global name of the label at q of a cell: two cells number ways apart. +fn global_name(cell: Cell, q: [f64; 2]) -> String { + label_name(cell, find(cell.0, q), q) +} + +/// The global name of label `id` of a cell, its ways named near q. +fn label_name(cell: Cell, id: Option, q: [f64; 2]) -> String { + let (words, graph, features) = cell; + let o = graph.cell.origin(); + let near = [o.x + q[0] as i64, o.y + q[1] as i64]; + let n = records_name(words, id); + if n == TERRAIN { + return "terrain".into(); + } + let way = |w: u32| (w != u32::MAX).then(|| owner_name(graph, features, Owner::Way(w), near)); + let owner = match (n[0] >> 8) & 0xff { + WAY_OWNER => Owner::Way(n[1]), + JUNCTION => Owner::Junction(n[1]), + PLATFORM => Owner::Platform(n[1]), + _ => Owner::Terrain, + }; + format!("{} {} {:?} {:?}", n[0] & !0xff00, owner_name(graph, features, owner, near), way(n[2]), way(n[3])) +} + +/// The vertices of a block's candidate items on a cell line, as positions along it, and the count +/// of their edges along it: the line x = `at` (0 or the cell's size) for `vertical`, else y = `at`. +pub(crate) fn on_line(words: &[u32], vertical: bool, at: i32) -> (Vec, usize) { + let (mut out, mut edges) = (Vec::new(), 0); + let edge_bin = if at == 0 { 0 } else { BINS - 1 }; + for k in 0..BINS { + let (col, row) = if vertical { (edge_bin, k) } else { (k, edge_bin) }; + let head = words[9] as usize + super::HEADER * (row * BINS + col) as usize; + let mut p = words[head] as usize; + for _ in 0..words[head + 1] >> 16 { + let runs = words[p + 1]; + p += 2; + for _ in 0..runs { + let n = words[p] as usize; + let mut last = false; + for v in 0..n { + let (x, y) = (words[p + 1 + 2 * v] as i32, words[p + 2 + 2 * v] as i32); + let (on, along) = if vertical { (x, y) } else { (y, x) }; + let here = on == at && (0..=CELL_UNITS as i32).contains(&along); + if here { + out.push(along); + } + edges += usize::from(here && last); + last = here; + } + p += 1 + 2 * n; + } + } + } + (out, edges) +} + +/// Per pair of the blend face's label and the label beyond (global names), the least distance from q +/// to its blend edges that q's bin lists, if within `reach` units. Only these distances are the +/// neighbours' own: past `MARGIN_M` from the cell, an edge may end elsewhere. The distance takes q +/// from the ends first, so two cells measure alike. +fn blend_near(cell: Cell, q: [f64; 2], reach: f64) -> BTreeMap { + let mut out = BTreeMap::new(); + for e in blend_edges(cell.0, q) { + let d = |p: [i32; 2]| [f64::from(p[0]) - q[0], f64::from(p[1]) - q[1]]; + let dist = seg_dist(d(e.a), d(e.b), [0.0, 0.0]); + if dist <= reach { + let name = format!("{} | {}", label_name(cell, Some(e.region), q), label_name(cell, e.other, q)); + let least = out.entry(name).or_insert(dist); + *least = f64::min(*least, dist); + } + } + out +} + +/// Cell `b` east of `a` (`east`) or south of it, on their shared line by global names, at every +/// `step` units along it and at every vertex of either block on it and 1/1024 unit beside it: the +/// labels, and the blend edges within most of `MARGIN_M`, bit-equal below the heights' region fade. +/// The points read, those of them with a blend edge near, and the places where the two differ. +pub fn border(a: Cell, b: Cell, east: bool, step: i32) -> (u64, u64, Vec<(f64, String, String)>) { + let c = CELL_UNITS as i32; + let mut along: Vec = (0..=c / step).map(|k| f64::from(k * step)).collect(); + for v in on_line(a.0, east, c).0.into_iter().chain(on_line(b.0, east, 0).0) { + along.extend([f64::from(v) - 1.0 / 1024.0, f64::from(v), f64::from(v) + 1.0 / 1024.0]); + } + along.retain(|&s| (0.0..=f64::from(c)).contains(&s)); + along.sort_by(f64::total_cmp); + along.dedup(); + let at = |s: f64, on: f64| if east { [on, s] } else { [s, on] }; + // Each block lists the blend edges within `MARGIN_M` of a bin in its own units. + let units = |cell: Cell| MARGIN_M / metres_per_unit(cell.1.cell.origin().y + CELL_UNITS / 2); + let reach = 0.9 * units(a).min(units(b)); + let fade_m = HeightRules::of(a.0).region_fade_m; + let (mut blend, mut differ) = (0, Vec::new()); + for &s in &along { + let (p, q) = (at(s, f64::from(c)), at(s, 0.0)); + let (x, y) = (global_name(a, p), global_name(b, q)); + if x != y { + differ.push((s, x, y)); + } + // Both list each pair up to the tolerance past the reach, so a pair within the reach in one + // cell is in the other's list too. + let (x, y) = (blend_near(a, p, reach + BLEND_TOL), blend_near(b, q, reach + BLEND_TOL)); + blend += u64::from(!x.is_empty() || !y.is_empty()); + // The heights read a distance below the region fade: there both cells give the same bits. + let fade = fade_m / metres_per_unit_at((a.1.cell.origin().y as f64) + p[1]); + let alike = (x.keys().chain(y.keys())).all(|k| { + let (d, e) = (x.get(k).copied().unwrap_or(f64::INFINITY), y.get(k).copied().unwrap_or(f64::INFINITY)); + d.min(e) > reach || if d.min(e) < fade { d == e } else { (d - e).abs() <= BLEND_TOL } + }); + if !alike { + differ.push((s, format!("blend {x:?}"), format!("blend {y:?}"))); + } + } + (along.len() as u64, blend, differ) +} + +/// Two neighbouring cells' outline edges near their shared line, by global names: each edge of either +/// block within its host's listing reach (`outline_m`'s terms) of the other cell's square must be an +/// edge of the other block with the same words, its host line named by its class and its sample nearest +/// the edge (two cells number a way's legs from its own start). The edges compared, and the ones that +/// differ within `MARGIN_M` of the shared line and past it: only up to `MARGIN_M` past a cell are its +/// inputs the neighbours' own. An end's turn counts only within that listing reach of both cells: past it, +/// the end's cone reaches no point of that cell, and that cell may not hold the edge that goes on there. +pub fn outline_border(a: (&[u32], CellKey), b: (&[u32], CellKey)) -> (u64, [Vec; 2]) { + type Edge = ([i64; 4], [u32; 8], [i64; 3]); + let edges = |(w, key): (&[u32], CellKey)| -> Vec { + let o = key.origin(); + let line = |l: u32| &w[w[6] as usize + LINE * l as usize..][..LINE]; + super::outline_words(w) + .as_chunks::<{ super::EDGE }>() + .0 + .iter() + .map(|e| { + let (pa, pb) = super::edge_ends(e); + let g = [pa[0], pa[1], pb[0], pb[1]].map(i64::from); + let g = [g[0] + o.x, g[1] + o.y, g[2] + o.x, g[3] + o.y]; + let host = line(super::edge_line(e)); + let sample = |i: u32| &w[w[7] as usize + super::SAMPLE * (host[2] + i) as usize..][..2]; + let near = (0..host[3]) + .map(|i| [i64::from(sample(i)[0] as i32) + o.x, i64::from(sample(i)[1] as i32) + o.y]) + .min_by_key(|s| (s[0] - g[0]).pow(2) + (s[1] - g[1]).pow(2)) + .unwrap_or([0, 0]); + let name = [i64::from(host[7]), near[0], near[1]]; + (g, [e[3] >> 16, e[4], e[5], e[6], e[7], e[8] & 0xffff, e[9] & 0xffff, e[8] >> 16], name) + }) + .collect() + }; + let reach = |w: &[u32], l: u32| f64::from(f32::from_bits(w[w[6] as usize + LINE * l as usize + 6])); + let (ea, eb) = (edges(a), edges(b)); + let mut differ = [Vec::new(), Vec::new()]; + let mut checked = 0; + for ((from, from_edges), (to, to_edges)) in [((a, &ea), (b, &eb)), ((b, &eb), (a, &ea))] { + let theirs: BTreeMap<[i64; 4], ([u32; 8], [i64; 3])> = to_edges.iter().map(|e| (e.0, (e.1, e.2))).collect(); + let o = to.1.origin(); + let sq = [o.x, o.y, o.x + CELL_UNITS, o.y + CELL_UNITS].map(|v| v as f64); + let corners = [[sq[0], sq[1]], [sq[2], sq[1]], [sq[0], sq[3]], [sq[2], sq[3]]]; + let f = from.1.origin(); + let own = [f.x, f.y, f.x + CELL_UNITS, f.y + CELL_UNITS].map(|v| v as f64); + let to_box = |v: [f64; 2]| { + libm::hypot((sq[0] - v[0]).max(v[0] - sq[2]).max(0.0), (sq[1] - v[1]).max(v[1] - sq[3]).max(0.0)) + }; + for (k, e) in from_edges.iter().enumerate() { + let (p, q) = ([e.0[0] as f64, e.0[1] as f64], [e.0[2] as f64, e.0[3] as f64]); + let host = super::edge_line(&super::outline_words(from.0)[super::EDGE * k..]); + // Well inside the other block's listing reach: less a margin for the scale over a cell. + let listed = (reach(from.0, host) - 0.1) / metres_per_unit(e.0[1]); + let d = if segment_meets_box(p, q, sq) { + 0.0 + } else { + corners.iter().map(|&c| seg_dist(p, q, c)).fold(to_box(p).min(to_box(q)), f64::min) + }; + if d >= listed { + continue; + } + checked += 1; + let own_box = |v: [f64; 2]| { + libm::hypot((own[0] - v[0]).max(v[0] - own[2]).max(0.0), (own[1] - v[1]).max(v[1] - own[3]).max(0.0)) + }; + // The turns at a and at b, the last two words, where the end lies within both cells' reach. + let turns = |mut w: [u32; 8]| { + for (t, v) in [(6, p), (7, q)] { + if to_box(v).max(own_box(v)) >= listed { + w[t] = 0; + } + } + w + }; + if theirs.get(&e.0).map(|(w, n)| (turns(*w), *n)) != Some((turns(e.1), e.2)) { + // Within `MARGIN_M` of the shared line: within it of both squares. + let off = + |sq: [f64; 4], v: [f64; 2]| (sq[0] - v[0]).max(v[0] - sq[2]).max(sq[1] - v[1]).max(v[1] - sq[3]); + let far = [p, q].iter().all(|&v| off(own, v).max(off(sq, v)) * metres_per_unit(e.0[1]) > MARGIN_M); + differ[usize::from(far)].push(format!( + "{:?} host {:?} words {:?}: {:?}", + e.0, + e.2, + e.1, + theirs.get(&e.0) + )); + } + } + } + (checked, differ) +} + +/// The outline ends of a block that hold a turn but not exactly one edge of their host going on there with +/// the same paved height bits: there the fan's far ray would be a step. +pub fn outline_turns(words: &[u32]) -> Vec { + let edges = super::outline_words(words).as_chunks::<{ super::EDGE }>().0; + let mut heights: BTreeMap<(super::P, u32, bool), Vec> = BTreeMap::new(); + for e in edges { + let (a, b) = super::edge_ends(e); + heights.entry((a, super::edge_line(e), true)).or_default().push(e[4]); + heights.entry((b, super::edge_line(e), false)).or_default().push(e[5]); + } + let none = u32::from(i16::MIN as u16); + let mut out = Vec::new(); + for e in edges { + let (a, b) = super::edge_ends(e); + for (p, h, turn, next_a) in [(a, e[4], e[9] & 0xffff, false), (b, e[5], e[8] >> 16, true)] { + let goes_on = heights.get(&(p, super::edge_line(e), next_a)); + if turn != none && goes_on.map(Vec::as_slice) != Some(&[h][..]) { + out.push(format!( + "end {p:?} of line {}: a turn, the edges going on hold {goes_on:?}", + super::edge_line(e) + )); + } + } + } + out +} + +/// Whether segment pq meets the box [x0, y0, x1, y1]. +fn segment_meets_box(p: [f64; 2], q: [f64; 2], bx: [f64; 4]) -> bool { + let (mut t0, mut t1) = (0.0f64, 1.0f64); + let d = [q[0] - p[0], q[1] - p[1]]; + for (a, b) in [(-d[0], p[0] - bx[0]), (d[0], bx[2] - p[0]), (-d[1], p[1] - bx[1]), (d[1], bx[3] - p[1])] { + if a == 0.0 { + if b < 0.0 { + return false; + } + } else if a < 0.0 { + t0 = t0.max(b / a); + } else { + t1 = t1.min(b / a); + } + } + t0 <= t1 +} diff --git a/host/obc-ground-plan/src/faces/records/far.rs b/host/obc-ground-plan/src/faces/records/far.rs new file mode 100644 index 0000000000..4ecbc085fd --- /dev/null +++ b/host/obc-ground-plan/src/faces/records/far.rs @@ -0,0 +1,177 @@ +//! The far block of a cell: the record lines of its records' lines that reach it, each with a run of +//! its samples, for the pages that draw the ways from their lines alone. A full build encodes it from +//! the lines of its candidates, a far-only build (`far_block`) from the same lines without them: one +//! encoder of one set of lines, so both give the same words. +//! +//! Little-endian words; coordinates are frame units from the cell's origin. Words 3, 6, 7 and 10 of +//! the head, the rules, the lines and the samples sit where the near block's do, so a reader of those +//! reads both blocks. Words 8 and 9 are not the near block's extras and bins, so a reader of bins or +//! candidates never reads a far block. A change of the layout changes `MAGIC_FAR`. +//! +//! | Words | Holds | +//! | --- | --- | +//! | 0 | `MAGIC_FAR` | +//! | 1, 2 | 0: no candidates, no labels | +//! | 3 | the count of record lines L | +//! | 4, 5, 6 | the offset of the lines: `HEAD` + `heights::RULES` | +//! | 7, 8, 9 | the offsets of the samples, the keys and the sides | +//! | 10 | the cell's row of zoom 16 | +//! | 11, 12, 14 | the length of the block: the near block's blend edges, junctions and outline edges are empty; 13 is 0 | +//! | rules | `heights::RULES` words, as the near block's | +//! | lines | `LINE` words per record line, as the near block's, but word 2 is its first sample in this block and word 3 its count of samples here | +//! | samples | `SAMPLE` words each, as the near block's, but word 4 is the rank (0 to n − 1, below 2^20) of the sample's global name among the n names of this block's samples | +//! | keys | a word per record line: the key of its way's carriageway or rail bed candidate, rank << 16, class << 8, kind; its numeric order is the overlay's order of keys | +//! | sides | 2 words per sample: the plain terrain (f32 bits) where the cones of its left and of its right side let go; unknown is the NaN 0x7fc0_0000 | +//! +//! A line is in the block when one of its segments reaches the cell: the segment's box grown by the +//! line's `reach` meets the cell square. Then each of its legs is a record line, in the near block's +//! order. A leg with no segment in reach holds no samples. Else its run ends at its leg's end, or +//! `PAD` segments before its first segment in reach and `PAD` + 1 samples after its last. The line +//! words are the whole leg's, so at a run end that is not its leg's end the end kinds (line words 12 +//! and 13) and `h_segment`'s first and last segment are not true: a reader reads there only what the +//! stroke of a segment in reach reads, the segments within `WINDOW` of it and their neighbours. +//! +//! A side's point is the sample moved along the left normal (m.y, −m.x) of its mitre m by ± (its +//! shoulder's outer offset + the class's slope reach × (1 − `fade_share`)), rounded to whole units: +//! where the cones of an outline edge let go (`outline_edges`). + +use super::{f, f32w, key_word, line_words, outline_units, HEAD, LEG_SHIFT, SAMPLE}; +use crate::faces::geom::P; +use crate::faces::{legs, record_lines, way_key, Glob, Rules, WayLine}; +use crate::frame::{metres_per_unit, CellKey, GlobalPoint, CELL_UNITS}; +use crate::graph::WayGraph; +use crate::CellInput; + +/// "OBF" and the layout's version. +pub const MAGIC_FAR: u32 = 0x4f42_4602; +/// The viewer's road mask reaches this far past a way's core (`MASK_M` of `terrain/features.wgsl`). +pub const MASK_M: f64 = 12.75; +/// The segments on each side of its own that the stroke of a segment reads. +pub const WINDOW: usize = 4; +/// The segments of a run before its first segment in reach: a stroke's window, and the neighbour on +/// each side that `h_segment` reads. +pub const PAD: usize = WINDOW + 1; +/// The most samples of a run: the viewer packs a sample's index in 16 bits. +pub const RUN_MAX: usize = 65_535; +/// More names than this in one block are an error: the viewer packs a sample's rank in 20 bits. +pub const NAMES_MAX: usize = 1 << 20; + +/// The far block of a cell's ground level alone: the lines of its records, without candidates. +pub fn far_block(graph: &WayGraph, input: &CellInput, rules: &Rules, cell: CellKey) -> Result, String> { + encode(cell, graph, input, rules, &record_lines(graph, input, rules, cell)) +} + +/// A line's reach past a segment, in units at the cell's edge nearer the pole: its widest carriageway, +/// then its core and slope or the mask's reach, whichever is farther, and a metre. It holds for the +/// pages of level 16 and finer, where two texels are less than the mask's reach. +fn reach(cell: CellKey, line: &WayLine) -> f64 { + let y = cell.origin().y; + let half = (line.p.iter().zip(&line.h)).map(|(p, h)| h * metres_per_unit(y + i64::from(p[1]))).fold(0.0, f64::max); + let s = &line.sec; + outline_units(cell, half + (s.shoulder_m + s.verge_m + s.reach_m).max(MASK_M) + 1.0) +} + +/// Per leg [lo, hi] its run of samples, none where no segment of it is in reach r of the cell square. +/// Segment i joins the samples i and i + 1. +fn runs(p: &[P], legs: &[(usize, usize)], r: f64) -> Vec> { + let cell = f64::from(CELL_UNITS as i32); + let meets = |i: &usize| { + let (a, b) = (p[*i].map(f64::from), p[i + 1].map(f64::from)); + (0..2).all(|k| a[k].min(b[k]) - r <= cell && a[k].max(b[k]) + r >= 0.0) + }; + (legs.iter()) + .map(|&(lo, hi)| { + Some((lo.max((lo..hi).find(meets)?.saturating_sub(PAD)), hi.min((lo..hi).rfind(meets)? + PAD + 1))) + }) + .collect() +} + +/// The far block of `lines`, the lines of a cell's records. An error where a run holds more than +/// `RUN_MAX` samples, or the samples more than `NAMES_MAX` names. +pub(crate) fn encode( + cell: CellKey, + graph: &WayGraph, + input: &CellInput, + rules: &Rules, + lines: &[WayLine], +) -> Result, String> { + let legs: Vec> = + lines.iter().map(|l| legs::record_ranges(&l.spans, &l.cuts, l.p.len())).collect(); + let runs: Vec>> = + lines.iter().zip(&legs).map(|(l, g)| runs(&l.p, g, reach(cell, l))).collect(); + let kept: Vec = (0..lines.len()).filter(|&k| runs[k].iter().any(Option::is_some)).collect(); + let mut globs: Vec = (kept.iter()) + .flat_map(|&k| runs[k].iter().flatten().flat_map(move |&(a, b)| lines[k].key[a..=b].iter().copied())) + .collect(); + globs.sort_unstable(); + globs.dedup(); + if globs.len() > NAMES_MAX { + return Err(format!("cell {}/{}: {} names, more than {NAMES_MAX}", cell.x, cell.y, globs.len())); + } + // The samples past a run have no rank: their words are cut away. + let order = |g: &Glob| globs.binary_search(g).map_or(u32::MAX, |k| k as u32); + let origin = cell.origin(); + // One NaN for an unknown height: a cast's NaN bits may differ in WASM. + let terrain = |q: [f64; 2]| { + let g = GlobalPoint { x: origin.x + libm::round(q[0]) as i64, y: origin.y + libm::round(q[1]) as i64 }; + input.terrain.height(g).map_or(f32::NAN.to_bits(), f) + }; + let (mut lines_w, mut samples_w, mut keys, mut sides) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for &k in &kept { + let line = &lines[k]; + let go = line.sec.reach_m * (1.0 - rules.plan.heights.fade_share); + for (leg, (&(lo, hi), &run)) in legs[k].iter().zip(&runs[k]).enumerate() { + // The whole leg first: its mitres are the near block's. + let (mut w, s) = line_words(line, (lo, hi), graph, input, rules, &order); + let (a, n) = run.map_or((lo, 0), |(a, b)| (a, b - a + 1)); + if n > RUN_MAX { + return Err(format!( + "cell {}/{}: a leg of way {} keeps {n} samples, more than {RUN_MAX}", + cell.x, cell.y, line.way + )); + } + w[1] |= (leg as u32) << LEG_SHIFT; + w[2] = (samples_w.len() / SAMPLE) as u32; + w[3] = n as u32; + lines_w.extend(w); + keys.push(key_word(way_key(rules, line))); + for (i, s) in (a..a + n).zip(s[SAMPLE * (a - lo)..][..SAMPLE * n].as_chunks::().0) { + samples_w.extend(s); + let (p, m) = (line.p[i].map(f64::from), [f32w(s[8]), f32w(s[9])]); + let d = line.bands[i][1] + go / metres_per_unit(origin.y + i64::from(line.p[i][1])); + sides.extend([1.0, -1.0].map(|side| terrain([p[0] + side * d * m[1], p[1] - side * d * m[0]]))); + } + } + } + let mut words = vec![0u32; HEAD]; + words[0] = MAGIC_FAR; + words[3] = keys.len() as u32; + words[10] = (origin.y / CELL_UNITS) as u32; + words.extend(rules.plan.heights.words()); + let at = words.len() as u32; + words[4..7].fill(at); + words.extend(&lines_w); + words[7] = words.len() as u32; + words.extend(&samples_w); + words[8] = words.len() as u32; + words.extend(&keys); + words[9] = words.len() as u32; + words.extend(&sides); + let len = words.len() as u32; + for k in [11, 12, 14] { + words[k] = len; + } + Ok(words) +} + +#[cfg(test)] +mod tests { + use super::MASK_M; + + #[test] + fn the_mask_reaches_as_far_as_the_viewers() { + let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../builder/web/src/lib/trailview/terrain/features.wgsl"); + let features = std::fs::read_to_string(path).unwrap(); + assert!(features.contains(&format!("const MASK_M: f32 = {MASK_M};")), "MASK_M of {path}"); + } +} diff --git a/host/obc-ground-plan/src/faces/records/mod.rs b/host/obc-ground-plan/src/faces/records/mod.rs new file mode 100644 index 0000000000..6488492223 --- /dev/null +++ b/host/obc-ground-plan/src/faces/records/mod.rs @@ -0,0 +1,1909 @@ +//! The records of a cell: its candidates with the data that `decide` reads, listed per bin, so that +//! a reader gives any point the overlay's label by the overlay's own decision, near and far. +//! +//! A block is little-endian words; coordinates are frame units from the cell's origin. A change of +//! the layout changes `MAGIC`. +//! +//! | Words | Holds | +//! | --- | --- | +//! | head | `HEAD` words: `MAGIC`; the counts of candidates, labels and lines; the offsets of the candidates, labels, lines, samples, extras and bin headers; the cell's row of zoom 16; the offset of the blend edges; the offset of the junction table and the count of its records; the offset of the outline edges | +//! | rules | `heights::RULES` words: the rule values of the heights (`HeightRules::words`) | +//! | candidates | `CAND` words each: kind, key, glob order, label, line, then offset and count of its discs, beyond cuts and parts in the extras | +//! | labels | `LABEL` words each: surface, owner kind, rank, height rule; owner id (a junction's: the index of its junction record); material line; rail line of a crossing; 4 host lines; 4 other lines (none for a junction: its record holds its arms) | +//! | lines | `LINE` words each, one per leg of a way (`legs`), a way's legs in order, the water after the ways: way, finish code (0 for water) with flags, material and the leg (`LEG_SHIFT`), first sample, sample count, cut, fill, reach (m), class rank, shoulder, verge (m), return grade, half-width (m), the kind of each end, the steepest fill and cut, the fill's rise and crest (m); then the ceiling lines (`CEILING`), whose cut and fill words hold their flat ends and whose return grade holds their drop | +//! | samples | `SAMPLE` words each: x, y, half-width (units), metres along, glob order, height, bank, grade, mitre direction x, y, health radius left and right (units) | +//! | extras | discs (`DISC` words), beyond cuts (a cut and a label), parts (a way and two cuts, each with a flag) | +//! | junctions | the table, a word per junction record: its offset; then the records (`junction`) | +//! | blend edges | `BLEND` words each: the ends a (x, y) and b (x, y) as i32 bits, the label of the blend face, the label of the face beyond (u32::MAX for terrain) | +//! | outline edges | `EDGE` words each (`edge_ends`, `edge_line`): the end a (x, y) as i32 bits with the paved face on the left; b − a as two i16 (x low); the host line, low half, and the terrain's grade outward at a in 1/`GRADE_STEPS` (i16, `i16::MIN` unknown), high half; the paved height at a and at b; the plain terrain where the cones from a and from b start to let go (NaN unknown); the grade at b, low half, and the turn at b in 1/`TURN_STEPS` of π (i16, `i16::MIN` none), high half; the turn at a, low half | +//! | bins | `BINS`² headers of `HEADER` words (the first word of the bin's items; the counts of items and segments; of height segments and height discs; the words of the items and the count of blend edges), then per bin its candidate items, segments, height segments, height discs, blend edges, and in half words (the first low) the count of its outline edges followed by them | +//! +//! Floats are f32 bits. A side is right or left of the line's direction in frame axes (y south). +//! A candidate item is its index with its winding number at the bin's reference point (its middle +//! plus half a unit) + 128 << 16, its run count, then per run a vertex count and the vertices (x, y) +//! of a ring's consecutive edges that meet the bin grown by `MARGIN_M`. The vertices are the rings' +//! own, so two cells hold the same edges. A segment item `line | sample << 16` is the centre line +//! from that sample to the next. A blend edge is an edge of the overlay's faces between a blend face +//! (a junction's region) and a face of another label, with the blend face on its left (the side +//! where cross(b − a, q − a) > 0); a bin lists by index every one within `MARGIN_M` of its square. A +//! bin lists by index every outline edge within its host's reach of its square, by host line. +//! Two cells give a point the same distance to the blend edges, bit for bit below +//! `heights.region_fade_m` and within `check::BLEND_TOL` up to `MARGIN_M`: past that, an edge may end +//! elsewhere. Snap rounding does not guarantee the bits; the border check holds them. + +pub mod check; +pub mod far; +mod storeys; + +pub use far::far_block; +pub use storeys::storeys; + +use std::collections::BTreeMap; +use std::f64::consts::PI; + +use super::geom::P; +use super::heights::{self, Height, Items}; +use super::legs::{self, Legs}; +use super::points::Circle; +use super::stroke::union; +use super::{ + band, candidates, near_only, sample_at, snap, Cand, FacePlan, Glob, HeightRule, Label, Mouth, Owner, PlanRules, + Rules, Sliced, Surface, WayLine, LAYERS, OUTSIDE, SLOPE, +}; +use crate::frame::{metres_per_unit, CellKey, GlobalPoint, CELL_UNITS}; +use crate::graph::{Level, WayGraph}; +use crate::sections::{Finish, Material, WaySection}; +use crate::CellInput; + +/// "OBR" and the layout's version. +pub const MAGIC: u32 = 0x4f42_5216; + +/// Whether a junction's guest `g` stops at its best host `h`: a way with round corners whose pair's +/// mouth in `plan.json` is `stop`, and whose look (finish and material) is not the host's or whose +/// finish keeps its tread (`tread_finishes`). The paint gives the face beside such an arm its own +/// look up to the route's edge. A `reach` pair keeps the junction's look. +fn stops(plan: &PlanRules, h: &WaySection, g: &WaySection) -> bool { + let tread = g.material == Material::Finish && g.finish.is_some_and(|f| plan.keeps_tread(f)); + (tread || (g.finish, g.material) != (h.finish, h.material)) + && g.corner_radius_m.max(g.corner_radius_walk_m) > 0.0 + && plan.pair(h.group, g.group).mouth == Mouth::Stop +} +/// Bins per side of the cell square: 4,096 frame units, about 6.5 m. +pub const BINS: i32 = 64; +pub const BIN_UNITS: i32 = CELL_UNITS as i32 / BINS; +/// A bin lists every candidate edge within this of its square: the reach of the anti-aliasing and +/// of the edge lines. +pub const MARGIN_M: f64 = 3.0; +/// A bin lists every centre-line segment within this past the way's half-width: the paint reads +/// the metres across and along of the label's way. +pub const LINE_PAD_M: f64 = 3.0; +/// The heights read a line's segments and the discs within its slope reach and this past a bin. +pub const HEIGHT_PAD_M: f64 = 1.0; +pub const HEAD: usize = 15; +pub const CAND: usize = 11; +pub const LABEL: usize = 12; +pub const LINE: usize = 18; +pub const SAMPLE: usize = 12; +/// Centre, radius, the line at each foot. +pub const DISC: usize = 5; +pub const BEYOND: usize = 5; +pub const PART: usize = 11; +pub const BLEND: usize = 6; +pub const EDGE: usize = 10; +/// An outline edge's turn at an end in these steps per π radians (`i16`; `i16::MIN`: no edge goes on there). +pub const TURN_STEPS: f64 = 32767.0; +/// A junction record: node x, y; the arm count (bits 0-7) and the graph junction (bits 16-31); then +/// `JR_ARM` words per arm in the graph's order: its record line (bits 0-15) with `ARM_HOST` and +/// `ARM_STOP`; its node sample (bits 0-15) and its last sample (bits 16-31), the first past its seam, +/// both of the record line; its unit direction at the node (`pack2x16snorm`). +pub const JR: usize = 3; +pub const JR_ARM: usize = 3; +pub const ARM_HOST: u32 = 1 << 16; +/// A guest of another look than the host that stops at it (`stops`). +pub const ARM_STOP: u32 = 1 << 17; +/// Offset, candidate items << 16 | segment items, height segment items << 16 | height disc items, +/// blend edge items. +pub const HEADER: usize = 4; + +/// Candidate kinds. +pub const WAY: u32 = 0; +pub const POINT: u32 = 1; +pub const REGION: u32 = 2; +pub const BAND: u32 = 3; +pub const FILL: u32 = 4; +/// The paved outline: the union of the paving candidates, for the distance to the road's edge. It +/// takes no part in the decision. +pub const OUTLINE: u32 = 5; + +/// Owner kinds. +pub const TERRAIN: u32 = 0; +pub const WAY_OWNER: u32 = 1; +pub const JUNCTION: u32 = 2; +pub const PLATFORM: u32 = 3; + +/// Line flags above the finish code's byte: a rail line, a way that wears lines, one that looks as a +/// motorway, a wall class, line water, a path (`WaySection::path`); and from `MATERIAL_SHIFT` its top's +/// `sections::Material` (4 bits). +pub const RAIL: u32 = 1 << 8; +pub const MARKED: u32 = 1 << 9; +pub const MOTORWAY: u32 = 1 << 10; +/// A class with a wall at its edge where a higher line's bank needs one (`leg_wall`). +pub const WALL: u32 = 1 << 11; +/// A deck way over storey 0, after every line of storey 0: the ground stays under its underside +/// (`heights::ceiling`). Its word 10 holds the drop from its surface to that bound, the deck's depth and +/// `ceiling_gap_m`; its words 4 and 5 the unit normal into it of its stroke's flat end at its start and at its +/// end (`pack2x16snorm`): the end line of the ground way that ends there, or the mitre with another deck that +/// ends there, whichever lies nearest the deck's chord and within `FLAT_TURN_DEG` of it, else square to the +/// deck's own chord. Its samples' half-width is its stroke's: its paved layers' and `edge_band_m`. No reader of +/// storey 0 takes it as a way. +pub const CEILING: u32 = 1 << 12; +/// Line water: a painter reads only the records of its host's kind, water or not. +pub const WATER: u32 = 1 << 13; +pub const PATH: u32 = 1 << 14; +/// A line of a storey over the ground (`storeys`), after the ceiling lines: one leg, whose leg bits (from +/// `LEG_SHIFT`) hold its storey. Only a reader of that storey's labels takes it as a way. +pub const STOREY: u32 = 1 << 15; +/// A deck's stroke ends flat on an end line within this turn of its chord: past it the two ways meet side by +/// side, and the stroke ends square to its own chord. +pub const FLAT_TURN_DEG: f64 = 45.0; + +/// The farthest from a ceiling line's end segment that its term in `heights::decks` holds the ground, for its +/// stroke's half-width `half` and the release `release` (one unit for both). The end segment goes on along its +/// chord until q lies `release` past the flat end, whose normal turns up to `FLAT_TURN_DEG` (θ) from the chord, +/// and holds q within `half + release` across the chord: so q lies at most `(release + (half + release)·sin θ) / +/// cos θ` along the chord behind the end sample. Every other segment holds q within `half + release` of itself. +pub(crate) fn ceiling_end_reach(half: f64, release: f64) -> f64 { + let theta = FLAT_TURN_DEG.to_radians(); + libm::hypot((release + (half + release) * libm::sin(theta)) / libm::cos(theta), half + release) +} +pub const MATERIAL_SHIFT: u32 = 16; +/// A line of a bridge's ground stretch (an open part of a bridge way, `graph::level_tags::split`): a wall at its edge +/// is the bridge's, of concrete. +pub const BRIDGE_GROUND: u32 = 1 << 20; +/// A storey's line: what its deck is made of (`deck::Build`, 2 bits from here) and whether its top is of planks. +pub const BUILD_SHIFT: u32 = 21; +pub const PLANKS: u32 = 1 << 23; +/// The leg of a line's way, from 0 in the way's direction, in the bits from this one of its finish word. +pub const LEG_SHIFT: u32 = 24; +// The fields of a line's finish word: the finish code, each flag, the material and the leg. No two +// overlap; a new flag joins this list. +const _: () = { + let fields = [ + 0xff, + RAIL, + MARKED, + MOTORWAY, + WALL, + CEILING, + WATER, + PATH, + STOREY, + 0xf << MATERIAL_SHIFT, + BRIDGE_GROUND, + 3 << BUILD_SHIFT, + PLANKS, + u32::MAX << LEG_SHIFT, + ]; + let (mut seen, mut i) = (0u32, 0); + while i < fields.len() { + assert!(seen & fields[i] == 0, "two fields of a line's finish word overlap"); + seen |= fields[i]; + i += 1; + } +}; + +/// End kinds of a line: a free (round) end, an arm of a junction or joint or the cut where the next +/// or the previous leg of its way goes on (`legs`), a level change to a tunnel or a gallery, and one to a +/// deck, where the paved layers end square on the end line and the slope runs round it. +pub const FREE: u32 = 0; +pub const MEETS: u32 = 1; +pub const LEVEL: u32 = 2; +pub const DECK: u32 = 3; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RecordStats { + pub cands: u32, + pub labels: u32, + pub lines: u32, + pub samples: u32, + pub bins_used: u32, + pub bin_items: u32, + pub bin_edges: u32, + /// The most words of one bin. + pub max_bin_words: u32, +} + +pub struct Records { + pub cell: CellKey, + pub words: Vec, + pub stats: RecordStats, +} + +/// A cell's faces, its records near and far, and its far block, from one pass of candidates and one +/// slice. +pub struct Built { + pub faces: FacePlan, + pub near: Records, + /// For points where a pixel spans more than the band layers' detail: the near candidates without + /// the band layers. A point that the near records give no band layer's label has the same label. + /// It has no slope faces, so it carries no outline edges. + pub far_records: Records, + /// The far block (`far`) of the near records' lines. + pub far_block: Result, String>, +} + +/// The faces and records of one cell and level. `slopes = false` leaves out the slope layer. +pub fn build(graph: &WayGraph, input: &CellInput, rules: &Rules, cell: CellKey, level: i8, slopes: bool) -> Built { + let (faces, near, far_records, far_block) = pass(graph, input, rules, cell, level, slopes, true); + Built { faces, near, far_records: far_records.expect("asked for"), far_block } +} + +/// The faces, near records and far block of `build`, without the far records, which a viewer's cell +/// does not read. An error of the far block leaves the near records. +pub fn near( + graph: &WayGraph, + input: &CellInput, + rules: &Rules, + cell: CellKey, + level: i8, + slopes: bool, +) -> (FacePlan, Records, Result, String>) { + let (faces, near, _, far_block) = pass(graph, input, rules, cell, level, slopes, false); + (faces, near, far_block) +} + +/// One pass of candidates and one slice: the faces, the near records, with `far_records` the far +/// records, and the far block of the candidates' lines, the lines of `level` (`far_block` gives level +/// 0's, as every build asks). +fn pass( + graph: &WayGraph, + input: &CellInput, + rules: &Rules, + cell: CellKey, + level: i8, + slopes: bool, + far_records: bool, +) -> (FacePlan, Records, Option, Result, String>) { + let mut c = candidates(graph, input, rules, cell, level, if slopes { LAYERS } else { SLOPE }, true); + let s = Sliced::new(&c); + let faces = s.cell(&c, cell, level); + let map = s.map(); + let ceilings = if level == 0 { super::ceiling_lines(graph, input, rules, cell) } else { Vec::new() }; + let plan = s.plan(cell, level, &map, &s.labels); + let near = encode(cell, graph, input, rules, (&c.lines, &ceilings), &c.cands, &plan, true); + // The far block and the far level hold no water: their lines are the way lines. + let far_block = far::encode(cell, graph, input, rules, &c.lines[..c.ways]); + let records = far_records.then(|| { + let labels = c.far(&s); + c.cands.retain(|c| !near_only(c)); + let plan = s.plan(cell, level, &map, &labels); + encode(cell, graph, input, rules, (&c.lines[..c.ways], &[]), &c.cands, &plan, false) + }); + (faces, near, records, far_block) +} + +/// How far an outline edge's cones reach: the greatest slope reach of a class or a water row. The +/// candidates are the neighbours' own only up to `MARGIN_M` past the cell (the input margin holds no more +/// past the faces' longest chain), so past it two cells hold the same outline edges only as far as the +/// border check shows. +pub fn outline_m(sections: &crate::sections::Sections) -> f64 { + let ways = (0..).map_while(|rank| sections.class_faces(rank)).map(|c| c.reach_m); + ways.chain(sections.bank_reaches()).fold(0.0, f64::max) +} + +/// Frame units of `m` metres at the cell's edge nearer the pole: at least `m` at every point of it, so +/// a bin lists every outline edge whose cones reach a point of it. +fn outline_units(cell: CellKey, m: f64) -> f64 { + let o = cell.origin(); + let pole = if o.y < 1 << (crate::frame::FRAME_BITS - 1) { o.y } else { o.y + CELL_UNITS }; + m / metres_per_unit(pole) +} + +/// The words of a block's outline edges. +pub fn outline_words(words: &[u32]) -> &[u32] { + &words[words[14] as usize..words[9] as usize] +} + +/// An outline edge's grade in these steps per metre (`i16`; `i16::MIN` unknown). +pub const GRADE_STEPS: f64 = 4096.0; + +/// The ends a and b of an outline edge's words (`EDGE`): b as its offset from a. +pub fn edge_ends(e: &[u32]) -> (P, P) { + let a = [e[0] as i32, e[1] as i32]; + (a, [a[0] + i32::from(e[2] as u16 as i16), a[1] + i32::from((e[2] >> 16) as u16 as i16)]) +} + +/// The host line of an outline edge's words. +pub fn edge_line(e: &[u32]) -> u32 { + e[3] & 0xffff +} + +/// Segment ab cut where it crosses the lines of the bin grid: its ends and the crossings in order from a, +/// each rounded to the nearest unit from the exact line. Each piece lies in one bin. The cell origins lie +/// on the grid, so the grid is global, and two cells that hold segments of one line cut them at the same +/// points, whatever ends each of them sees. +fn bin_cuts(a: P, b: P) -> Vec

{ + let (a64, d) = (a.map(i64::from), [i64::from(b[0] - a[0]), i64::from(b[1] - a[1])]); + let unit = i64::from(BIN_UNITS); + // The crossings of one axis's grid lines in order from a: the share num / |d[axis]| of ab and the point. + let crossings = |axis: usize| -> Vec<(i64, P)> { + let (lo, hi) = (a64[axis].min(a64[axis] + d[axis]), a64[axis].max(a64[axis] + d[axis])); + let (den, o) = (d[axis].abs(), 1 - axis); + let mut out: Vec<(i64, P)> = (lo.div_euclid(unit) + 1..=(hi - 1).div_euclid(unit)) + .map(|k| { + let num = (k * unit - a64[axis]) * d[axis].signum(); + // The other coordinate on the line through a and b, (a·den + num·d) / den, rounded half up. + let other = (2 * (a64[o] * den + num * d[o]) + den).div_euclid(2 * den); + let mut q = [(k * unit) as i32; 2]; + q[o] = other as i32; + (num, q) + }) + .collect(); + if d[axis] < 0 { + out.reverse(); + } + out + }; + let (x, y) = (crossings(0), crossings(1)); + let (mut i, mut j, mut out) = (0, 0, vec![a]); + while i < x.len() || j < y.len() { + let take_x = j == y.len() || (i < x.len() && x[i].0 * d[1].abs() <= y[j].0 * d[0].abs()); + out.push(if take_x { x[i].1 } else { y[j].1 }); + (i, j) = if take_x { (i + 1, j) } else { (i, j + 1) }; + } + out.push(b); + out.dedup(); + out +} + +/// Per bin the outline edges (by index, under 2^16) within their host's reach of its square, in the +/// order of their host lines. `reach`: a record line's slope reach in metres. +fn outline_bins(cell: CellKey, edges: &[u32], reach: &dyn Fn(u32) -> f64) -> Vec> { + let mut bins: Vec> = vec![Vec::new(); (BINS * BINS) as usize]; + let all = edges.as_chunks::().0; + crate::probe::field(crate::probe::Field::OutlineEdges, all.len()); + assert!(all.len() < 1 << 16, "a cell's outline edges overflow a bin's half words"); + for (k, e) in all.iter().enumerate() { + let (a, b) = edge_ends(e); + let (a, b) = ([f64::from(a[0]), f64::from(a[1])], [f64::from(b[0]), f64::from(b[1])]); + let r = outline_units(cell, reach(edge_line(e))); + let bx = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]; + let Some((c, rows)) = bins_of(bx, r) else { continue }; + for row in rows[0]..=rows[1] { + for col in c[0]..=c[1] { + if near_box(a, b, square(col, row, 0.0), r) { + bins[(row * BINS + col) as usize].push((edge_line(e), k as u32)); + } + } + } + } + bins.into_iter() + .map(|mut v| { + v.sort_unstable(); + v.into_iter().map(|(_, k)| k).collect() + }) + .collect() +} + +/// Whether segment ab comes within r of the box [x0, y0, x1, y1]: an end lies within r of it, a corner +/// within r of the segment, or the segment meets it. Squared distances, no roots. +fn near_box(a: [f64; 2], b: [f64; 2], bx: [f64; 4], r: f64) -> bool { + let r2 = r * r; + let to_box = |p: [f64; 2]| { + let (dx, dy) = ((bx[0] - p[0]).max(p[0] - bx[2]).max(0.0), (bx[1] - p[1]).max(p[1] - bx[3]).max(0.0)); + dx * dx + dy * dy + }; + if to_box(a) <= r2 || to_box(b) <= r2 { + return true; + } + let u = [b[0] - a[0], b[1] - a[1]]; + let l2 = u[0] * u[0] + u[1] * u[1]; + let to_seg = |q: [f64; 2]| { + let t = if l2 > 0.0 { (((q[0] - a[0]) * u[0] + (q[1] - a[1]) * u[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let (dx, dy) = (q[0] - a[0] - t * u[0], q[1] - a[1] - t * u[1]); + dx * dx + dy * dy + }; + let corners = [[bx[0], bx[1]], [bx[2], bx[1]], [bx[0], bx[3]], [bx[2], bx[3]]]; + corners.iter().any(|&c| to_seg(c) <= r2) + || clip([a[0] as i32, a[1] as i32], [b[0] as i32, b[1] as i32], bx).is_some() +} + +/// An outline edge's height runs linearly between its ends: a rim splits at its middle while the paved +/// field leaves that line by more than this at the middle, or on a piece longer than `QUARTER_M` at +/// either quarter, down to `SPLIT_PAVED_MIN_M`: the slope starts from that line, so the paved side and +/// the slope side meet there with no step where the paved field bends. Half of the least step that the +/// heights check counts (`check::STEP_M`). +const SPLIT_M: f64 = 0.005; +/// The paved split stops at this length: a break of k m/m in the paved grade leaves k · L / 4 at a piece's +/// middle, so a shorter piece leaves its line by at most `check::STEP_M` where the grade breaks by up to +/// 2 m/m. +const SPLIT_PAVED_MIN_M: f64 = 0.02; +/// The ground's split (`SPLIT_GROUND_M`) goes down to this. +const SPLIT_MIN_M: f64 = 0.25; +/// A rim also splits while the ground where its cones let go leaves the line between its ends by more than +/// this: the cones read the need linearly between the ends, so a ground they did not see would move the +/// slope with the cuts. +const SPLIT_GROUND_M: f64 = 0.25; +/// The quarters find a field that crosses the line at the middle. Its offset there grows with the +/// cube of the piece's length, so a shorter piece reads its middle alone. +const QUARTER_M: f64 = 1.0; + +/// The outline edges' words (`EDGE` each) of the near plan's rims (a, b, paved label, the paved face on +/// the left): the host line, the paved field at both ends (`heights::paved_end`) from the block so far +/// through the window's bins (`items`), so two cells give an end the same bits, and the plain terrain +/// where the host's cones start to let go (`ground`), and each end's turn to the edge that goes on from it. +/// The host is the face's material line, else the paved field's host at the middle of the rim's piece. A rim +/// splits at the bin grid (`bin_cuts`), then while the paved field or that ground leaves the line between a +/// piece's ends (`SPLIT_*`). An edge with an end where the face has no height of its own stays out: a fault +/// that `heights::check` counts. +fn outline_edges<'a>( + words: &[u32], + input: &CellInput, + rules: &Rules, + rims: &[(P, P, u32)], + items: &dyn Fn([f64; 2]) -> Items<'a>, +) -> Vec { + let origin = input.key.origin(); + let fp = |p: P| [f64::from(p[0]), f64::from(p[1])]; + // The terrain at whole-unit point x moved by d units: global whatever the cell. + let terrain = |x: P, d: [f64; 2]| { + let at = |o: i64, x: i32, d: f64| o + i64::from(x) + libm::round(d) as i64; + let g = GlobalPoint { x: at(origin.x, x[0], d[0]), y: at(origin.y, x[1], d[1]) }; + input.terrain.height(g).unwrap_or(f64::NAN) + }; + let mpu = |x: P| metres_per_unit(origin.y + i64::from(x[1])); + let mut ends: BTreeMap<(P, u32), Option> = BTreeMap::new(); + let mut end = + |p: P, id: u32| *ends.entry((p, id)).or_insert_with(|| heights::paved_end(words, fp(p), id, &items(fp(p)))); + // At point x of host line l's outline, along the line's frame there (not along the rim, so every rim + // through x reads the same): the plain terrain where its cones start to let go, `go` metres out, as a mean + // along the way with a tent weight over `go` metres each side, so the cones and walls follow the hillside + // and not each bump of it; and the terrain's grade outward there. NaN unknown. + let mut grounds: BTreeMap<(P, u32), [f64; 2]> = BTreeMap::new(); + let mut ground = |x: P, l: u32, go: f64| { + *grounds.entry((x, l)).or_insert_with(|| { + let Some((out, along)) = heights::frame(words, fp(x), l, &items(fp(x))) else { return [f64::NAN; 2] }; + let u = go / mpu(x); + let at = |m: f64, s: f64| terrain(x, [out[0] * m + along[0] * s, out[1] * m + along[1] * s]); + let (mut sw, mut sz) = (0.0, 0.0); + for k in -2i32..=2 { + let z = at(u, f64::from(k) * u / 3.0); + if !z.is_nan() { + let w = f64::from(3 - k.abs()); + (sw, sz) = (sw + w, sz + w * z); + } + } + [if sw > 0.0 { sz / sw } else { f64::NAN }, (at(u, 0.0) - at(u / 2.0, 0.0)) / (go / 2.0)] + }) + }; + let metres = |p: P, q: P| { + libm::hypot(f64::from(q[0] - p[0]), f64::from(q[1] - p[1])) * metres_per_unit(origin.y + i64::from(p[1])) + }; + // Whole-unit middles, the same in every cell. + let mid = |p: P, q: P| [(p[0] + q[0]).div_euclid(2), (p[1] + q[1]).div_euclid(2)]; + // The rims' edges with a height at both ends: ends, host, paved heights. + let mut edges: Vec<(P, P, u32, [f64; 2])> = Vec::with_capacity(rims.len()); + let cell = f64::from(CELL_UNITS as i32); + for &(a, b, id) in rims.iter().filter(|(a, b, _)| a != b) { + let material = label(words, id)[2]; + let cuts = bin_cuts(a, b); + for (&r0, &r1) in cuts.iter().zip(&cuts[1..]) { + // The middle is the first point that the split reads. + let host = if material != u32::MAX { material } else { end(mid(r0, r1), id).map_or(u32::MAX, |h| h.owner) }; + if host == u32::MAX { + continue; + } + // A bin lists the edge within its host's reach: else the cell has no use for it. + let reach = f32w(words[words[6] as usize + LINE * host as usize + 6]); + if seg_box(r0, r1, [0.0, 0.0, cell, cell]) > outline_units(input.key, reach) { + continue; + } + // The cones let go from this many metres. + let go = reach * (1.0 - rules.plan.heights.fade_share); + // The piece's edges from r0: an edge splits while the paved field, or the ground where its + // cones let go, leaves the line between its ends. + let mut pieces = vec![(r0, end(r0, id))]; + let mut ahead = vec![(r1, end(r1, id))]; + while let Some(&(q, hq)) = ahead.last() { + let (p, hp) = pieces[pieces.len() - 1]; + let m = mid(p, q); + let off = |x: P, f: f64, end: &mut dyn FnMut(P, u32) -> Option| match (hp, hq, end(x, id)) { + (Some(hp), Some(hq), Some(hx)) => (hx.h - (hp.h + f * (hq.h - hp.h))).abs() > SPLIT_M, + (hp, hq, hx) => hx.is_some() != (hp.is_some() && hq.is_some()), + }; + let (gp, gq) = (ground(p, host, go)[0], ground(q, host, go)[0]); + let mut bent = |x: P, f: f64| (ground(x, host, go)[0] - (gp + f * (gq - gp))).abs() > SPLIT_GROUND_M; + let long = metres(p, q); + let quarters = long > QUARTER_M; + let split = (long > SPLIT_PAVED_MIN_M + && (off(m, 0.5, &mut end) + || (quarters && (off(mid(p, m), 0.25, &mut end) || off(mid(m, q), 0.75, &mut end))))) + || (long > SPLIT_MIN_M + && (bent(m, 0.5) || (quarters && (bent(mid(p, m), 0.25) || bent(mid(m, q), 0.75))))); + if split { + ahead.push((m, end(m, id))); + continue; + } + pieces.push((q, hq)); + ahead.pop(); + } + for w in pieces.windows(2) { + if let ((p, Some(hp)), (q, Some(hq))) = (w[0], w[1]) { + if p != q { + edges.push((p, q, host, [hp.h, hq.h])); + } + } + } + } + } + // Each end's turn to the one edge of the same host that goes on from it (a cut, a split or the rim's + // corner) with the same paved height bits there: the angle between the two edges' integer directions, so + // two cells that hold both give it alike. Where two faces of one host meet with two heights, the end has + // none: a fan's far ray would be a step there, and a free end's full cone is continuous. + let mut at: BTreeMap<(P, u32, bool), Vec> = BTreeMap::new(); + for (k, e) in edges.iter().enumerate() { + at.entry((e.0, e.2, true)).or_default().push(k); + at.entry((e.1, e.2, false)).or_default().push(k); + } + let dir = |k: usize| [f64::from(edges[k].1[0] - edges[k].0[0]), f64::from(edges[k].1[1] - edges[k].0[1])]; + let turn = |from: [f64; 2], to: [f64; 2]| { + let t = libm::atan2(from[0] * to[1] - from[1] * to[0], from[0] * to[0] + from[1] * to[1]); + u32::from(libm::round(t / PI * TURN_STEPS).clamp(-TURN_STEPS, TURN_STEPS) as i16 as u16) + }; + let none = u32::from(i16::MIN as u16); + let mut out = Vec::with_capacity(EDGE * edges.len()); + for (k, &(p, q, host, h)) in edges.iter().enumerate() { + let one = |key: (P, u32, bool), h: f64| { + let there = |j: usize| edges[j].3[usize::from(!key.2)]; + at.get(&key).filter(|v| v.len() == 1).map(|v| v[0]).filter(|&j| f(there(j)) == f(h)) + }; + let turn_a = one((p, host, false), h[0]).map_or(none, |j| turn(dir(j), dir(k))); + let turn_b = one((q, host, true), h[1]).map_or(none, |j| turn(dir(k), dir(j))); + let go = f32w(words[words[6] as usize + LINE * host as usize + 6]) * (1.0 - rules.plan.heights.fade_share); + let ([tp, gp], [tq, gq]) = (ground(p, host, go), ground(q, host, go)); + let grade = |g: f64| { + let g = if g.is_nan() { i16::MIN } else { libm::round(g * GRADE_STEPS).clamp(-32767.0, 32767.0) as i16 }; + u32::from(g as u16) + }; + let d = [q[0] - p[0], q[1] - p[1]].map(|v| u32::from(v as i16 as u16)); + crate::probe::field(crate::probe::Field::Line, host as usize); + assert!(host < 1 << 16, "a cell's record lines overflow an outline edge's half word"); + out.extend([p[0] as u32, p[1] as u32, d[0] | d[1] << 16, host | grade(gp) << 16]); + out.extend([f(h[0]), f(h[1]), f(tp), f(tq), grade(gq) | turn_b << 16, turn_a]); + } + out +} + +fn f32w(w: u32) -> f64 { + f64::from(f32::from_bits(w)) +} + +fn f(v: f64) -> u32 { + (v as f32).to_bits() +} + +/// A candidate's key as its word: rank, class, kind. +fn key_word(key: (u8, u8, u8)) -> u32 { + u32::from(key.0) << 16 | u32::from(key.1) << 8 | u32::from(key.2) +} + +fn kind(c: &Cand) -> u32 { + if c.relabel.is_some() { + REGION + } else if c.fill.is_some() { + FILL + } else if c.glob.is_none() { + WAY + } else if band(c) { + BAND + } else { + POINT + } +} + +/// Whether a candidate paves: a carriageway's label that is no band layer and relabels nothing. +fn paves(c: &Cand) -> bool { + c.label.surface == Surface::Carriageway && !matches!(kind(c), REGION | BAND) +} + +pub(super) fn label_words(l: &Label) -> [u32; 4] { + let (kind, id) = match l.owner { + Owner::Terrain => (TERRAIN, 0), + Owner::Way(w) => (WAY_OWNER, w), + Owner::Junction(j) => (JUNCTION, j), + Owner::Platform(p) => (PLATFORM, p), + }; + [ + l.surface as u32 | kind << 8 | u32::from(l.rank) << 16 | (l.rule as u32) << 24, + id, + l.material.unwrap_or(u32::MAX), + l.crossing.unwrap_or(u32::MAX), + ] +} + +/// Segment ab clipped to the box [x0, y0, x1, y1], if they meet. +fn clip(a: P, b: P, bx: [f64; 4]) -> Option<([f64; 2], [f64; 2])> { + let (mut t0, mut t1) = (0.0f64, 1.0f64); + let (ax, ay) = (f64::from(a[0]), f64::from(a[1])); + let (dx, dy) = (f64::from(b[0]) - ax, f64::from(b[1]) - ay); + for (p, q) in [(-dx, ax - bx[0]), (dx, bx[2] - ax), (-dy, ay - bx[1]), (dy, bx[3] - ay)] { + if p == 0.0 { + if q < 0.0 { + return None; + } + } else if p < 0.0 { + t0 = t0.max(q / p); + } else { + t1 = t1.min(q / p); + } + } + (t0 <= t1).then_some(([ax + t0 * dx, ay + t0 * dy], [ax + t1 * dx, ay + t1 * dy])) +} + +/// The distance from segment ab to the box [x0, y0, x1, y1]: 0 where they meet. +fn seg_box(a: P, b: P, bx: [f64; 4]) -> f64 { + if clip(a, b, bx).is_some() { + return 0.0; + } + let (fa, fb) = ([f64::from(a[0]), f64::from(a[1])], [f64::from(b[0]), f64::from(b[1])]); + let to_box = |p: [f64; 2]| { + let dx = (bx[0] - p[0]).max(p[0] - bx[2]).max(0.0); + let dy = (bx[1] - p[1]).max(p[1] - bx[3]).max(0.0); + libm::hypot(dx, dy) + }; + let corners = [[bx[0], bx[1]], [bx[2], bx[1]], [bx[0], bx[3]], [bx[2], bx[3]]]; + corners.into_iter().map(|q| seg_dist(fa, fb, q)).fold(to_box(fa).min(to_box(fb)), f64::min) +} + +fn seg_dist(a: [f64; 2], b: [f64; 2], q: [f64; 2]) -> f64 { + let u = [b[0] - a[0], b[1] - a[1]]; + let t = (((q[0] - a[0]) * u[0] + (q[1] - a[1]) * u[1]) / (u[0] * u[0] + u[1] * u[1]).max(1e-12)).clamp(0.0, 1.0); + libm::hypot(q[0] - a[0] - t * u[0], q[1] - a[1] - t * u[1]) +} + +/// A bin's reference point less half a unit: its middle. +pub fn reference(i: i32) -> i32 { + i * BIN_UNITS + BIN_UNITS / 2 +} + +/// The bin square [x0, y0, x1, y1] of column c and row r, grown by g units. +fn square(c: i32, r: i32, g: f64) -> [f64; 4] { + let u = f64::from(BIN_UNITS); + [f64::from(c) * u - g, f64::from(r) * u - g, f64::from(c + 1) * u + g, f64::from(r + 1) * u + g] +} + +/// The bins whose square grown by g meets the box [x0, y0, x1, y1]: columns and rows, or none. +fn bins_of(bx: [f64; 4], g: f64) -> Option<([i32; 2], [i32; 2])> { + bins_in(bx, g, 0) +} + +/// `bins_of` over the cell's bins and `wide` more on each side (columns and rows from −`wide`). +fn bins_in(bx: [f64; 4], g: f64, wide: i32) -> Option<([i32; 2], [i32; 2])> { + let (lo, hi) = (-f64::from(wide * BIN_UNITS), f64::from((BINS + wide) * BIN_UNITS)); + if bx[2] + g < lo || bx[3] + g < lo || bx[0] - g > hi || bx[1] - g > hi { + return None; + } + let to = |v: f64| ((v / f64::from(BIN_UNITS)).floor() as i32).clamp(-wide, BINS - 1 + wide); + Some(([to(bx[0] - g), to(bx[2] + g)], [to(bx[1] - g), to(bx[3] + g)])) +} + +/// The bins of the build's window: the cell's and `wide` more on each side, row by row. The records keep +/// the cell's; the build reads the paved field at outline ends past the cell square from the others. +struct Window { + wide: i32, +} + +impl Window { + fn side(&self) -> i32 { + BINS + 2 * self.wide + } + + fn len(&self) -> usize { + (self.side() * self.side()) as usize + } + + fn at(&self, col: i32, row: i32) -> usize { + ((row + self.wide) * self.side() + col + self.wide) as usize + } + + /// The window bin of a point (frame units), clamped to the window. + fn of(&self, q: [f64; 2]) -> usize { + let to = |v: f64| ((v / f64::from(BIN_UNITS)).floor() as i32).clamp(-self.wide, BINS - 1 + self.wide); + self.at(to(q[0]), to(q[1])) + } +} + +/// The windings of rings at the reference point of each bin of columns c and rows r, as `find` reads +/// it: moved by (ε, ε²) in frame axes. Per row a horizontal line through the reference points in +/// doubled units (odd, so it meets no vertex), and the signed crossings east of each point, exact. +fn windings(rings: &[Vec

], c: [i32; 2], r: [i32; 2]) -> Vec { + let cols = (c[1] - c[0] + 1) as usize; + let mut out = vec![0; cols * (r[1] - r[0] + 1) as usize]; + for row in r[0]..=r[1] { + let y = 2 * i64::from(reference(row)) + 1; + let mut edges: Vec<([i64; 2], [i64; 2], i32)> = Vec::new(); + for ring in rings { + for (i, &a) in ring.iter().enumerate() { + let b = ring[(i + 1) % ring.len()]; + let (a, b) = ([2 * i64::from(a[0]), 2 * i64::from(a[1])], [2 * i64::from(b[0]), 2 * i64::from(b[1])]); + if (a[1] < y) != (b[1] < y) { + edges.push((a, b, if b[1] > a[1] { 1 } else { -1 })); + } + } + } + for col in c[0]..=c[1] { + let x = 2 * i64::from(reference(col)) + 1; + // East of the point: (x at y) − x has the sign of num / (b.y − a.y). On the edge, the + // moved point lies east of it. + let east = |&(a, b, _): &&([i64; 2], [i64; 2], i32)| { + let num = (a[0] - x) * (b[1] - a[1]) + (b[0] - a[0]) * (y - a[1]); + num != 0 && (num > 0) == (b[1] > a[1]) + }; + out[(row - r[0]) as usize * cols + (col - c[0]) as usize] = edges.iter().filter(east).map(|e| e.2).sum(); + } + } + out +} + +/// Per vertex of a line: the mitre direction (unit) and the health radius on the left and on the right +/// (units, 1e9 for none): the nearest crossing on that side of the mitre lines of the two quads that +/// meet at the vertex. The mitres follow the centre line's direction smoothed to a least radius +/// (`least`, units per vertex): between two vertices they turn by at most the chord over it, so two +/// neighbour mitre lines cross no nearer, and a mean over that length takes out the polyline's kinks. +/// A mitre stays within `tilt_deg` of both its chords (or the bisector's angle at a sharper vertex), +/// so where that does not reach the least radius the frame keeps its fold. The positions, and so the +/// road's outline, do not change. +fn mitres(p: &[P], least: &[f64], tilt_deg: f64) -> Vec<[f64; 4]> { + let at = |k: usize| [f64::from(p[k][0]), f64::from(p[k][1])]; + let n = p.len(); + if n < 2 { + return vec![[1.0, 0.0, 1e9, 1e9]; n]; + } + // The chords' lengths and directions, unwrapped; a chord of no length keeps the one before it. + let mut len = vec![0.0; n - 1]; + let mut dir = vec![0.0; n - 1]; + for k in 0..n - 1 { + let d = [at(k + 1)[0] - at(k)[0], at(k + 1)[1] - at(k)[1]]; + len[k] = libm::hypot(d[0], d[1]); + let raw = if len[k] > 0.0 { + libm::atan2(d[1], d[0]) + } else if k > 0 { + dir[k - 1] + } else { + 0.0 + }; + dir[k] = if k == 0 { raw } else { dir[k - 1] + libm::remainder(raw - dir[k - 1], 2.0 * PI) }; + } + // Per vertex the bisector's angle; per chord the most turn that the least radius allows. + let beta: Vec = (0..n) + .map(|i| match (i.checked_sub(1).and_then(|k| dir.get(k)), dir.get(i)) { + (Some(a), Some(b)) => (a + b) / 2.0, + (Some(a), None) | (None, Some(a)) => *a, + (None, None) => 0.0, + }) + .collect(); + let most: Vec = (0..n - 1).map(|k| len[k] / least[k].min(least[k + 1])).collect(); + // The best fit of the angles that turns by at most `most`: the mean of the greatest such function + // below them and the least one above them. + let (mut lo, mut hi) = (beta.clone(), beta.clone()); + for k in 0..n - 1 { + lo[k + 1] = lo[k + 1].min(lo[k] + most[k]); + hi[k + 1] = hi[k + 1].max(hi[k] - most[k]); + } + for k in (0..n - 1).rev() { + lo[k] = lo[k].min(lo[k + 1] + most[k]); + hi[k] = hi[k].max(hi[k + 1] - most[k]); + } + // A mitre stays within the tilt of both its chords, or as near to them as the bisector. + let tilt = |i: usize, a: f64| { + let (c0, c1) = (dir[i.saturating_sub(1)], dir[i.min(n - 2)]); + let room = (tilt_deg.to_radians() - (c1 - c0).abs() / 2.0).max(0.0); + a.clamp(beta[i] - room, beta[i] + room) + }; + let fit: Vec = (0..n).map(|i| tilt(i, (lo[i] + hi[i]) / 2.0)).collect(); + // The mean of the piecewise linear angle over the least radius's arc about each vertex, the window + // shrinking toward the ends, so an end keeps its chord's direction. + let mut s = vec![0.0; n]; + let mut area = vec![0.0; n]; + for k in 0..n - 1 { + s[k + 1] = s[k] + len[k]; + area[k + 1] = area[k] + len[k] * (fit[k] + fit[k + 1]) / 2.0; + } + let integral = |x: f64| { + let k = s.partition_point(|&v| v <= x).clamp(1, n - 1) - 1; + let f = if len[k] > 0.0 { ((x - s[k]) / len[k]).clamp(0.0, 1.0) } else { 0.0 }; + let v = fit[k] + f * (fit[k + 1] - fit[k]); + area[k] + (x - s[k]).clamp(0.0, len[k]) * (fit[k] + v) / 2.0 + }; + let total = s.last().copied().unwrap_or(0.0); + let t: Vec<[f64; 2]> = (0..n) + .map(|i| { + let half = (least[i] / 2.0).min(s[i]).min(total - s[i]); + let a = if half > 0.0 { + tilt(i, (integral(s[i] + half) - integral(s[i] - half)) / (2.0 * half)) + } else { + beta[i] + }; + [libm::cos(a), libm::sin(a)] + }) + .collect(); + // Where the mitre lines of vertices i and i + 1 cross: the signed offset along i's left normal. + let crossing = |i: usize| { + let (ma, mb) = ([t[i][1], -t[i][0]], [t[i + 1][1], -t[i + 1][0]]); + let den = ma[0] * mb[1] - ma[1] * mb[0]; + if den.abs() < 1e-12 { + return f64::INFINITY; + } + let ab = [at(i + 1)[0] - at(i)[0], at(i + 1)[1] - at(i)[1]]; + (ab[0] * mb[1] - ab[1] * mb[0]) / den + }; + (0..n) + .map(|i| { + let rho = |side: f64| { + let near = [(i > 0).then(|| crossing(i - 1)), (i + 1 < n).then(|| crossing(i))]; + near.into_iter().flatten().filter(|c| c * side > 0.0).fold(1e9, |r: f64, c| r.min(c * side)) + }; + [t[i][0], t[i][1], rho(1.0), rho(-1.0)] + }) + .collect() +} + +/// The finish code of the viewer's looks: `Finish` in order from 1. +fn code(finish: Finish) -> u32 { + Finish::ALL.iter().position(|&x| x == finish).map_or(0, |i| i as u32 + 1) +} + +/// The words of the leg of a line from point `lo` to point `hi` (`legs`), with its first sample 0, and +/// of its samples. A leg is a line of its own: its ends at cuts meet the next legs, and its frame's mitres turn +/// as a line's that ends there. A taper's vertex between two graph samples takes their values at its +/// share of the segment. +fn line_words( + line: &WayLine, + (lo, hi): (usize, usize), + graph: &WayGraph, + input: &CellInput, + rules: &Rules, + order: &dyn Fn(&Glob) -> u32, +) -> (Vec, Vec) { + let way = &graph.ways[line.way as usize]; + let sec = &line.sec; + let flags = [ + (line.rail, RAIL), + (sec.marked, MARKED), + (sec.motorway, MOTORWAY), + (sec.leg_wall, WALL), + (sec.water, WATER), + (sec.path, PATH), + (way.level == Level::Ground && graph.parts[way.part as usize].level == Level::Deck, BRIDGE_GROUND), + ]; + let flags = flags.iter().fold(0, |f, &(on, bit)| f | if on { bit } else { 0 }); + let finish = sec.finish.map_or(0, code) | flags | (sec.material as u32) << MATERIAL_SHIFT; + let mut w = vec![line.way, finish, 0, (hi - lo + 1) as u32]; + w.extend([f(sec.cut), f(sec.fill), f(sec.reach_m), sec.rank as u32]); + w.extend([f(sec.shoulder_m), f(sec.verge_m), f(sec.return_grade), f(sec.half_m)]); + // An end meets a junction or a joint whose arms all lie on the way's level; a joint to a bridge or + // a tunnel is a level change. + let meets = |dir: i8, st: &crate::graph::Station| { + let arm = |a: &crate::graph::Arm| a.way == line.way && a.dir == dir && a.at.span == st.span && a.at.u == st.u; + let level = |arms: &[crate::graph::Arm]| arms.iter().any(arm) && arms.iter().all(|a| a.level == way.level); + graph.junctions.iter().any(|j| level(&j.arms)) || graph.joints.iter().any(|j| level(&j.arms)) + }; + for (k, (dir, st)) in [(1i8, &way.from), (-1i8, &way.to)].into_iter().enumerate() { + w.push(if [lo > 0, hi + 1 < line.p.len()][k] { + MEETS + } else if line.round[k] { + FREE + } else if meets(dir, st) { + MEETS + } else if line.deck[k] { + DECK + } else { + LEVEL + }); + } + w.extend([f(sec.fill_max), f(sec.cut_max), f(sec.rise_m), f(sec.crest_m)]); + let samples = &graph.samples[way.samples.start as usize..way.samples.end as usize]; + // Per vertex: its graph sample and its share of the segment to the next one. + let mut share = vec![(0usize, 0.0f64); line.p.len()]; + for (k, win) in line.index.windows(2).enumerate() { + let (a, b) = (line.p[win[0]], line.p[win[1]]); + let len = libm::hypot(f64::from(b[0] - a[0]), f64::from(b[1] - a[1])).max(1e-9); + for (j, s) in share.iter_mut().enumerate().take(win[1]).skip(win[0]) { + let p = line.p[j]; + *s = (k, libm::hypot(f64::from(p[0] - a[0]), f64::from(p[1] - a[1])) / len); + } + } + if let Some(&last) = line.index.last() { + share[last] = (line.index.len() - 1, 0.0); + } + let origin = input.key.origin(); + // The frame's least radius: the half-width and the health's margin and width, so the frame has + // full health over the whole carriageway. + let health = rules.plan.heights.health_margin_m + rules.plan.heights.health_width_m; + let least: Vec = + (line.p.iter().zip(&line.h)).map(|(p, h)| h + health / metres_per_unit(origin.y + i64::from(p[1]))).collect(); + let mitres = mitres(&line.p[lo..=hi], &least[lo..=hi], rules.plan.heights.frame_tilt_deg); + let mut s = Vec::with_capacity(SAMPLE * (hi - lo + 1)); + for (i, &p) in line.p.iter().enumerate().take(hi + 1).skip(lo) { + let (k, x) = share[i]; + let (s0, s1) = (&samples[k], &samples[(k + 1).min(samples.len() - 1)]); + let lerp = |a: f64, b: f64| a + x * (b - a); + s.extend([p[0] as u32, p[1] as u32, f(line.h[i]), f(lerp(s0.along_m, s1.along_m)), order(&line.key[i])]); + s.extend([f(lerp(s0.z_m, s1.z_m)), f(lerp(s0.bank, s1.bank)), f(lerp(s0.grade, s1.grade))]); + s.extend(mitres[i - lo].map(f)); + } + (w, s) +} + +/// The words of a disc; `line` gives the record line of a line at a foot. +fn disc_words(d: &Circle, line: &dyn Fn(usize, P) -> u32) -> [u32; DISC] { + [d.centre[0] as u32, d.centre[1] as u32, f(d.radius), line(d.lines[0], d.feet[0]), line(d.lines[1], d.feet[1])] +} + +/// The words of a cut as the slice holds it: its ends snapped as the overlay's `past` reads them. +fn cut_words(cut: &[P; 2]) -> [u32; 4] { + let (a, b) = (snap(cut[0]), snap(cut[1])); + [a[0] as u32, a[1] as u32, b[0] as u32, b[1] as u32] +} + +/// The block of a cell's candidates and plan, with its lines and its ceiling lines (`CEILING`). +#[allow(clippy::too_many_arguments)] +fn encode( + cell: CellKey, + graph: &WayGraph, + input: &CellInput, + rules: &Rules, + (lines, ceilings): (&[WayLine], &[WayLine]), + cands: &[Cand], + plan: &FacePlan, + with_outline: bool, +) -> Records { + let origin = cell.origin(); + let mpu = metres_per_unit(origin.y + CELL_UNITS / 2); + let units = |m: f64| m / mpu; + // The window's bins reach past the cell square as far as the ends of the outline edges that a bin + // lists: an edge reaches a bin's square within `outline_m`, and is a bin long at most (`bin_cuts`). + let reach_units = outline_units(cell, outline_m(&rules.sections)); + let wide = if with_outline { (reach_units / f64::from(BIN_UNITS)).ceil() as i32 + 1 } else { 0 }; + let window = Window { wide }; + // The paved outline with the circles of its fans and rounds: one union, so the distance to the + // road's edge has no seam inside the paved area. + let paved: Vec> = cands.iter().filter(|c| paves(c)).flat_map(|c| c.rings.iter().cloned()).collect(); + let outline = union(&paved, [0, 0]); + let outline_discs: Vec<&Circle> = cands.iter().filter(|c| paves(c)).flat_map(|c| &c.discs).collect(); + // The global names in order: a way's at its samples, a point's at its position. + let mut globs: Vec = + lines.iter().flat_map(|l| l.key.iter().copied()).chain(cands.iter().filter_map(|c| c.glob)).collect(); + globs.sort_unstable(); + globs.dedup(); + let order = |g: &Glob| globs.binary_search(g).unwrap() as u32; + // One record line per leg of each line (`legs`): its line and its first and last point. + let mut lines_w = Vec::new(); + let mut samples_w = Vec::new(); + let mut rec: Vec<(usize, usize, usize)> = Vec::new(); + let mut rec_of: Vec = Vec::with_capacity(lines.len()); + for (l, line) in lines.iter().enumerate() { + rec_of.push(rec.len() as u32); + for (leg, (lo, hi)) in legs::record_ranges(&line.spans, &line.cuts, line.p.len()).into_iter().enumerate() { + let (mut w, s) = line_words(line, (lo, hi), graph, input, rules, &order); + w[1] |= (leg as u32) << LEG_SHIFT; + w[2] = (samples_w.len() / SAMPLE) as u32; + lines_w.extend(w); + samples_w.extend(s); + rec.push((l, lo, hi)); + } + } + // The ceiling lines after them, each one leg (`faces::ceiling_lines`), with the drop in word 10. + let heights = &rules.plan.heights; + // The ground ways' deck end lines: their end point, the unit direction into the way. + let ends: Vec<[f64; 5]> = lines.iter().flat_map(super::deck_ends).collect(); + let unit = |v: [f64; 2]| { + let len = libm::hypot(v[0], v[1]); + (len > 1e-9).then(|| [v[0] / len, v[1] / len]) + }; + // Each ceiling line's ends: the end point and the unit chord into the line. Two decks that end at one point + // end on their mitre, the bisector of their chords, so their strokes leave no notch on the outside of a bend. + let chord = |line: &WayLine, at: usize, next: usize| { + let (a, b) = (line.p[at], line.p[next]); + let own = unit([f64::from(b[0] - a[0]), f64::from(b[1] - a[1])]).unwrap_or([1.0, 0.0]); + (a, own) + }; + let deck_chords: Vec<(usize, (P, [f64; 2]))> = (ceilings.iter().enumerate()) + .flat_map(|(k, l)| [(k, chord(l, 0, 1)), (k, chord(l, l.p.len() - 1, l.p.len() - 2))]) + .collect(); + for (c, line) in ceilings.iter().enumerate() { + let (mut w, s) = line_words(line, (0, line.p.len() - 1), graph, input, rules, &|_| 0); + let n = line.p.len(); + for (k, (at, next)) in [(0, 1), (n - 1, n - 2)].into_iter().enumerate() { + let (a, own) = chord(line, at, next); + let grounds = + (ends.iter()).filter(|e| e[0] == f64::from(a[0]) && e[1] == f64::from(a[1])).map(|e| [-e[2], -e[3]]); + let mitres = (deck_chords.iter()) + .filter(|&&(m, (p, _))| m != c && p == a) + .filter_map(|&(_, (_, other))| unit([own[0] - other[0], own[1] - other[1]])); + let flat = (grounds.chain(mitres)) + .map(|n| (n[0] * own[0] + n[1] * own[1], n)) + .filter(|&(c, _)| c >= libm::cos(FLAT_TURN_DEG.to_radians())) + .max_by(|x, y| x.0.total_cmp(&y.0)) + .map_or(own, |(_, n)| n); + let snorm = |v: f64| u32::from(libm::round(v.clamp(-1.0, 1.0) * 32767.0) as i16 as u16); + w[4 + k] = snorm(flat[0]) | snorm(flat[1]) << 16; + } + w[1] |= CEILING; + w[2] = (samples_w.len() / SAMPLE) as u32; + w[10] = f(graph.deck_depth(input, line.way, &line.sec) + heights.ceiling_gap_m); + lines_w.extend(w); + samples_w.extend(s); + } + let rec_line = |l: usize, leg: u8| rec_of[l] + u32::from(leg); + let rec_points = |r: usize| &lines[rec[r].0].p[rec[r].1..=rec[r].2]; + let of_way: BTreeMap = lines.iter().enumerate().map(|(i, l)| (l.way, i as u32)).collect(); + let line_of = + |w: Option, leg: u8| w.and_then(|w| of_way.get(&w)).map_or(u32::MAX, |&l| rec_line(l as usize, leg)); + // The leg of a line nearest a point: a disc's foot on its line's edge. + let legs_of: Vec> = (lines.iter()) + .map(|l| { + let reach = |o: P| l.leg_reach_m() / metres_per_unit(origin.y + i64::from(o[1])); + (!l.cuts.is_empty()).then(|| Legs::new(&l.p, &l.cuts, &reach)) + }) + .collect(); + let foot_line = |l: usize, foot: P| { + if l == usize::MAX { + return u32::MAX; + } + let leg = legs_of[l].as_ref().map_or(0, |g| g.nearest([f64::from(foot[0]), f64::from(foot[1])])); + rec_line(l, leg) + }; + // The leg of an arm of a graph point: the one it leaves along. + let arm_line = |a: &crate::graph::Arm, pos: P| { + of_way.get(&a.way).map_or(u32::MAX, |&l| { + let l = l as usize; + rec_line(l, legs::leg(&lines[l].cuts, sample_at(graph, &lines[l], &a.at, pos), a.dir)) + }) + }; + // A label's words with its material and crossing as record lines. + let mut labels: Vec<[u32; 4]> = Vec::new(); + let mut label_id = |l: &Label| { + let mut w = label_words(l); + w[2] = line_of(l.material, l.legs[0]); + w[3] = line_of(l.crossing, l.legs[1]); + labels.iter().position(|x| *x == w).unwrap_or_else(|| { + labels.push(w); + labels.len() - 1 + }) as u32 + }; + let mut cands_w = Vec::new(); + let mut extras: Vec = Vec::new(); + // Per candidate, the labels it can give a point: its own and those past its seams. + let mut given: Vec> = Vec::with_capacity(cands.len()); + for c in cands { + let k = kind(c); + let own = label_id(&c.label); + let discs = extras.len() as u32; + extras.extend(c.discs.iter().flat_map(|d| disc_words(d, &foot_line))); + let beyond = extras.len() as u32; + let mut ids = vec![own]; + for (cut, l) in &c.beyond { + let id = label_id(l); + extras.extend(cut_words(cut)); + extras.push(id); + ids.push(id); + } + given.push(ids); + let parts_at = extras.len() as u32; + let parts = c.relabel.as_deref().unwrap_or(&[]); + for part in parts { + extras.push(lines[part.line].way); + for cut in &part.cuts { + extras.push(u32::from(cut.is_some())); + extras.extend(cut.as_ref().map_or([0; 4], cut_words)); + } + } + cands_w.extend([k, key_word(c.key), c.glob.as_ref().map_or(u32::MAX, order), own]); + cands_w.push(if k == WAY { rec_line(c.line, c.label.legs[0]) } else { u32::MAX }); + cands_w.extend([discs, c.discs.len() as u32, beyond, c.beyond.len() as u32, parts_at, parts.len() as u32]); + } + // The blend edges that a bin lists, each side of an edge between two labels whose face blends. + let n_bins = (BINS * BINS) as usize; + let margin = units(MARGIN_M); + let mut blend: Vec = Vec::new(); + let mut bedges: Vec> = vec![Vec::new(); window.len()]; + // The paved outline near the cell (near level only): (a, b, paved label) with the paved face on the + // left of a to b. + let mut rims: Vec<(P, P, u32)> = Vec::new(); + for e in plan.edges.iter().filter(|e| e.left != OUTSIDE && e.right != OUTSIDE) { + let (l, r) = (Label::of(&plan.faces[e.left as usize]), Label::of(&plan.faces[e.right as usize])); + let (a, b) = (plan.vertices[e.a as usize], plan.vertices[e.b as usize]); + let eb = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])].map(f64::from); + let paved = |l: &Label| l.rule as u8 >= HeightRule::Owner as u8; + // Water casts no cone into a culvert's zone: the slopes there rise from its sides only (`culverts`). + let hidden = [(l, r), (r, l)].iter().any(|(a, b)| a.surface == Surface::Water && b.surface == Surface::Zone); + if with_outline && paved(&l) != paved(&r) && !hidden && bins_of(eb, reach_units).is_some() { + rims.push(if paved(&l) { (a, b, label_id(&l)) } else { (b, a, label_id(&r)) }); + } + let Some((ec, er)) = bins_in(eb, margin + 1.0, window.wide).filter(|_| l != r) else { continue }; + let listed: Vec = (er[0]..=er[1]) + .flat_map(|row| (ec[0]..=ec[1]).map(move |col| (col, row))) + .filter(|&(col, row)| clip(a, b, square(col, row, margin + 1.0)).is_some()) + .map(|(col, row)| window.at(col, row)) + .collect(); + for (region, other, a, b) in [(l, r, a, b), (r, l, b, a)] { + if region.rule != HeightRule::Blend || listed.is_empty() { + continue; + } + let other = if other.surface == Surface::Terrain { u32::MAX } else { label_id(&other) }; + for &k in &listed { + bedges[k].push((blend.len() / BLEND) as u32); + } + blend.extend([a[0] as u32, a[1] as u32, b[0] as u32, b[1] as u32, label_id(®ion), other]); + } + } + let discs = extras.len() as u32; + extras.extend(outline_discs.iter().flat_map(|d| disc_words(d, &foot_line))); + cands_w.extend([OUTLINE, u32::MAX, u32::MAX, u32::MAX, u32::MAX, discs, outline_discs.len() as u32, 0, 0, 0, 0]); + // The shapes in bin order: the paved outline first, then the band layers, then the rest, so a + // point far from the paved area reads only these first. + let shapes: Vec<&Vec>> = cands.iter().map(|c| &c.rings).chain(std::iter::once(&outline)).collect(); + let mut by_order = vec![cands.len()]; + by_order.extend((0..cands.len()).filter(|&c| kind(&cands[c]) == BAND)); + by_order.extend((0..cands.len()).filter(|&c| kind(&cands[c]) != BAND)); + let mut items: Vec> = vec![Vec::new(); n_bins]; + let mut n_items = vec![0u32; n_bins]; + let mut stats = RecordStats::default(); + for ci in by_order { + let rings = shapes[ci]; + let bb = rings.iter().flatten().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| { + [b[0].min(f64::from(p[0])), b[1].min(f64::from(p[1])), b[2].max(f64::from(p[0])), b[3].max(f64::from(p[1]))] + }); + let Some((c, r)) = bins_of(bb, margin).filter(|_| bb[0] <= bb[2]) else { continue }; + let wind = windings(rings, c, r); + let cols = (c[1] - c[0] + 1) as usize; + // Per bin, the edges (ring, index) that meet its square grown by the margin and a unit. + let mut edges: Vec> = vec![Vec::new(); wind.len()]; + for (ri, ring) in rings.iter().enumerate() { + for (i, &a) in ring.iter().enumerate() { + let b = ring[(i + 1) % ring.len()]; + let eb = [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])].map(f64::from); + let Some((ec, er)) = bins_of(eb, margin + 1.0) else { continue }; + for row in er[0].max(r[0])..=er[1].min(r[1]) { + for col in ec[0].max(c[0])..=ec[1].min(c[1]) { + if clip(a, b, square(col, row, margin + 1.0)).is_some() { + edges[(row - r[0]) as usize * cols + (col - c[0]) as usize].push((ri, i)); + } + } + } + } + } + for row in r[0]..=r[1] { + for col in c[0]..=c[1] { + let k = (row - r[0]) as usize * cols + (col - c[0]) as usize; + if edges[k].is_empty() && wind[k] == 0 { + continue; + } + // The edges as runs of a ring's consecutive vertices. + let mut runs: Vec> = Vec::new(); + let mut last: Option<(usize, usize)> = None; + for &(ri, i) in &edges[k] { + let ring = &rings[ri]; + if last != Some((ri, i.wrapping_sub(1))) { + runs.push(vec![ring[i]]); + } + runs.last_mut().unwrap().push(ring[(i + 1) % ring.len()]); + last = Some((ri, i)); + } + let b = (row * BINS + col) as usize; + crate::probe::field(crate::probe::Field::Candidate, ci); + items[b].extend([ci as u32 | ((wind[k].clamp(-127, 127) + 128) as u32) << 16, runs.len() as u32]); + for run in &runs { + items[b].push(run.len() as u32); + items[b].extend(run.iter().flat_map(|v| [v[0] as u32, v[1] as u32])); + } + n_items[b] += 1; + stats.bin_items += 1; + stats.bin_edges += edges[k].len() as u32; + } + } + } + // A carriageway over a rail bed is a crossing: its label's variant with the rail as `crossing`. A + // point reads only the candidates of its bin, so a variant is needed only for a label that a + // candidate can give in a bin that lists a rail bed. + let rail = |ci: usize| { + (cands.get(ci).filter(|c| c.label.surface == Surface::RailBed)) + .map(|c| line_of(c.label.material, c.label.legs[0])) + }; + // The rails already paired with each label. + let mut paired: Vec> = vec![Vec::new(); labels.len()]; + for list in &items { + let mut listed = Vec::new(); + let mut at = 0; + while at < list.len() { + listed.push((list[at] & 0xffff) as usize); + at = skip_item(list, at); + } + let rails: Vec = listed.iter().filter_map(|&ci| rail(ci)).collect(); + for &l in listed.iter().filter_map(|&ci| given.get(ci)).flatten() { + let w = labels[l as usize]; + if w[0] & 0xff != Surface::Carriageway as u32 { + continue; + } + for &r in &rails { + let x = [Surface::Crossing as u32 | (w[0] & !0xff), w[1], w[2], r]; + if !paired[l as usize].contains(&r) && !labels.contains(&x) { + paired[l as usize].push(r); + labels.push(x); + } + } + } + } + let four = |mut v: Vec| { + v.retain(|&x| x != u32::MAX); + v.sort_unstable(); + v.dedup(); + v.resize(4, u32::MAX); + [v[0], v[1], v[2], v[3]] + }; + // The lines whose frame the paint of a way's label follows: its leg and the ways it meets at a + // joint; and its other lines: those partners. Each arm names the leg it leaves along. A junction's + // record holds its arms. + let joints_of = |w: u32| graph.joints.iter().filter(move |j| j.arms.iter().any(|a| a.way == w)); + let hosts: Vec<[u32; 4]> = (labels.iter()) + .map(|l| match (l[0] >> 8) & 0xff { + WAY_OWNER => { + let partners = + joints_of(l[1]).flat_map(|j| j.arms.iter().filter(|a| a.way != l[1]).map(|a| arm_line(a, j.pos))); + four(std::iter::once(l[2]).chain(partners).collect()) + } + _ => four(Vec::new()), + }) + .collect(); + let others: Vec<[u32; 4]> = (labels.iter().zip(&hosts)) + .map(|(l, h)| match (l[0] >> 8) & 0xff { + WAY_OWNER => four(h.iter().copied().filter(|&x| x != l[2]).collect()), + _ => four(Vec::new()), + }) + .collect(); + // A record per junction that a label names, in the order of the labels. + let mut named: Vec = Vec::new(); + for l in labels.iter().filter(|l| (l[0] >> 8) & 0xff == JUNCTION) { + if !named.contains(&l[1]) { + named.push(l[1]); + } + } + let sec = |w: u32| of_way.get(&w).map(|&l| &lines[l as usize].sec); + let junction_words = |id: u32| { + let j = &graph.junctions[id as usize]; + let host = (j.arms.iter().filter(|a| a.host)).filter_map(|a| sec(a.way)).min_by_key(|s| s.rank); + let parts: Vec<&super::points::Part> = (cands.iter()) + .filter(|c| c.label.owner == Owner::Junction(id)) + .flat_map(|c| c.relabel.iter().flatten()) + .collect(); + let mut w = vec![j.pos[0] as u32, j.pos[1] as u32, 0]; + for a in &j.arms { + let Some(&l) = of_way.get(&a.way) else { continue }; + let (l, line) = (l as usize, &lines[l as usize]); + let at = sample_at(graph, line, &a.at, j.pos); + let r = rec_line(l, legs::leg(&line.cuts, at, a.dir)); + let (lo, hi) = (rec[r as usize].1, rec[r as usize].2); + // The first sample past the seam of the region's part that holds the node; the node itself + // where the region has none. + let x = at as f64; + let part = parts.iter().find(|p| p.line == l && p.lo <= x + 1e-9 && x <= p.hi + 1e-9); + let last = match part { + Some(p) if a.dir > 0 => (p.hi.floor() as usize + 1).min(hi), + Some(p) => (p.lo.ceil() as usize).saturating_sub(1).max(lo), + None => at, + }; + let next = at.checked_add_signed(isize::from(a.dir)).filter(|n| (lo..=hi).contains(n)); + let d = next.map_or([0.0, 0.0], |n| { + [f64::from(line.p[n][0] - line.p[at][0]), f64::from(line.p[n][1] - line.p[at][1])] + }); + let len = libm::hypot(d[0], d[1]).max(1e-9); + let snorm = |v: f64| u32::from(libm::round((v / len).clamp(-1.0, 1.0) * 32767.0) as i16 as u16); + let stop = !a.host && host.zip(sec(a.way)).is_some_and(|(h, g)| stops(&rules.plan, h, g)); + let flags = if a.host { ARM_HOST } else { 0 } | if stop { ARM_STOP } else { 0 }; + crate::probe::field(crate::probe::Field::Span, (at - lo).max(last - lo)); + w.extend([r | flags, (at - lo) as u32 | ((last - lo) as u32) << 16, snorm(d[0]) | snorm(d[1]) << 16]); + } + let n = (w.len() - JR) / JR_ARM; + crate::probe::field(crate::probe::Field::JunctionArms, n); + crate::probe::field(crate::probe::Field::JunctionId, id as usize); + assert!(n < 1 << 8 && id < 1 << 16, "a junction record overflows its words"); + w[2] = n as u32 | id << 16; + w + }; + let junctions: Vec> = named.iter().map(|&id| junction_words(id)).collect(); + // Centre-line segments within their half-width and LINE_PAD_M of a bin. + let mut segs: Vec> = vec![Vec::new(); n_bins]; + let pad = units(LINE_PAD_M); + let seg_box_of = |a: P, b: P| [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])].map(f64::from); + for (li, &(l, lo, hi)) in rec.iter().enumerate() { + let line = &lines[l]; + for i in 0..hi - lo { + let (a, b) = (line.p[lo + i], line.p[lo + i + 1]); + let reach = line.h[lo + i].max(line.h[lo + i + 1]) + pad; + let Some((c, r)) = bins_of(seg_box_of(a, b), reach) else { continue }; + crate::probe::field(crate::probe::Field::Line, li); + crate::probe::field(crate::probe::Field::Sample, i); + for row in r[0]..=r[1] { + for col in c[0]..=c[1] { + if clip(a, b, square(col, row, reach)).is_some() { + segs[(row * BINS + col) as usize].push(li as u32 | (i as u32) << 16); + } + } + } + } + } + // The paint reads a label's host lines, its other lines and its material line at their segment + // nearest the point: in every bin that a point's, region's or round's label reaches, each set's + // segments that can be nearest to a point of the bin. A segment farther from the bin than the + // set's nearest one plus the bin's diagonal is nearer to no point of it. + let diag = f64::from(BIN_UNITS) * std::f64::consts::SQRT_2; + for b in 0..n_bins { + let mut sets: Vec<[u32; 4]> = Vec::new(); + let mut at = 0; + while at < items[b].len() { + let ci = (items[b][at] & 0xffff) as usize; + at = skip_item(&items[b], at); + if !cands.get(ci).is_some_and(|c| c.label.owner != Owner::Terrain && kind(c) != WAY) { + continue; + } + for &l in &given[ci] { + let own = [labels[l as usize][2], u32::MAX, u32::MAX, u32::MAX]; + // A junction's frames search the bin for the lines of its record's arms: its hosts and its guests. + let [h, o] = if (labels[l as usize][0] >> 8) & 0xff == JUNCTION { + let j = &graph.junctions[labels[l as usize][1] as usize]; + let lines = |host: bool| -> Vec { + j.arms.iter().filter(|a| a.host == host).map(|a| arm_line(a, j.pos)).collect() + }; + [four(lines(true)), four(lines(false))] + } else { + [hosts[l as usize], others[l as usize]] + }; + for h in [h, o, own] { + if h[0] != u32::MAX && !sets.contains(&h) { + sets.push(h); + } + } + } + } + let (col, row) = (b as i32 % BINS, b as i32 / BINS); + let bx = square(col, row, 0.0); + let mut wanted: Vec = Vec::new(); + for h in sets { + let found: Vec<(u32, usize, f64)> = (h.iter().filter(|&&l| l != u32::MAX)) + .flat_map(|&l| { + let p = rec_points(l as usize); + (0..p.len().saturating_sub(1)).map(move |i| (l, i, seg_box(p[i], p[i + 1], bx))) + }) + .collect(); + let near = found.iter().map(|s| s.2).fold(f64::INFINITY, f64::min); + for &(l, i, _) in found.iter().filter(|s| s.2 <= near + diag) { + crate::probe::field(crate::probe::Field::Line, l as usize); + crate::probe::field(crate::probe::Field::Sample, i); + } + wanted.extend(found.iter().filter(|s| s.2 <= near + diag).map(|&(l, i, _)| l | (i as u32) << 16)); + } + wanted.retain(|w| !segs[b].contains(w)); + wanted.sort_unstable(); + wanted.dedup(); + segs[b].append(&mut wanted); + } + // The heights' segments within their reach and HEIGHT_PAD_M of a bin, and the discs whose circle + // grown by the greater reach of its two lines meets a bin: a fan relates its lines only within their + // feathers past its circle. A segment's reach is the one that the heights read: its half-width, the + // class's shoulder and verge, and the class's slope reach or the least feather, whatever a taper + // narrows the bands to. + let mut hsegs: Vec> = vec![Vec::new(); window.len()]; + let mut hdiscs: Vec> = vec![Vec::new(); window.len()]; + let hpad = units(HEIGHT_PAD_M); + let mut line_reach = vec![0.0f64; lines.len()]; + for (li, &(l, lo, hi)) in rec.iter().enumerate() { + let line = &lines[l]; + let sec = &line.sec; + let side = units(sec.shoulder_m + sec.verge_m + sec.reach_m.max(rules.plan.heights.feather_min_m)); + for i in 0..hi - lo { + let (a, b) = (line.p[lo + i], line.p[lo + i + 1]); + let reach = line.h[lo + i].max(line.h[lo + i + 1]) + side + hpad; + line_reach[l] = line_reach[l].max(reach); + let Some((c, r)) = bins_in(seg_box_of(a, b), reach, window.wide) else { continue }; + crate::probe::field(crate::probe::Field::Line, li); + crate::probe::field(crate::probe::Field::Sample, i); + for row in r[0]..=r[1] { + for col in c[0]..=c[1] { + if clip(a, b, square(col, row, reach)).is_some() { + hsegs[window.at(col, row)].push(li as u32 | (i as u32) << 16); + } + } + } + } + } + // A ceiling line's segments within their reach (`ceiling_end_reach` for the first and the last) and + // HEIGHT_PAD_M of a bin of the cell: last in each bin, so a reader of storey 0 stops before them and the + // ceiling walks them from the end. + let release = units(heights.ceiling_release_m); + for (k, line) in ceilings.iter().enumerate() { + let li = rec.len() + k; + let n = line.p.len(); + for i in 0..n - 1 { + let (a, b) = (line.p[i], line.p[i + 1]); + let half = line.h[i].max(line.h[i + 1]); + let end = i == 0 || i + 2 == n; + let reach = if end { ceiling_end_reach(half, release) } else { half + release } + hpad; + let Some((c, r)) = bins_of(seg_box_of(a, b), reach) else { continue }; + crate::probe::field(crate::probe::Field::Line, li); + crate::probe::field(crate::probe::Field::Sample, i); + for row in r[0]..=r[1] { + for col in c[0]..=c[1] { + if clip(a, b, square(col, row, reach)).is_some() { + hsegs[window.at(col, row)].push(li as u32 | (i as u32) << 16); + } + } + } + } + } + for (ci, cand) in cands.iter().enumerate() { + for (di, d) in cand.discs.iter().enumerate() { + let reach = d.lines.iter().filter_map(|&l| line_reach.get(l)).fold(0.0, |r: f64, &x| r.max(x)); + let (x, y, reach) = (f64::from(d.centre[0]), f64::from(d.centre[1]), d.radius + reach); + let Some((c, r)) = bins_in([x, y, x, y], reach, window.wide) else { continue }; + crate::probe::field(crate::probe::Field::Candidate, ci); + crate::probe::field(crate::probe::Field::Disc, di); + for row in r[0]..=r[1] { + for col in c[0]..=c[1] { + let bx = square(col, row, 0.0); + let (dx, dy) = ((bx[0] - x).max(x - bx[2]).max(0.0), (bx[1] - y).max(y - bx[3]).max(0.0)); + if libm::hypot(dx, dy) <= reach { + hdiscs[window.at(col, row)].push(ci as u32 | (di as u32) << 16); + } + } + } + } + } + let mut words = vec![0u32; HEAD]; + words[0] = MAGIC; + words[1] = shapes.len() as u32; + words[2] = labels.len() as u32; + words[3] = (rec.len() + ceilings.len()) as u32; + words[10] = (origin.y / CELL_UNITS) as u32; + words.extend(rules.plan.heights.words()); + words[4] = words.len() as u32; + words.extend(&cands_w); + words[5] = words.len() as u32; + for ((l, h), o) in labels.iter().zip(&hosts).zip(&others) { + let mut l = *l; + if (l[0] >> 8) & 0xff == JUNCTION { + l[1] = named.iter().position(|&j| j == l[1]).unwrap() as u32; + } + words.extend(l.iter().chain(h).chain(o)); + } + words[6] = words.len() as u32; + words.extend(&lines_w); + words[7] = words.len() as u32; + words.extend(&samples_w); + words[8] = words.len() as u32; + words.extend(&extras); + words[12] = words.len() as u32; + words[13] = junctions.len() as u32; + let mut at = words.len() + junctions.len(); + for j in &junctions { + words.push(at as u32); + at += j.len(); + } + words.extend(junctions.iter().flatten()); + // The blend edges that a bin of the cell lists first: the records keep only those, and the build's + // window bins read the rest. + let n_blend = blend.len() / BLEND; + let mut listed = vec![false; n_blend]; + for b in 0..n_bins { + for &k in &bedges[window.at(b as i32 % BINS, b as i32 / BINS)] { + listed[k as usize] = true; + } + } + let mut order: Vec = (0..n_blend).collect(); + order.sort_by_key(|&k| !listed[k]); + let mut renumber = vec![0u32; n_blend]; + for (to, &k) in order.iter().enumerate() { + renumber[k] = to as u32; + } + for list in &mut bedges { + list.iter_mut().for_each(|k| *k = renumber[*k as usize]); + } + words[11] = words.len() as u32; + words.extend(order.iter().flat_map(|&k| &blend[BLEND * k..BLEND * (k + 1)])); + // The outline edges: the near level's from its plan and the block so far, which the paved field + // reads. + let edges = if with_outline { + outline_edges(&words, input, rules, &rims, &|q| { + let k = window.of(q); + Items { segs: &hsegs[k], discs: &hdiscs[k], blend: &bedges[k] } + }) + } else { + Vec::new() + }; + words.truncate(words[11] as usize + BLEND * listed.iter().filter(|&&l| l).count()); + words[14] = words.len() as u32; + words.extend(&edges); + // Per bin the outline edges within their host's reach of its square, by host line. A block with no + // outline edges lists none. + let oedges = outline_bins(cell, &edges, &|l| lines[rec[l as usize].0].sec.reach_m); + words[9] = words.len() as u32; + let heads = words.len(); + words.resize(heads + HEADER * n_bins, 0); + for b in 0..n_bins { + let w = window.at(b as i32 % BINS, b as i32 / BINS); + if items[b].is_empty() + && segs[b].is_empty() + && hsegs[w].is_empty() + && hdiscs[w].is_empty() + && bedges[w].is_empty() + && oedges[b].is_empty() + { + continue; + } + let before = words.len(); + { + use crate::probe::{field, Field}; + field(Field::BinCandidates, n_items[b] as usize); + field(Field::BinSegments, segs[b].len()); + field(Field::HeightSegments, hsegs[w].len()); + field(Field::HeightDiscs, hdiscs[w].len()); + field(Field::BinItems, items[b].len()); + field(Field::BlendEdges, bedges[w].len()); + } + words[heads + HEADER * b] = before as u32; + words[heads + HEADER * b + 1] = n_items[b] << 16 | segs[b].len() as u32; + words[heads + HEADER * b + 2] = (hsegs[w].len() as u32) << 16 | hdiscs[w].len() as u32; + // The words of the items let a reader find the segments without walking the items. + assert!( + items[b].len() < 1 << 16 && bedges[w].len() < 1 << 16, + "a bin's items or blend edges overflow its header" + ); + words[heads + HEADER * b + 3] = (items[b].len() as u32) << 16 | bedges[w].len() as u32; + words.extend(items[b].iter().chain(&segs[b]).chain(&hsegs[w]).chain(&hdiscs[w]).chain(&bedges[w])); + // The count of its outline edges, then the edges: half words, the first in the low half. + if !edges.is_empty() { + assert!(oedges[b].len() < 1 << 16, "a bin's outline edges overflow a half word"); + let half: Vec = std::iter::once(oedges[b].len() as u32).chain(oedges[b].iter().copied()).collect(); + words.extend(half.chunks(2).map(|k| k[0] | k.get(1).map_or(0, |&x| x << 16))); + } + stats.bins_used += 1; + stats.max_bin_words = stats.max_bin_words.max((words.len() - before) as u32); + } + stats.cands = shapes.len() as u32; + stats.labels = labels.len() as u32; + stats.lines = (rec.len() + ceilings.len()) as u32; + stats.samples = (samples_w.len() / SAMPLE) as u32; + Records { cell, words, stats } +} + +/// An edge of a blend face: its ends in frame units from the cell's origin, with the blend face on +/// its left, the blend face's label and the label of the face beyond it (None for terrain). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BlendEdge { + pub a: [i32; 2], + pub b: [i32; 2], + pub region: u32, + pub other: Option, +} + +/// The blend edges that q's bin lists (q in the closed cell square, as `find`): every one within +/// `MARGIN_M` of the bin. +pub fn blend_edges(words: &[u32], q: [f64; 2]) -> impl Iterator + '_ { + let cell = f64::from(CELL_UNITS as i32); + let inside = (0.0..=cell).contains(&q[0]) && (0.0..=cell).contains(&q[1]); + let bin = |v: f64| ((v / f64::from(BIN_UNITS)).floor() as i32).clamp(0, BINS - 1); + let head = words[9] as usize + HEADER * (bin(q[1]) * BINS + bin(q[0])) as usize; + let (start, n) = if inside { blend_items(words, head) } else { (0, 0) }; + words[start..start + n].iter().map(move |&k| blend_edge(words, k)) +} + +/// Blend edge k of a block. +pub fn blend_edge(words: &[u32], k: u32) -> BlendEdge { + let e = &words[words[11] as usize + BLEND * k as usize..][..BLEND]; + BlendEdge { + a: [e[0] as i32, e[1] as i32], + b: [e[2] as i32, e[3] as i32], + region: e[4], + other: (e[5] != u32::MAX).then_some(e[5]), + } +} + +/// The start and the count of the blend edge items of the bin whose header is at `head`. +fn blend_items(words: &[u32], head: usize) -> (usize, usize) { + let h = words[head + 2]; + let at = words[head] as usize + (words[head + 3] >> 16) as usize; + let at = at + (words[head + 1] & 0xffff) as usize + (h >> 16) as usize + (h & 0xffff) as usize; + (at, (words[head + 3] & 0xffff) as usize) +} + +/// The words of label `id` of a block. +pub fn label(words: &[u32], id: u32) -> &[u32] { + &words[words[5] as usize + LABEL * id as usize..][..LABEL] +} + +/// The junction record of label `id` (`JR`), none for a label that no junction owns. +pub fn junction(words: &[u32], id: u32) -> Option<&[u32]> { + let l = label(words, id); + if (l[0] >> 8) & 0xff != JUNCTION { + return None; + } + let at = words[words[12] as usize + l[1] as usize] as usize; + Some(&words[at..at + JR + JR_ARM * (words[at + 2] & 0xff) as usize]) +} + +/// The graph's id of the owner of label `id`: a junction's from its record. +pub fn owner(words: &[u32], id: u32) -> u32 { + junction(words, id).map_or(label(words, id)[1], |j| j[2] >> 16) +} + +fn cand(words: &[u32], ci: u32) -> &[u32] { + &words[words[4] as usize + CAND * ci as usize..][..CAND] +} + +/// The word after the candidate item at `at`. +pub(crate) fn skip_item(words: &[u32], mut at: usize) -> usize { + let runs = words[at + 1]; + at += 2; + for _ in 0..runs { + at += 1 + 2 * words[at] as usize; + } + at +} + +fn cross(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[1] - a[1] * b[0] +} + +/// Whether point p moved by (ε, ε²) lies left of the line through a along e. +fn left(e: [f64; 2], a: [f64; 2], p: [f64; 2]) -> bool { + let s = cross(e, [p[0] - a[0], p[1] - a[1]]); + if s != 0.0 { + return s > 0.0; + } + e[1] < 0.0 || (e[1] == 0.0 && e[0] > 0.0) +} + +/// The change of the winding number from c to q, both moved by (ε, ε²), across edge ab: +1 where q +/// enters the side on the edge's left. In doubled units. +fn crossing(a: [f64; 2], b: [f64; 2], c: [f64; 2], q: [f64; 2]) -> i32 { + let e = [b[0] - a[0], b[1] - a[1]]; + let (sc, sq) = (left(e, a, c), left(e, a, q)); + if sc == sq { + return 0; + } + // The ends of the edge against the moved segment: v − (c + (ε, ε²)) across d. + let d = [q[0] - c[0], q[1] - c[1]]; + let side = |v: [f64; 2]| { + let s = cross(d, [v[0] - c[0], v[1] - c[1]]); + if s != 0.0 { + s > 0.0 + } else { + d[1] > 0.0 || (d[1] == 0.0 && d[0] < 0.0) + } + }; + if side(a) == side(b) { + 0 + } else if sq { + 1 + } else { + -1 + } +} + +/// Whether q lies past a cut: on its right, within its length, as the overlay's `past`. +fn past(cut: &[u32], q: [f64; 2]) -> bool { + let [a0, a1, b0, b1] = [0, 1, 2, 3].map(|k| f64::from(cut[k] as i32)); + let (u, v) = ([b0 - a0, b1 - a1], [q[0] - a0, q[1] - a1]); + let along = u[0] * v[0] + u[1] * v[1]; + cross(u, v) < 0.0 && (0.0..=u[0] * u[0] + u[1] * u[1]).contains(&along) +} + +/// The label of a block at point q of the closed cell square (frame units from the cell's origin), +/// none for terrain: the overlay's decision over the candidates that cover q. A point on an edge +/// reads as moved by (ε, ε²) in frame axes, so every cell breaks a tie alike; the tests are exact +/// for q on a grid of 1/1024 unit. A fan or round leaves out the disc of its circle: its arc is the +/// true circle where the overlay's is its chords. +pub fn find(words: &[u32], q: [f64; 2]) -> Option { + let cell = f64::from(CELL_UNITS as i32); + if !(0.0..=cell).contains(&q[0]) || !(0.0..=cell).contains(&q[1]) { + return None; + } + let bin = |v: f64| ((v / f64::from(BIN_UNITS)).floor() as i32).min(BINS - 1); + let (col, row) = (bin(q[0]), bin(q[1])); + let head = words[9] as usize + HEADER * (row * BINS + col) as usize; + let (mut at, n_cands, n_segs) = (words[head] as usize, (words[head + 1] >> 16) as usize, words[head + 1] & 0xffff); + let c = [2.0 * f64::from(reference(col)) + 1.0, 2.0 * f64::from(reference(row)) + 1.0]; + let q2 = [2.0 * q[0], 2.0 * q[1]]; + let extras = &words[words[8] as usize..]; + let mut covered = Vec::new(); + for _ in 0..n_cands { + let ci = words[at] & 0xffff; + let mut w = ((words[at] >> 16) & 0xff) as i32 - 128; + let runs = words[at + 1]; + at += 2; + for _ in 0..runs { + let n = words[at] as usize; + let v = |k: usize| { + [2.0 * f64::from(words[at + 1 + 2 * k] as i32), 2.0 * f64::from(words[at + 2 + 2 * k] as i32)] + }; + for k in 0..n.saturating_sub(1) { + w += crossing(v(k), v(k + 1), c, q2); + } + at += 1 + 2 * n; + } + let k = cand(words, ci); + let in_disc = (0..k[6] as usize).any(|d| { + let e = &extras[k[5] as usize + DISC * d..]; + libm::hypot(q[0] - f64::from(e[0] as i32), q[1] - f64::from(e[1] as i32)) < f64::from(f32::from_bits(e[2])) + }); + if w != 0 && !in_disc { + covered.push(ci); + } + } + decide(words, &covered, q, &words[at..at + n_segs as usize]) +} + +/// The glob order of a line at q: of its sample nearest q among the bin's segments. +fn way_glob(words: &[u32], line: u32, q: [f64; 2], segs: &[u32]) -> u32 { + let first = words[words[6] as usize + LINE * line as usize + 2] as usize; + let mut best = (f64::INFINITY, u32::MAX); + for &s in segs.iter().filter(|&&s| s & 0xffff == line) { + for i in [(s >> 16) as usize, (s >> 16) as usize + 1] { + let w = &words[words[7] as usize + SAMPLE * (first + i)..]; + let (dx, dy) = (q[0] - f64::from(w[0] as i32), q[1] - f64::from(w[1] as i32)); + if dx * dx + dy * dy < best.0 { + best = (dx * dx + dy * dy, w[4]); + } + } + } + best.1 +} + +fn decide(words: &[u32], covered: &[u32], q: [f64; 2], segs: &[u32]) -> Option { + let extras = &words[words[8] as usize..]; + let glob = |ci: u32| { + let k = cand(words, ci); + if k[0] == WAY { + way_glob(words, k[4], q, segs) + } else { + k[2] + } + }; + let surface = |c: u32| label(words, cand(words, c)[3])[0] & 0xff; + let own = |c: u32| !matches!(cand(words, c)[0], REGION | OUTLINE); + let zone = covered.iter().any(|&c| own(c) && surface(c) == Surface::Zone as u32); + // Where a zone covers q, line water does not count: the water ends at the zone. + let water = |c: u32| { + let line = label(words, cand(words, c)[3])[2]; + line != u32::MAX && words[words[6] as usize + LINE * line as usize + 1] & WATER != 0 + }; + let rest: Vec = covered.iter().copied().filter(|&c| own(c) && !(zone && water(c))).collect(); + let best = rest.iter().map(|&c| cand(words, c)[1]).min()?; + let win = rest.iter().copied().filter(|&c| cand(words, c)[1] == best).min_by_key(|&c| glob(c))?; + let k = cand(words, win); + if k[0] == FILL { + return Some(k[3]); + } + let across = (0..k[8] as usize).map(|b| &extras[k[7] as usize + BEYOND * b..][..BEYOND]).find(|e| past(e, q)); + let mut id = across.map_or(k[3], |e| e[4]); + let l = label(words, id); + // A zone keeps itself in a region of its owner way, as the overlay's. + if (l[0] >> 8) & 0xff == WAY_OWNER && across.is_none() && l[0] & 0xff != Surface::Zone as u32 { + let w = l[1]; + let outside = |p: &[u32]| !(p[1] == 1 && past(&p[2..6], q)) && !(p[6] == 1 && past(&p[7..11], q)); + let region = (covered.iter().copied()) + .filter(|&c| cand(words, c)[0] == REGION) + .filter(|&c| { + let r = cand(words, c); + let parts = (0..r[10] as usize).map(|p| &extras[r[9] as usize + PART * p..][..PART]); + let mine: Vec<&[u32]> = parts.filter(|p| p[0] == w).collect(); + !mine.is_empty() && mine.iter().all(|p| outside(p)) + }) + .min_by_key(|&c| (cand(words, c)[1], cand(words, c)[2])); + if let Some(r) = region { + id = cand(words, r)[3]; + } + } + let l = label(words, id); + let rail = rest.iter().find(|&&c| label(words, cand(words, c)[3])[0] & 0xff == Surface::RailBed as u32); + if let (true, Some(&r)) = (l[0] & 0xff == Surface::Carriageway as u32, rail) { + let want = [Surface::Crossing as u32 | (l[0] & !0xff), l[1], l[2], label(words, cand(words, r)[3])[2]]; + let found = (0..words[2]).find(|&x| label(words, x)[..4] == want); + debug_assert!(found.is_some(), "no crossing variant of label {id} over a rail of the bin"); + if let Some(x) = found { + id = x; + } + } + Some(id) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn two_segments_of_one_line_are_cut_at_the_same_points_whatever_their_far_ends() { + // From a point on a cell line, along one exact line, to two far ends; north-south and oblique. + for (a, step, far) in [([1000, 0], [0, 1], [32222, 32768]), ([5, 40], [3, 7], [4600, 4681])] { + let end = |n: i32| [a[0] + n * step[0], a[1] + n * step[1]]; + let (p, q) = (bin_cuts(a, end(far[0])), bin_cuts(a, end(far[1]))); + let shared = p.len().min(q.len()) - 1; + assert!(shared >= 3, "{p:?}"); + assert_eq!(p[..shared], q[..shared]); + // Each piece spans at most a bin. + assert!(q.windows(2).all(|w| (0..2).all(|i| (w[1][i] - w[0][i]).abs() <= BIN_UNITS)), "{q:?}"); + } + } + + #[test] + fn a_guest_stops_where_its_look_is_not_the_hosts_or_its_finish_keeps_its_tread() { + let sections = crate::sections::Sections::embedded(); + let plan = &Rules::embedded().plan; + let way = |kind: &str, tags: &[(&str, &str)]| { + sections.way(kind, &tags.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(), false) + }; + let road = way("road", &[("highway", "residential")]); + let service = way("road", &[("highway", "service")]); + let dirt = way("path", &[("highway", "path"), ("surface", "dirt")]); + let gravel = way("road", &[("highway", "track"), ("surface", "gravel")]); + let pavers = way("path", &[("highway", "path"), ("surface", "paving_stones")]); + let cycleway = way("path", &[("highway", "cycleway"), ("surface", "asphalt")]); + assert!(stops(plan, &road, &dirt) && stops(plan, &road, &gravel)); + // Paved guests of another look keep it too: pavers at a service road, asphalt at a gravel track. + assert!(stops(plan, &service, &pavers) && stops(plan, &gravel, &cycleway)); + // A reach pair keeps the junction's look: asphalt at a gravel footway. + let gravel_footway = way("path", &[("highway", "footway"), ("surface", "gravel")]); + assert_eq!(plan.pair(gravel_footway.group, cycleway.group).mouth, Mouth::Reach); + assert!(!stops(plan, &gravel_footway, &cycleway)); + // A paved guest of the host's look does not stop; a soil one keeps its tread (`tread_finishes`). + let paved = way("road", &[("highway", "track"), ("surface", "asphalt")]); + let gravel_path = way("path", &[("highway", "path"), ("surface", "gravel")]); + assert!(!stops(plan, &road, &paved) && !stops(plan, &road, &road) && stops(plan, &gravel, &gravel_path)); + // Steps of another look stop at a road too, but their corners have no radius: no mouth. + let steps = way("path", &[("highway", "steps"), ("surface", "dirt")]); + assert_eq!(plan.pair(road.group, steps.group).mouth, Mouth::Stop); + assert_eq!(steps.corner_radius_m.max(steps.corner_radius_walk_m), 0.0); + assert!(!stops(plan, &road, &steps)); + } + + /// The angle of a unit vector, and the turn between two. + fn angle(v: [f64; 2]) -> f64 { + libm::atan2(v[1], v[0]) + } + + #[test] + fn the_frame_turns_no_tighter_than_its_least_radius_and_keeps_ordinary_bends_square() { + let least = 4000.0; + // A U of radius 4,500 units between two legs, sampled at uneven angles, so that the polyline's + // own mitre lines cross well within the least radius. + let mut p: Vec

= (0..6).map(|k| [0, -20_000 + 4_000 * k]).collect(); + let mut a = 0.0f64; + for step in [0.3, 0.05, 0.4, 0.1, 0.35, 0.05, 0.45, 0.2, 0.3, 0.1, 0.4, 0.2, 0.12] { + a += step; + p.push([(4_500.0 - 4_500.0 * libm::cos(a)) as i32, (4_500.0 * libm::sin(a)) as i32]); + } + p.extend((1..6).map(|k| [9_000, -4_000 * k])); + let raw = mitres(&p, &vec![1.0; p.len()], 30.0); + assert!(raw.iter().any(|m| m[2].min(m[3]) < 0.5 * least), "the polyline itself folds"); + let m = mitres(&p, &vec![least; p.len()], 30.0); + for (i, w) in m.iter().enumerate() { + assert!(w[2].min(w[3]) >= 0.99 * least, "vertex {i}: health radius {:?}", &w[2..]); + } + // The ends keep their chords, and a straight leg away from the bend stays square. + let n = p.len(); + let chord = |i: usize| angle([f64::from(p[i + 1][0] - p[i][0]), f64::from(p[i + 1][1] - p[i][1])]); + assert_eq!(angle([m[0][0], m[0][1]]), chord(0)); + assert!((angle([m[n - 1][0], m[n - 1][1]]) - chord(n - 2)).abs() < 1e-12); + assert!((angle([m[1][0], m[1][1]]) - chord(0)).abs() < 1e-12); + // An evenly sampled arc wider than the least radius stays square to the arc away from its ends. + let arc: Vec

= (0..40) + .map(|k| f64::from(k) * 0.05) + .map(|a| [libm::round(9_000.0 * libm::cos(a)) as i32, libm::round(9_000.0 * libm::sin(a)) as i32]) + .collect(); + let m = mitres(&arc, &vec![least; arc.len()], 30.0); + for (i, w) in m.iter().enumerate().take(arc.len() - 6).skip(6) { + let square = f64::from(i as u32) * 0.05 + PI / 2.0; + assert!(libm::remainder(angle([w[0], w[1]]) - square, 2.0 * PI).abs() < 1e-3, "vertex {i}"); + } + } +} diff --git a/host/obc-ground-plan/src/faces/records/storeys.rs b/host/obc-ground-plan/src/faces/records/storeys.rs new file mode 100644 index 0000000000..628bdebd33 --- /dev/null +++ b/host/obc-ground-plan/src/faces/records/storeys.rs @@ -0,0 +1,215 @@ +//! The storeys over the ground in a cell's one near block: each storey's records follow storey 0's in every +//! table, so a corner's label names a label of any storey. A storey's lines (`STOREY`, after the ceiling lines) +//! are its own; its height segments, discs, blend edges and centre-line segments come last in each bin's lists. +//! The bins list no candidate item of a storey over the ground: the mesh names its faces' labels, and no reader +//! decides one by point. + +use super::{encode, BEYOND, BLEND, CAND, DISC, HEADER, JR, JR_ARM, LABEL, LEG_SHIFT, LINE, SAMPLE, STOREY}; +use super::{BINS, JUNCTION}; +use crate::faces::deck::{DeckWay, Decks, Storeys, PIER_NEAR_M}; +use crate::faces::{candidates, window, Rules, Sliced, LAYERS}; +use crate::frame::CellKey; +use crate::graph::WayGraph; +use crate::tile::Geometry; +use crate::CellInput; + +/// The storeys over the ground near the cell, storey 1 first, with their records merged into `near` (storey 0's +/// block). A storey with no deck near the cell has no plan; without the feature `storeys` there is none. +pub fn storeys(graph: &WayGraph, input: &CellInput, rules: &Rules, cell: CellKey, near: &mut Vec) -> Storeys { + if !cfg!(feature = "storeys") { + return Storeys::default(); + } + let decks = Decks::of(graph, input); + let top = decks.storey.iter().copied().max().unwrap_or(0); + let mut out = Storeys::default(); + for k in 1..=top { + let c = candidates(graph, input, rules, cell, k, LAYERS, true); + if c.cands.is_empty() { + continue; + } + let s = Sliced::new(&c); + let faces = s.cell(&c, cell, k); + let plan = s.plan(cell, k, &s.map(), &s.labels); + let sub = encode(cell, graph, input, rules, (&c.lines, &[]), &c.cands, &plan, false); + *near = merge(near, &sub.words, k, &|w| DeckWay::of(graph, input, rules, w, &decks).finish_bits()); + for w in faces.faces.iter().filter_map(|f| f.material) { + if let Err(k) = out.ways.binary_search_by_key(&w, |x| x.0) { + out.ways.insert(k, (w, DeckWay::of(graph, input, rules, w, &decks))); + } + } + out.plans.push(faces); + } + if !out.plans.is_empty() { + let o = cell.origin(); + let near_m = window(cell, PIER_NEAR_M); + for f in input.features.iter().filter(|f| f.kind == "bridge-pier" && f.geometry == Geometry::Point) { + for p in f.parts.iter().filter_map(|p| p.points.first()) { + let at = [(p.x - o.x) as i32, (p.y - o.y) as i32]; + if (near_m[0]..=near_m[2]).contains(&at[0]) + && (near_m[1]..=near_m[3]).contains(&at[1]) + && !out.piers.contains(&at) + { + out.piers.push(at); + } + } + } + } + out +} + +fn add(v: u32, by: u32) -> u32 { + if v == u32::MAX { + v + } else { + v + by + } +} + +/// Block `main` with the records of block `sub` of storey `storey` after its own in every table, their indices +/// moved past main's; a line of way w takes `bits(w)` into its finish word. Main's words keep their values, its +/// offsets move. +fn merge(main: &[u32], sub: &[u32], storey: i8, bits: &dyn Fn(u32) -> u32) -> Vec { + let (c0, l0, n0) = (main[1], main[2], main[3]); + let x0 = main[12] - main[8]; + let j0 = main[13]; + let e0 = (main[14] - main[11]) / BLEND as u32; + let s0 = (main[8] - main[7]) / SAMPLE as u32; + let mut w = main[..main[4] as usize].to_vec(); + w[1] += sub[1]; + w[2] += sub[2]; + w[3] += sub[3]; + // Candidates: the label, the line and the offsets into the extras. + w.extend(&main[main[4] as usize..main[5] as usize]); + let sub_cands = &sub[sub[4] as usize..sub[5] as usize]; + for k in sub_cands.chunks(CAND) { + let mut k = k.to_vec(); + k[3] = add(k[3], l0); + k[4] = add(k[4], n0); + for at in [5, 7, 9] { + k[at] += x0; + } + w.extend(k); + } + w[5] = w.len() as u32; + w.extend(&main[main[5] as usize..main[6] as usize]); + for l in sub[sub[5] as usize..sub[6] as usize].chunks(LABEL) { + let mut l = l.to_vec(); + if (l[0] >> 8) & 0xff == JUNCTION { + l[1] += j0; + } + for x in &mut l[2..] { + *x = add(*x, n0); + } + w.extend(l); + } + w[6] = w.len() as u32; + w.extend(&main[main[6] as usize..main[7] as usize]); + for l in sub[sub[6] as usize..sub[7] as usize].chunks(LINE) { + let mut l = l.to_vec(); + l[1] |= STOREY | bits(l[0]) | u32::from(storey as u8) << LEG_SHIFT; + l[2] += s0; + w.extend(l); + } + w[7] = w.len() as u32; + w.extend(&main[main[7] as usize..main[8] as usize]); + w.extend(&sub[sub[7] as usize..sub[8] as usize]); + w[8] = w.len() as u32; + w.extend(&main[main[8] as usize..main[12] as usize]); + let mut extras = sub[sub[8] as usize..sub[12] as usize].to_vec(); + for k in sub_cands.chunks(CAND) { + for d in 0..k[6] as usize { + let at = k[5] as usize + DISC * d; + extras[at + 3] = add(extras[at + 3], n0); + extras[at + 4] = add(extras[at + 4], n0); + } + for b in 0..k[8] as usize { + let at = k[7] as usize + BEYOND * b + 4; + extras[at] = add(extras[at], l0); + } + } + w.extend(extras); + // Junctions: a table of offsets, then the records, whose arms name their lines in the low half word. + w[12] = w.len() as u32; + w[13] = j0 + sub[13]; + let record = |b: &[u32], k: u32| { + let at = b[b[12] as usize + k as usize] as usize; + b[at..at + JR + JR_ARM * (b[at + 2] & 0xff) as usize].to_vec() + }; + let mut records: Vec> = (0..j0).map(|k| record(main, k)).collect(); + for k in 0..sub[13] { + let mut r = record(sub, k); + for a in r[JR..].chunks_mut(JR_ARM) { + a[0] = (a[0] & !0xffff) | ((a[0] & 0xffff) + n0); + } + records.push(r); + } + let mut at = w.len() + records.len(); + for r in &records { + w.push(at as u32); + at += r.len(); + } + w.extend(records.iter().flatten()); + w[11] = w.len() as u32; + w.extend(&main[main[11] as usize..main[14] as usize]); + for b in sub[sub[11] as usize..sub[14] as usize].chunks(BLEND) { + w.extend(&b[..4]); + w.extend([add(b[4], l0), add(b[5], l0)]); + } + w[14] = w.len() as u32; + w.extend(&main[main[14] as usize..main[9] as usize]); + // The bins: main's items; each list with the storey's after main's; main's outline edges. + w[9] = w.len() as u32; + let heads = w.len(); + let n_bins = (BINS * BINS) as usize; + w.resize(heads + HEADER * n_bins, 0); + let outline = main[14] < main[9]; + for b in 0..n_bins { + let lists = |x: &[u32], outline: bool| -> [Vec; 6] { + let h = x[9] as usize + HEADER * b; + if x[h] == 0 { + return Default::default(); + } + let at = x[h] as usize; + let (n_items, n_segs) = ((x[h + 3] >> 16) as usize, (x[h + 1] & 0xffff) as usize); + let (n_hs, n_hd, n_be) = + ((x[h + 2] >> 16) as usize, (x[h + 2] & 0xffff) as usize, (x[h + 3] & 0xffff) as usize); + let mut k = at; + let mut take = |n: usize| { + let v = x[k..k + n].to_vec(); + k += n; + v + }; + let (items, segs, hs, hd, be) = (take(n_items), take(n_segs), take(n_hs), take(n_hd), take(n_be)); + let rest = if outline { + let n = (x[k] & 0xffff) as usize; + x[k..k + (n + 2) / 2].to_vec() + } else { + Vec::new() + }; + [items, segs, hs, hd, be, rest] + }; + let [items, mut segs, mut hs, mut hd, mut be, rest] = lists(main, outline); + let [_, s_segs, s_hs, s_hd, s_be, _] = lists(sub, false); + let line = |v: &u32| (v & !0xffff) | ((v & 0xffff) + n0); + segs.extend(s_segs.iter().map(line)); + hs.extend(s_hs.iter().map(line)); + hd.extend(s_hd.iter().map(|v| (v & !0xffff) | ((v & 0xffff) + c0))); + be.extend(s_be.iter().map(|v| v + e0)); + if items.is_empty() && segs.is_empty() && hs.is_empty() && hd.is_empty() && be.is_empty() && rest.is_empty() { + continue; + } + assert!(segs.len() < 1 << 16 && hs.len() < 1 << 16 && hd.len() < 1 << 16 && be.len() < 1 << 16); + let n_items = (main[main[9] as usize + HEADER * b + 1] >> 16) * u32::from(!items.is_empty()); + let h = heads + HEADER * b; + w[h] = w.len() as u32; + w[h + 1] = n_items << 16 | segs.len() as u32; + w[h + 2] = (hs.len() as u32) << 16 | hd.len() as u32; + w[h + 3] = (items.len() as u32) << 16 | be.len() as u32; + w.extend(items.iter().chain(&segs).chain(&hs).chain(&hd).chain(&be)); + // A block with outline edges lists their count in every bin it lists. + if outline { + w.extend(if rest.is_empty() { vec![0] } else { rest }); + } + } + w +} diff --git a/host/obc-ground-plan/src/faces/rules.rs b/host/obc-ground-plan/src/faces/rules.rs new file mode 100644 index 0000000000..8e3535bb89 --- /dev/null +++ b/host/obc-ground-plan/src/faces/rules.rs @@ -0,0 +1,380 @@ +//! The rules of the faces: `plan.json` (shape values, ranks, junction pair rules) with the class +//! fields of `roads.json` that `Sections` reads, and the faces' rows of the reach table. + +use std::collections::BTreeMap; +use std::sync::OnceLock; + +use serde_json::{Map, Value}; + +use super::heights::{HeightRules, Legs, RULE_FIELDS}; +use super::records::MARGIN_M; +use crate::frame::CHAIN_MAX_M; +use crate::graph::{Structures, HEADING_M, ROOM_MAX_M, SNAP_REACH_M}; +use crate::sections::HALF_MAX_M; +use crate::sections::{Finish, Reach, Sections}; + +/// The overlay ranks, each named once in `ranks`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Rank { + Carriageway, + Platform, + RailBed, + ShoulderPaved, + WaterLine, + Shoulder, + Verge, + Zone, + Bank, + Slope, + Terrain, +} + +const RANKS: [(&str, Rank); 11] = [ + ("carriageway", Rank::Carriageway), + ("platform", Rank::Platform), + ("rail_bed", Rank::RailBed), + ("shoulder_paved", Rank::ShoulderPaved), + ("water_line", Rank::WaterLine), + ("shoulder", Rank::Shoulder), + ("verge", Rank::Verge), + ("zone", Rank::Zone), + ("bank", Rank::Bank), + ("slope", Rank::Slope), + ("terrain", Rank::Terrain), +]; + +/// How a guest meets its host. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mouth { + /// The guest's carriageway reaches the host's carriageway edge. + Reach, + /// The guest stops at the host's core edge. + Stop, + /// The bands meet by key only. + Join, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pair { + pub mouth: Mouth, + pub blend: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PlanRules { + /// How far a point's arms reach along their ways: its rounds and its seams read this far. + pub extent_m: f64, + /// A seam lies this far past the farthest point that a point's rounding or another arm reaches. + pub seam_m: f64, + /// Where the two arms of a joint differ in half-width, the wider one's carriageway edge runs into + /// the narrower one's by this much per metre along it, over at most `extent_m`. The edge then turns + /// by atan(0.15) = 8.5° at each end of the taper: under the kink check's `CORNER_TURN` (10.5°) by + /// 2°, so neither end needs a round and a joint's own small turn there still makes no corner. + pub taper_rate: f64, + /// The block `heights`. + pub heights: HeightRules, + /// The half-width of a platform line without a `width` tag. + pub platform_half_m: f64, + /// A platform's `reach_m`: its edge is a wall, with no blend into the ground. + pub platform_reach_m: f64, + /// Per rank, its place in the list `ranks` of `plan.json`. + ranks: [u8; RANKS.len()], + /// "host group/guest group" and "default". + pairs: BTreeMap, + /// Per finish, whether it is in `tread_finishes`: a guest of it keeps its own tread at a stop + /// mouth also beside a host of its look. + tread: [bool; 12], +} + +impl PlanRules { + pub fn rank(&self, rank: Rank) -> u8 { + self.ranks[rank as usize] + } + + /// The pair rule of a guest group at a host group, else `default`. + pub fn pair(&self, host: &str, guest: &str) -> Pair { + self.pairs.get(&format!("{host}/{guest}")).copied().unwrap_or(self.pairs["default"]) + } + + pub fn keeps_tread(&self, finish: Finish) -> bool { + self.tread[finish as usize] + } +} + +/// The rules that `faces::build` reads. +#[derive(Clone, Debug, PartialEq)] +pub struct Rules { + pub sections: Sections, + pub plan: PlanRules, + /// The block `structures`: the levels of the way graph. + pub structures: Structures, + reaches: Vec, +} + +fn number(row: &Map, field: &str) -> Result { + match row.get(field) { + Some(Value::Object(_)) => Err(format!("plan.json {field}: a value by place is not read yet")), + Some(v) => { + v.as_f64().filter(|v| *v >= 0.0).ok_or_else(|| format!("plan.json {field}: not a number of 0 or more")) + } + None => Err(format!("plan.json: no field {field}")), + } +} + +impl Rules { + /// The committed tables, parsed once. It panics on an invalid table; a test parses them. + pub fn embedded() -> &'static Rules { + static RULES: OnceLock = OnceLock::new(); + RULES.get_or_init(|| { + Rules::parse(Sections::embedded().clone(), include_str!("../../../../data/trailview/plan.json")) + .unwrap_or_else(|e| panic!("data/trailview: {e}")) + }) + } + + pub fn parse(sections: Sections, plan: &str) -> Result { + let json: Value = serde_json::from_str(plan).map_err(|e| format!("plan.json: {e}"))?; + let top = json.as_object().ok_or("plan.json: not an object")?; + let heights = top.get("heights").and_then(Value::as_object).ok_or("plan.json: no object heights")?; + let h = |field: &str| number(heights, field).map_err(|e| e.replace("plan.json ", "plan.json heights.")); + let mut values = [0.0; RULE_FIELDS.len()]; + for (v, field) in values.iter_mut().zip(RULE_FIELDS) { + *v = h(field)?; + } + if values[RULE_FIELDS.iter().position(|&f| f == "region_fade_m").unwrap()] > MARGIN_M { + return Err("plan.json heights.region_fade_m: over the records' MARGIN_M".into()); + } + let legs = match heights.get("legs").and_then(Value::as_str) { + Some("ramp") => Legs::Ramp, + Some("wall") => Legs::Wall, + _ => return Err("plan.json heights.legs: not ramp or wall".into()), + }; + let names = top.get("ranks").and_then(Value::as_array).ok_or("plan.json: no list ranks")?; + let names: Vec<&str> = names.iter().filter_map(Value::as_str).collect(); + let mut ranks = [u8::MAX; RANKS.len()]; + for (at, name) in names.iter().enumerate() { + let Some(&(_, rank)) = RANKS.iter().find(|(n, _)| n == name) else { + return Err(format!("plan.json ranks: an unknown rank {name:?}")); + }; + if ranks[rank as usize] != u8::MAX { + return Err(format!("plan.json ranks: {name:?} twice")); + } + ranks[rank as usize] = at as u8; + } + if let Some(&(name, _)) = RANKS.iter().find(|(_, r)| ranks[*r as usize] == u8::MAX) { + return Err(format!("plan.json ranks: no rank {name:?}")); + } + let classes: Vec<_> = (0..).map_while(|rank| sections.class_faces(rank)).collect(); + // The groups of roads.json, and line water's. + let groups: Vec<&str> = classes.iter().map(|c| c.group).chain(["water"]).collect(); + let mut pairs = BTreeMap::new(); + for (key, row) in top.get("pairs").and_then(Value::as_object).ok_or("plan.json: no object pairs")? { + if key != "default" { + let known = key.split_once('/').is_some_and(|(a, b)| groups.contains(&a) && groups.contains(&b)); + if !known { + return Err(format!("plan.json pairs {key:?}: not two groups of roads.json")); + } + } + let row = row.as_object().ok_or_else(|| format!("plan.json pairs {key:?}: not an object"))?; + let mouth = match row.get("mouth").and_then(Value::as_str) { + Some("reach") => Mouth::Reach, + Some("stop") => Mouth::Stop, + Some("join") => Mouth::Join, + _ => return Err(format!("plan.json pairs {key:?}.mouth: not reach, stop or join")), + }; + let blend = row.get("blend").and_then(Value::as_bool); + let blend = blend.ok_or_else(|| format!("plan.json pairs {key:?}.blend: not true or false"))?; + pairs.insert(key.clone(), Pair { mouth, blend }); + } + if !pairs.contains_key("default") { + return Err("plan.json pairs: no default".into()); + } + let mut tread = [false; 12]; + for name in top.get("tread_finishes").and_then(Value::as_array).ok_or("plan.json: no list tread_finishes")? { + let at = Finish::ALL.iter().position(|f| Some(f.name()) == name.as_str()); + tread[at.ok_or_else(|| format!("plan.json tread_finishes: {name} is no finish"))?] = true; + } + let block = top.get("structures").and_then(Value::as_object).ok_or("plan.json: no object structures")?; + let mut parts = [0.0; Structures::FIELDS.len()]; + for (v, field) in parts.iter_mut().zip(Structures::FIELDS) { + *v = number(block, field).map_err(|e| e.replace("plan.json ", "plan.json structures."))?; + } + let structures = Structures::new(parts); + let f = |field: &str| number(top, field); + let plan = PlanRules { + extent_m: f("extent_m")?, + seam_m: f("seam_m")?, + taper_rate: f("taper_rate")?, + platform_half_m: f("platform_half_m")?, + platform_reach_m: f("platform_reach_m")?, + heights: HeightRules::new(values, legs), + ranks, + pairs, + tread, + }; + if classes.iter().any(|c| c.return_grade <= 0.0) { + return Err("roads.json: a return_grade of 0".into()); + } + let mut reaches = reach_rows(&plan, band_m(§ions), inner_max_m(§ions), radius_max_m(§ions)); + let graph_m = (sections.reaches().iter()).filter(|r| r.owner == "graph").map(Reach::metres).fold(0.0, f64::max); + reaches.push(structures.reach(graph_m)); + for row in reaches.iter().filter(|r| r.chain) { + if row.metres() > CHAIN_MAX_M { + return Err(format!( + "the chain {:?} of faces is {} m, over CHAIN_MAX_M {CHAIN_MAX_M} m", + row.name, + row.metres() + )); + } + } + Ok(Rules { sections, plan, structures, reaches }) + } + + /// The reach table: the rows of `Sections` and those of the faces. + pub fn reaches(&self) -> impl Iterator { + self.sections.reaches().iter().chain(&self.reaches) + } +} + +/// The widest band past a carriageway edge: shoulder, verge and slope reach. +fn band_m(sections: &Sections) -> f64 { + (0..).map_while(|rank| sections.class_faces(rank)).map(|c| c.shoulder_m + c.verge_m + c.reach_m).fold(0.0, f64::max) +} + +/// The distance past the cell within which a point's faces can reach the window, so that a cell +/// rounds the points within it: a point's arms and seam, a half-width and the widest band. +pub fn input_m(plan: &PlanRules, sections: &Sections) -> f64 { + plan.extent_m + plan.seam_m + HALF_MAX_M + band_m(sections) +} + +/// The distance past the cell within which a cell's faces read points: a point within `input_m` +/// rounds its arms up to the next point, at most `extent_m` on. +pub fn points_m(plan: &PlanRules, sections: &Sections) -> f64 { + input_m(plan, sections) + plan.extent_m +} + +/// The greatest inner radius of a class. +pub fn inner_max_m(sections: &Sections) -> f64 { + (0..).map_while(|rank| sections.class_faces(rank)).map(|c| c.inner_radius_m).fold(0.0, f64::max) +} + +/// The terms of the outline rounds' reach: a round's feet lie within `extent_m / 2` of its place +/// along the outline, so its rings lie within that and its radius; a place's round depends on the +/// rounds of the places within `extent_m`; a round reads the outline that its circle can meet, +/// another radius on; the outline holds the carriageways of the ways within a half-width. It also +/// holds the fans of the points within `input_m`, which these terms do not bound. +fn outline_terms(plan: &PlanRules, inner_m: f64) -> [(&'static str, f64); 4] { + let round = plan.extent_m / 2.0 + inner_m; + [ + ("extent_m / 2 + inner radius: a round's rings", round), + ("extent_m: the places that a round depends on", plan.extent_m), + ("extent_m / 2 + 2 inner radii: the outline that it reads", round + inner_m), + ("HALF_MAX_M", HALF_MAX_M), + ] +} + +/// The greatest corner radius of a class, with a sidewalk or without. +fn corner_max_m(sections: &Sections) -> f64 { + (0..) + .map_while(|rank| sections.class_faces(rank)) + .map(|c| c.corner_radius_m.max(c.corner_radius_walk_m)) + .fold(0.0, f64::max) +} + +/// The greatest corner or inner radius of a class. +fn radius_max_m(sections: &Sections) -> f64 { + corner_max_m(sections).max(inner_max_m(sections)) +} + +/// The terms of the off-line test of a point's rounds past `input_m`: a round's centre lies up to +/// `extent_m` along an arm, a half-width and its radius off it, and the carriageways that its circle +/// meets lie another radius and half-width on. +fn off_terms(radius_m: f64) -> [(&'static str, f64); 2] { + [ + ("HALF_MAX_M + radius: a round's centre off its arm", HALF_MAX_M + radius_m), + ("radius + HALF_MAX_M: a carriageway it meets", radius_m + HALF_MAX_M), + ] +} + +/// The distance past the cell within which a cell's faces build carriageways: the points' +/// `input_m`, and the outline that the outline rounds read. +pub fn lines_m(plan: &PlanRules, sections: &Sections) -> f64 { + let outline: f64 = outline_terms(plan, inner_max_m(sections)).iter().map(|t| t.1).sum(); + input_m(plan, sections).max(outline) +} + +/// The distance past the cell within which a cell's faces read ways: the carriageways of `lines_m`, +/// and the ways that the rounds of the points within `input_m` test (`points_m` and `off_terms`). +pub fn ways_m(plan: &PlanRules, sections: &Sections) -> f64 { + let off: f64 = off_terms(radius_max_m(sections)).iter().map(|t| t.1).sum(); + lines_m(plan, sections).max(points_m(plan, sections) + off) +} + +/// The faces' rows: what a cell's faces read, and the chains through GP2's room decision. +fn reach_rows(plan: &PlanRules, band_m: f64, inner_m: f64, radius_m: f64) -> Vec { + let chain = |name: &str, terms: &[(&str, f64)]| Reach { + name: name.into(), + owner: "faces", + chain: true, + terms: terms.iter().map(|&(what, m)| (what.to_string(), m)).collect(), + }; + // GP2's `room_m` reads the room and a snap foot there. + let room = ROOM_MAX_M + 2.0 * SNAP_REACH_M; + let input = + [("extent_m", plan.extent_m), ("seam_m", plan.seam_m), ("HALF_MAX_M", HALF_MAX_M), ("widest band", band_m)]; + let mut points = input.to_vec(); + points.push(("extent_m: a run to the next point", plan.extent_m)); + let mut cell = vec![("GP2 room_m", room)]; + cell.extend(&points); + let mut hosts = vec![("HEADING_M", HEADING_M)]; + hosts.extend(input); + let mut outline = vec![("GP2 room_m", room)]; + outline.extend(outline_terms(plan, inner_m)); + let mut off = vec![("GP2 room_m", room)]; + off.extend(&points); + off.extend(off_terms(radius_m)); + let rows = [ + ("input", &input[..]), + ("cell", &cell), + ("hosts", &hosts), + ("points", &points), + ("outline", &outline), + ("off-line test", &off), + ]; + let mut rows: Vec = rows.iter().map(|(name, terms)| chain(&format!("faces {name}"), terms)).collect(); + // The records' blend edges are the neighbours' own up to `MARGIN_M` past the cell: the longest + // chain reads that much farther. + let longest = rows.iter().max_by(|a, b| a.metres().total_cmp(&b.metres())).map(|r| r.terms.clone()); + let mut terms = longest.unwrap_or_default(); + terms.push(("records MARGIN_M".into(), MARGIN_M)); + rows.push(Reach { name: "faces blend edges".into(), owner: "faces", chain: true, terms }); + rows +} + +#[cfg(test)] +mod tests { + use super::*; + + const PLAN: &str = include_str!("../../../../data/trailview/plan.json"); + + #[test] + fn the_committed_rules_parse_and_a_broken_one_names_its_field() { + let rules = Rules::embedded(); + assert_eq!(rules.plan.rank(Rank::Carriageway), 0); + assert_eq!(rules.plan.pair("road", "path").mouth, Mouth::Stop); + assert_eq!(rules.plan.pair("water", "road").mouth, Mouth::Join); + assert_eq!(rules.plan.pair("water", "water"), Pair { mouth: Mouth::Join, blend: true }); + let cell = rules.reaches().find(|r| r.name == "faces cell").unwrap(); + assert!(cell.metres() < 191.0); + let fails = |plan: &str| Rules::parse(Sections::embedded().clone(), plan).unwrap_err(); + assert!(fails(&PLAN.replacen(r#""verge", "#, "", 1)).contains(r#"no rank "verge""#)); + assert!(fails(&PLAN.replacen(r#""road/track""#, r#""road/lane""#, 1)).contains("not two groups")); + assert!(fails(&PLAN.replacen(r#""extent_m": 20"#, r#""extent_m": 100"#, 1)).contains("faces cell")); + assert!(fails(&PLAN.replacen(r#""legs": "ramp""#, r#""legs": "lean""#, 1)).contains("heights.legs")); + let wide = PLAN.replacen(r#""region_fade_m": 1.5"#, r#""region_fade_m": 3.5"#, 1); + assert!(fails(&wide).contains("heights.region_fade_m")); + for field in RULE_FIELDS { + let without = PLAN.replacen(&format!(r#""{field}":"#), r#""unread":"#, 1); + assert!(fails(&without).contains(&format!("no field {field}")), "{field}"); + } + } +} diff --git a/host/obc-ground-plan/src/faces/slice.rs b/host/obc-ground-plan/src/faces/slice.rs new file mode 100644 index 0000000000..051fe57ea3 --- /dev/null +++ b/host/obc-ground-plan/src/faces/slice.rs @@ -0,0 +1,662 @@ +//! One integer slice of the window by string contours, and the planar map of its patches: shared +//! vertices, half-edges with their twins, and the boundary cycles of any grouping of the patches. + +use std::cmp::Ordering; + +use i_overlay::core::fill_rule::FillRule; +use i_overlay::core::overlay::{ContourDirection, IntOverlayOptions}; +use i_overlay::core::solver::{Precision, Solver, Strategy}; +use i_overlay::i_float::int::point::IntPoint; +use i_overlay::string::overlay::StringOverlay; +use i_overlay::string::rule::StringRule; + +use super::geom::{area2, P}; +use crate::frame::CELL_UNITS; + +pub const NONE: u32 = u32::MAX; + +/// One solver for every slice: one path at every segment count, a snap radius of one unit, no threads. +fn solver() -> Solver { + Solver { strategy: Strategy::Frag, precision: Precision::ABSOLUTE, multithreading: None } +} + +fn options() -> IntOverlayOptions { + IntOverlayOptions { + preserve_input_collinear: true, + output_direction: ContourDirection::CounterClockwise, + preserve_output_collinear: true, + min_output_area: 0, + ogc: false, + } +} + +/// The slice works in tiles of this many frame units: a cell is 8 × 8 tiles, each sliced by the +/// segments that reach it. A pass of the overlay's solver then reads one tile, so a place that needs +/// many passes costs them in its tile only. The faces' rings and seams get a vertex at each tile line +/// they cross as their last change (`geom::grid_points`), so no tile rounds a crossing of its own side; +/// the snap rounding of all patches together joins the tiles. +pub const TILE: i64 = CELL_UNITS / 8; + +/// Whether coordinate x lies on a cell line. +fn line(x: i32) -> bool { + i64::from(x).rem_euclid(CELL_UNITS) == 0 +} + +/// The patches of the window [x0, y0, x1, y1] sliced by closed strings and open lines: each patch +/// its rings, ring 0 positive, holes negative. Also the number of input segments. +pub fn slice(window: [i32; 4], strings: &[Vec

], lines: &[[P; 2]]) -> (Vec>>, usize) { + let pt = |p: P| IntPoint::new(p[0], p[1]); + let [x0, y0, x1, y1] = window; + // The tile bounds along each axis. + let bounds = |lo: i32, hi: i32| { + let mut b = vec![lo]; + let mut v = (i64::from(lo).div_euclid(TILE) + 1) * TILE; + while v < i64::from(hi) { + b.push(v as i32); + v += TILE; + } + b.push(hi); + b + }; + let (bx, by) = (bounds(x0, x1), bounds(y0, y1)); + let cols = bx.len() - 1; + // Each segment goes to every tile whose closed square its box meets. + let range = |b: &[i32], lo: i32, hi: i32| -> std::ops::Range { + let first = b.partition_point(|&x| x < lo).saturating_sub(1); + let last = b.partition_point(|&x| x <= hi).min(b.len() - 1); + first..last.max(first) + }; + let mut tiles: Vec> = vec![Vec::new(); cols * (by.len() - 1)]; + let rings = + strings.iter().filter(|r| r.len() >= 2).flat_map(|r| (0..r.len()).map(move |i| [r[i], r[(i + 1) % r.len()]])); + let mut segments = 4; + for [a, b] in rings.chain(lines.iter().copied()) { + segments += 1; + let (xs, ys) = (range(&bx, a[0].min(b[0]), a[0].max(b[0])), range(&by, a[1].min(b[1]), a[1].max(b[1]))); + for j in ys { + for i in xs.clone() { + tiles[j * cols + i].push([a, b]); + } + } + } + let mut patches = Vec::new(); + for (t, segs) in tiles.iter().enumerate() { + let (i, j) = (t % cols, t / cols); + let square = [[bx[i], by[j]], [bx[i + 1], by[j]], [bx[i + 1], by[j + 1]], [bx[i], by[j + 1]]]; + if segs.is_empty() { + patches.push(vec![square.to_vec()]); + continue; + } + let mut overlay = StringOverlay::with_options(segs.len() + 4, options()); + overlay.add_shape_contour(&square.map(pt)); + for &[a, b] in segs { + overlay.add_string_line([pt(a), pt(b)]); + } + let Some(graph) = overlay.build_graph_view_with_solver(FillRule::NonZero, solver()) else { + crate::probe::hit(crate::probe::Cap::SliceFallback); + patches.push(vec![square.to_vec()]); + continue; + }; + let shapes = graph.extract_shapes_custom(StringRule::Slice, options()); + patches.extend( + shapes + .into_iter() + .map(|shape| shape.into_iter().map(|c| c.into_iter().map(|p| [p.x, p.y]).collect()).collect()), + ); + } + (patches, segments) +} + +/// Whether segment ab lies on one cell line. +pub fn on_cell_line(a: P, b: P) -> bool { + let line = |v: i32| i64::from(v).rem_euclid(CELL_UNITS) == 0; + (a[0] == b[0] && line(a[0])) || (a[1] == b[1] && line(a[1])) +} + +#[derive(Clone, Copy, Debug)] +pub struct Half { + pub a: u32, + pub b: u32, + pub patch: u32, + pub twin: u32, +} + +/// The planar map of a slice. +pub struct Map { + pub verts: Vec

, + pub half: Vec, + /// The outgoing half-edges of vertex v: `out[start[v]..start[v + 1]]`, by angle (counter-clockwise + /// in x, y). + start: Vec, + out: Vec, + patches: usize, +} + +/// The plan's precision in frame units (about 6 mm): every vertex of a plan lies on the global grid +/// of this step, and an edge that passes through the grid square of a vertex runs through it. +pub const PRECISION: i32 = 4; + +/// A coordinate on the grid of `PRECISION`: the nearest grid line, but one step inside where that +/// line is a cell line and the coordinate is not on it, so a vertex that only one cell holds never +/// lands on the line two cells share. +fn grid(v: i32) -> i32 { + let h = PRECISION / 2; + let g = (v + h).div_euclid(PRECISION) * PRECISION; + if line(g) && !line(v) { + if v > g { + g + PRECISION + } else { + g - PRECISION + } + } else { + g + } +} + +/// Whether p lies on a cell line. +fn border(p: P) -> bool { + line(p[0]) || line(p[1]) +} + +fn on_grid(p: P) -> P { + [grid(p[0]), grid(p[1])] +} + +/// The open square of the coordinates that round to grid coordinate g along one axis: half a step +/// each way, but up to the cell line where the next grid line is one, as `grid` rounds them. +fn square(g: i32) -> (i32, i32) { + let r = PRECISION / 2; + let lo = if line(g - PRECISION) { g - PRECISION } else { g - r }; + let hi = if line(g + PRECISION) { g + PRECISION } else { g + r }; + (lo, hi) +} + +/// Whether segment ab meets the open square of the points that round to h. +fn through(a: P, b: P, h: P) -> bool { + let ((lx, hx), (ly, hy)) = (square(h[0]), square(h[1])); + let (lo, hi) = ([lx, ly], [hx, hy]); + if a[0].max(b[0]) <= lo[0] || a[0].min(b[0]) >= hi[0] || a[1].max(b[1]) <= lo[1] || a[1].min(b[1]) >= hi[1] { + return false; + } + let side = + |c: P| i128::from(b[0] - a[0]) * i128::from(c[1] - a[1]) - i128::from(b[1] - a[1]) * i128::from(c[0] - a[0]); + let s = [side(lo), side([hi[0], lo[1]]), side(hi), side([lo[0], hi[1]])]; + !(s.iter().all(|&x| x >= 0) || s.iter().all(|&x| x <= 0)) +} + +/// Patches on the grid: the grid points by (y, x), and per patch its directed segments as pairs of +/// their indices, its area on their left. +pub struct Snapped { + pub verts: Vec

, + pub patches: Vec>, +} + +/// The hot squares that segment ab passes besides those of its ends: the grid points (with their +/// index) whose squares it meets, in order along it. A square reaches at most a whole step from its +/// grid point, so the candidates lie in a slab about the segment along its shorter extent: `verts` +/// is ordered by (y, x) and `by_x` by (x, y). +fn passed(a: P, b: P, verts: &[P], by_x: &[u32], out: &mut Vec<(P, u32)>) { + out.clear(); + let (ga, gb) = (on_grid(a), on_grid(b)); + let r = PRECISION; + let (x0, x1, y0, y1) = (a[0].min(b[0]) - r, a[0].max(b[0]) + r, a[1].min(b[1]) - r, a[1].max(b[1]) + r); + let mut test = |h: P, i: u32| { + // The square of a vertex on a cell line holds only the edges on that line: the next cell holds + // the line's vertices but not this cell's edges beside it. + if h != ga && h != gb && (!border(h) || on_cell_line(a, b)) && through(a, b, h) { + out.push((h, i)); + } + }; + if x1 - x0 <= y1 - y0 { + let from = by_x.partition_point(|&i| verts[i as usize][0] < x0); + for &i in &by_x[from..] { + let h = verts[i as usize]; + if h[0] > x1 { + break; + } + if (y0..=y1).contains(&h[1]) { + test(h, i); + } + } + } else { + let from = verts.partition_point(|h| h[1] < y0); + for (i, &h) in verts.iter().enumerate().skip(from) { + if h[1] > y1 { + break; + } + if (x0..=x1).contains(&h[0]) { + test(h, i as u32); + } + } + } + let d = [i128::from(b[0] - a[0]), i128::from(b[1] - a[1])]; + out.sort_unstable_by_key(|&(h, _)| (d[0] * i128::from(h[0] - a[0]) + d[1] * i128::from(h[1] - a[1]), h)); + out.dedup(); +} + +/// Snap rounding of the patches to the plan's precision: every vertex moves to its grid point, and +/// every edge runs through the grid point of each vertex whose square it passes (a hot square), in +/// order along it. Two patches that share an edge share its rounded path. Per patch, a segment and +/// its reverse cancel: a part of a patch thinner than the precision collapses, and a vertex or a step +/// closer than it merges. +pub fn snap_round(patches: &[Vec>]) -> Snapped { + let mut verts: Vec

= patches.iter().flatten().flatten().map(|&p| on_grid(p)).collect(); + verts.sort_unstable_by_key(|p| (p[1], p[0])); + verts.dedup(); + let mut by_x: Vec = (0..verts.len() as u32).collect(); + by_x.sort_unstable_by_key(|&i| verts[i as usize]); + let index = |p: P| verts.binary_search_by_key(&(p[1], p[0]), |q| (q[1], q[0])).unwrap() as u32; + // Every directed segment of every patch by its edge: the edge from its lesser end, the patch, and + // whether the segment runs that way. + let mut segs: Vec<([P; 2], u32, bool)> = Vec::new(); + for (k, rings) in patches.iter().enumerate() { + for ring in rings { + for i in 0..ring.len() { + let (a, b) = (ring[i], ring[(i + 1) % ring.len()]); + if a != b { + segs.push(if a < b { ([a, b], k as u32, true) } else { ([b, a], k as u32, false) }); + } + } + } + } + segs.sort_unstable(); + // Per patch, its rounded segments by edge key (lesser index high) with +1 along the key, −1 against. + let mut keyed: Vec> = vec![Vec::new(); patches.len()]; + let (mut via, mut path) = (Vec::new(), Vec::new()); + for group in segs.chunk_by(|x, y| x.0 == y.0) { + let [a, b] = group[0].0; + passed(a, b, &verts, &by_x, &mut via); + path.clear(); + path.push(index(on_grid(a))); + path.extend(via.iter().map(|&(_, i)| i)); + path.push(index(on_grid(b))); + for &(_, k, fwd) in group { + for w in path.windows(2).filter(|w| w[0] != w[1]) { + let (u, v) = if fwd { (w[0], w[1]) } else { (w[1], w[0]) }; + keyed[k as usize].push(if u < v { + ((u64::from(u) << 32) | u64::from(v), 1) + } else { + ((u64::from(v) << 32) | u64::from(u), -1) + }); + } + } + } + let patches = keyed + .into_iter() + .map(|mut keyed| { + keyed.sort_unstable(); + let mut out = Vec::new(); + for group in keyed.chunk_by(|x, y| x.0 == y.0) { + let n: i32 = group.iter().map(|x| x.1).sum(); + let (u, v) = ((group[0].0 >> 32) as u32, group[0].0 as u32); + for _ in 0..n.abs() { + out.push(if n > 0 { [u, v] } else { [v, u] }); + } + } + out + }) + .collect(); + Snapped { verts, patches } +} + +/// The order of directions by angle from +x toward +y, exact. +fn by_angle(u: [i64; 2], v: [i64; 2]) -> Ordering { + let half = |d: [i64; 2]| u8::from(!(d[1] > 0 || (d[1] == 0 && d[0] > 0))); + half(u).cmp(&half(v)).then_with(|| { + let c = i128::from(u[0]) * i128::from(v[1]) - i128::from(u[1]) * i128::from(v[0]); + 0.cmp(&c) + }) +} + +impl Map { + /// The map of the patches' rings as they are, not rounded. + #[cfg(test)] + pub fn exact(patches: Vec>>) -> Map { + let mut verts: Vec

= patches.iter().flatten().flatten().copied().collect(); + verts.sort_unstable_by_key(|p| (p[1], p[0])); + verts.dedup(); + let index = |p: P| verts.binary_search_by_key(&(p[1], p[0]), |q| (q[1], q[0])).unwrap() as u32; + let patches = (patches.iter()) + .map(|rings| { + (rings.iter()) + .flat_map(|ring| (0..ring.len()).map(move |i| [ring[i], ring[(i + 1) % ring.len()]])) + .map(|[a, b]| [index(a), index(b)]) + .collect() + }) + .collect(); + Map::new(Snapped { verts, patches }) + } + + /// The map of snapped patches. + pub fn new(snapped: Snapped) -> Map { + let Snapped { verts, patches } = snapped; + let mut half = Vec::new(); + for (patch, segments) in patches.iter().enumerate() { + for &[a, b] in segments { + if a != b { + half.push(Half { a, b, patch: patch as u32, twin: NONE }); + } + } + } + let key = |e: &Half| (u64::from(e.a) << 32) | u64::from(e.b); + let mut order: Vec<(u64, u32)> = half.iter().enumerate().map(|(h, e)| (key(e), h as u32)).collect(); + order.sort_unstable(); + for &(k, h) in &order { + let back = k.rotate_left(32); + if let Ok(at) = order.binary_search_by_key(&back, |x| x.0) { + half[h as usize].twin = order[at].1; + } + } + // The outgoing half-edges of each vertex: the runs of `order` by their first vertex, by angle. + let mut start = vec![0u32; verts.len() + 1]; + for e in &half { + start[e.a as usize + 1] += 1; + } + for v in 0..verts.len() { + start[v + 1] += start[v]; + } + let mut out: Vec = order.iter().map(|x| x.1).collect(); + let dir = |h: u32| { + let e = half[h as usize]; + let (a, b) = (verts[e.a as usize], verts[e.b as usize]); + [i64::from(b[0]) - i64::from(a[0]), i64::from(b[1]) - i64::from(a[1])] + }; + for v in 0..verts.len() { + out[start[v] as usize..start[v + 1] as usize].sort_by(|&x, &y| by_angle(dir(x), dir(y))); + } + Map { verts, half, start, out, patches: patches.len() } + } + + pub fn point(&self, v: u32) -> P { + self.verts[v as usize] + } + + /// The group of each patch: patches of one key that share an edge, and not across a cell line + /// unless `across`. `key` gives each patch's key. + pub fn groups(&self, key: &[u32], across: bool) -> Vec { + let mut root: Vec = (0..self.patches as u32).collect(); + fn find(root: &mut [u32], i: u32) -> u32 { + let mut i = i; + while root[i as usize] != i { + root[i as usize] = root[root[i as usize] as usize]; + i = root[i as usize]; + } + i + } + for e in &self.half { + if e.twin == NONE { + continue; + } + let other = self.half[e.twin as usize].patch; + if key[e.patch as usize] != key[other as usize] { + continue; + } + if !across && on_cell_line(self.point(e.a), self.point(e.b)) { + continue; + } + let (x, y) = (find(&mut root, e.patch), find(&mut root, other)); + root[x.max(y) as usize] = x.min(y); + } + (0..self.patches as u32).map(|i| find(&mut root, i)).collect() + } + + /// The group across half-edge h, or NONE past the window. + pub fn across(&self, group: &[u32], h: u32) -> u32 { + let t = self.half[h as usize].twin; + if t == NONE { + NONE + } else { + group[self.half[t as usize].patch as usize] + } + } + + /// Whether h bounds its group: the twin lies in another group or past the window. + pub fn bounds(&self, group: &[u32], h: u32) -> bool { + self.across(group, h) != group[self.half[h as usize].patch as usize] + } + + /// The next boundary half-edge of h's group after h: the first outgoing edge clockwise from h's + /// reverse at its end that bounds the same group. + pub fn next(&self, group: &[u32], h: u32) -> u32 { + let e = self.half[h as usize]; + let g = group[e.patch as usize]; + let (a, b) = (self.point(e.a), self.point(e.b)); + let back = [i64::from(a[0]) - i64::from(b[0]), i64::from(a[1]) - i64::from(b[1])]; + let list = &self.out[self.start[e.b as usize] as usize..self.start[e.b as usize + 1] as usize]; + let dir = |x: u32| { + let q = self.point(self.half[x as usize].b); + [i64::from(q[0]) - i64::from(b[0]), i64::from(q[1]) - i64::from(b[1])] + }; + // The last edge before `back` by angle, then on clockwise. + let start = list.partition_point(|&x| by_angle(dir(x), back) == Ordering::Less); + for k in 1..=list.len() { + let x = list[(start + list.len() - k) % list.len()]; + if group[self.half[x as usize].patch as usize] == g && self.bounds(group, x) { + return x; + } + } + unreachable!("a boundary half-edge has a successor in its group") + } + + /// The boundary cycles of each group, split at repeated vertices into simple loops: (group, loop + /// of vertex indices, twice its area, the half-edge that leaves each vertex). Ordered by the + /// first half-edge of each cycle. + pub fn loops(&self, group: &[u32]) -> Vec { + let mut seen = vec![false; self.half.len()]; + let mut out = Vec::new(); + for h0 in 0..self.half.len() as u32 { + if seen[h0 as usize] || !self.bounds(group, h0) { + continue; + } + let g = group[self.half[h0 as usize].patch as usize]; + let mut cycle = Vec::new(); + let mut h = h0; + while !seen[h as usize] { + seen[h as usize] = true; + cycle.push((self.half[h as usize].a, h)); + h = self.next(group, h); + } + let mut stack: Vec<(u32, u32)> = Vec::new(); + for (v, h) in cycle { + if let Some(at) = stack.iter().position(|&(w, _)| w == v) { + let lp = stack.split_off(at); + stack.push((v, h)); + push_loop(&mut out, g, lp, self); + } else { + stack.push((v, h)); + } + } + push_loop(&mut out, g, stack, self); + } + out + } +} + +/// A boundary loop of a group: the group, its vertices, twice its area, and the half-edge that +/// leaves each vertex. +pub type Loop = (u32, Vec, i128, Vec); + +fn push_loop(out: &mut Vec, g: u32, lp: Vec<(u32, u32)>, map: &Map) { + if lp.len() >= 3 { + let ring: Vec

= lp.iter().map(|&(v, _)| map.point(v)).collect(); + let a = area2(&ring); + if a != 0 { + out.push((g, lp.iter().map(|x| x.0).collect(), a, lp.iter().map(|x| x.1).collect())); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::faces::geom::cross; + + const C: i32 = CELL_UNITS as i32; + + /// The snapped patches as point segments. + fn snapped(patches: &[Vec>]) -> Vec> { + let s = snap_round(patches); + let at = |i: u32| s.verts[i as usize]; + s.patches.iter().map(|segs| segs.iter().map(|&[a, b]| [at(a), at(b)]).collect()).collect() + } + + /// The snapped patches tile the window: every vertex on the grid, every segment off the window's + /// border has its reverse in another patch, no two segments cross, no patch has a negative area, + /// and the areas sum to the window's. + fn assert_partition(window: [i32; 4], snapped: &[Vec<[P; 2]>]) { + let [x0, y0, x1, y1] = window; + let on_border = |[a, b]: [P; 2]| { + (a[0] == b[0] && (a[0] == x0 || a[0] == x1)) || (a[1] == b[1] && (a[1] == y0 || a[1] == y1)) + }; + let mut all: Vec<([P; 2], usize)> = Vec::new(); + let mut total = 0i128; + for (k, segs) in snapped.iter().enumerate() { + let area: i128 = segs.iter().map(|&[a, b]| cross([0, 0], a, b)).sum(); + assert!(area >= 0, "patch {k} has a negative area"); + total += area; + for &s in segs { + for p in s { + assert_eq!(on_grid(p), p, "vertex {p:?} is off the grid"); + } + assert!(!segs.contains(&[s[1], s[0]]), "patch {k} keeps a segment and its reverse: {s:?}"); + all.push((s, k)); + } + } + assert_eq!(total, 2 * i128::from(x1 - x0) * i128::from(y1 - y0), "the areas sum to the window's"); + for &(s, k) in &all { + if !on_border(s) { + let twin = all.iter().any(|&(t, j)| t == [s[1], s[0]] && j != k); + assert!(twin, "segment {s:?} of patch {k} has no twin"); + } + } + for (i, &([a, b], _)) in all.iter().enumerate() { + for &([c, d], _) in &all[i + 1..] { + let (d1, d2, d3, d4) = (cross(a, b, c), cross(a, b, d), cross(c, d, a), cross(c, d, b)); + assert!( + d1.signum() * d2.signum() >= 0 || d3.signum() * d4.signum() >= 0, + "{a:?}-{b:?} crosses {c:?}-{d:?}" + ); + } + } + } + + /// Thin triangles about the corner (C, C) of a cell, with vertices 1 to 7 units off its lines. + fn near_lines(seed: u64, n: usize) -> Vec> { + let mut s = seed; + let mut next = |m: i32| { + s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + ((s >> 33) % m as u64) as i32 + }; + (0..n) + .map(|_| { + let a = [C - 1 - next(7), C - 40 - next(200)]; + let b = [C - 40 - next(200), C - 1 - next(7)]; + let c = [C - 1 - next(9), C - 1 - next(9)]; + vec![a, b, c] + }) + .collect() + } + + #[test] + fn snap_rounding_keeps_a_partition_beside_the_cell_lines() { + let window = [C - 400, C - 400, C, C]; + for seed in 0..40 { + let rings = near_lines(seed, 6); + // A line that runs within two units of the cell line, ending on it. + let lines = [[[C - 3, C - 400], [C, C - 1]]]; + let (patches, _) = slice(window, &rings, &lines); + assert_partition(window, &snapped(&patches)); + } + } + + #[test] + fn the_tiles_of_a_slice_join_into_one_partition() { + // Thin triangles across the corner where four tiles meet, inside one cell. + let t = TILE as i32; + let window = [t - 400, t - 400, t + 400, t + 400]; + for seed in 0..20 { + let rings: Vec> = near_lines(seed, 6) + .into_iter() + .map(|r| r.into_iter().map(|p| [p[0] - C + t + 150, p[1] - C + t + 150]).collect()) + .collect(); + let (patches, _) = slice(window, &rings, &[[[t - 397, t - 300], [t + 300, t + 3]]]); + assert_partition(window, &snapped(&patches)); + } + } + + #[test] + fn a_vertex_beside_a_cell_line_rounds_away_from_it_without_crossing_a_passing_edge() { + // v lies right of the line from (C-3, 0) to (C, 400); its grid point lies left of where the + // line passes, so the line must run through v's grid point. + let window = [C - 400, 0, C, 400]; + let v = [C - 1, 199]; + let (patches, _) = slice(window, &[vec![v, [C, 150], [C, 250]]], &[[[C - 3, 0], [C, 400]]]); + assert_partition(window, &snapped(&patches)); + } + + #[test] + fn a_part_thinner_than_the_precision_collapses_and_its_segments_cancel() { + // A square with a needle 3 units wide: both sides of the needle round to one grid line. + let window = [0, 0, 400, 400]; + let ring = vec![[100, 100], [200, 100], [200, 198], [300, 198], [300, 201], [200, 201], [200, 300], [100, 300]]; + let (patches, _) = slice(window, &[ring], &[]); + let snapped = snapped(&patches); + assert_partition(window, &snapped); + assert!(snapped.iter().flatten().flatten().all(|p| p[0] <= 200 || p[0] == 400), "the needle is gone"); + } + + #[test] + fn two_cells_round_their_shared_line_alike() { + // One shape over the line x = C, with its vertices on the line (as the build inserts them) + // and others 1 to 3 units off it on both sides. + let ring = vec![ + [C - 90, 103], + [C - 1, 101], + [C, 99], + [C + 2, 97], + [C + 70, 141], + [C + 3, 207], + [C, 209], + [C - 2, 211], + [C - 60, 230], + ]; + let line = |snapped: &[Vec<[P; 2]>]| { + let mut on: Vec<[P; 2]> = (snapped.iter().flatten()) + .filter(|[a, b]| a[0] == C && b[0] == C) + .map(|&[a, b]| if a < b { [a, b] } else { [b, a] }) + .collect(); + on.sort_unstable(); + on.dedup(); + on + }; + let mut sides = Vec::new(); + for window in [[C - 400, 0, C, 400], [C, 0, C + 400, 400]] { + let snapped = snapped(&slice(window, std::slice::from_ref(&ring), &[]).0); + assert_partition(window, &snapped); + sides.push(line(&snapped)); + } + assert_eq!(sides[0], sides[1]); + } + + #[test] + fn two_squares_that_share_an_edge_slice_the_window_into_patches_with_twins() { + let window = [0, 0, 100, 100]; + let a = vec![[10, 10], [50, 10], [50, 50], [10, 50]]; + let b = vec![[50, 10], [90, 10], [90, 50], [50, 50]]; + let (patches, _) = slice(window, &[a, b], &[]); + assert_eq!(patches.len(), 3); + let total: i128 = patches.iter().flatten().map(|r| area2(r)).sum(); + assert_eq!(total, 2 * 100 * 100); + let map = Map::exact(patches); + let inner = map.half.iter().filter(|e| e.twin != NONE).count(); + let border = map.half.iter().filter(|e| e.twin == NONE).count(); + assert_eq!(border, 4, "the window's four sides"); + assert!(inner > 0 && inner % 2 == 0); + let key = vec![0; 3]; + let one = map.groups(&key, false); + let loops = map.loops(&one); + assert_eq!(loops.len(), 1, "one group, the window: {loops:?}"); + assert_eq!(loops[0].2, 2 * 100 * 100); + assert_eq!(loops[0].3.len(), loops[0].1.len()); + } +} diff --git a/host/obc-ground-plan/src/faces/stroke.rs b/host/obc-ground-plan/src/faces/stroke.rs new file mode 100644 index 0000000000..3a3edda421 --- /dev/null +++ b/host/obc-ground-plan/src/faces/stroke.rs @@ -0,0 +1,476 @@ +//! Integer strokes and the booleans of the faces. A stroke is the union of a quad per segment, a pie +//! on the outer side of each inner vertex and a half disc at each round end. Every derived point is an +//! integer point plus a rounded offset, and arcs step at fixed global angles, so two cells that hold +//! the same points build the same rings. + +use i_overlay::core::fill_rule::FillRule; +use i_overlay::core::overlay::{ContourDirection, IntOverlayOptions, Overlay}; +use i_overlay::core::overlay_rule::OverlayRule; +use i_overlay::core::solver::{Precision, Solver, Strategy}; +use i_overlay::i_float::int::point::IntPoint; +use i_overlay::string::overlay::StringOverlay; +use i_overlay::string::rule::StringRule; + +use super::geom::{area2, round, P}; + +/// Rings with the NonZero rule: outer rings counter-clockwise, holes clockwise. +pub type Rings = Vec>; + +/// The arc step: 36 global directions. +pub const STEPS: i32 = 36; +/// A join that turns less than this (radians, one arc step) is mitred. +const MITRE: f64 = 2.0 * std::f64::consts::PI / STEPS as f64; + +/// An arc point closer than this to an arc's end (radians) is left out: no needle segment. +const END_EPS: f64 = 0.01; + +/// One solver for every boolean: one path at every segment count, a snap radius of one unit, no +/// threads. +pub fn solver() -> Solver { + Solver { strategy: Strategy::Frag, precision: Precision::ABSOLUTE, multithreading: None } +} + +pub fn options() -> IntOverlayOptions { + IntOverlayOptions { + preserve_input_collinear: false, + output_direction: ContourDirection::CounterClockwise, + preserve_output_collinear: false, + min_output_area: 0, + ogc: false, + } +} + +/// `p + round(d · dir)`. +pub fn off(p: P, d: f64, dir: [f64; 2]) -> P { + [p[0] + round(d * dir[0]) as i32, p[1] + round(d * dir[1]) as i32] +} + +/// The unit vector of b − a, or None for a = b. +pub fn unit(a: P, b: P) -> Option<[f64; 2]> { + let (x, y) = (f64::from(b[0] - a[0]), f64::from(b[1] - a[1])); + let len = (x * x + y * y).sqrt(); + (len > 0.0).then(|| [x / len, y / len]) +} + +/// The left normal of a direction (x east, y south: a quarter turn from +x toward +y). +pub fn left(u: [f64; 2]) -> [f64; 2] { + [-u[1], u[0]] +} + +fn global_dir(k: i32) -> [f64; 2] { + let a = f64::from(k.rem_euclid(STEPS)) * (2.0 * std::f64::consts::PI / f64::from(STEPS)); + [libm::cos(a), libm::sin(a)] +} + +/// The corners of the narrower layers (offsets `cuts`, ascending) on the ray from p toward `dir`, +/// out to offset d: the vertices that a square end or a fan side of a wider layer shares with them. +fn ray(p: P, d: f64, dir: [f64; 2], cuts: &[f64]) -> impl DoubleEndedIterator + '_ { + cuts.iter().filter(move |&&c| c > 0.0 && c < d).map(move |&c| off(p, c, dir)) +} + +/// The pie about p of radius d from direction `from`, turning `sweep` radians (0 to 2π) toward +y: +/// p, the two ends at `from` and at the end direction, and the global arc directions between. Its +/// two sides pass the corners of the narrower layers at offsets `cuts`. +fn pie(p: P, d: f64, from: [f64; 2], to: [f64; 2], sweep: f64, cuts: &[f64], out: &mut Vec>) { + if sweep <= 0.0 || d <= 0.0 { + return; + } + let step = 2.0 * std::f64::consts::PI / f64::from(STEPS); + let a0 = libm::atan2(from[1], from[0]); + let mut ring = vec![p]; + ring.extend(ray(p, d, from, cuts)); + ring.push(off(p, d, from)); + let mut k = libm::floor(a0 / step) as i32 + 1; + loop { + let a = f64::from(k) * step - a0; + if a >= sweep - END_EPS { + break; + } + if a > END_EPS { + ring.push(off(p, d, global_dir(k))); + } + k += 1; + } + ring.push(off(p, d, to)); + ring.extend(ray(p, d, to, cuts).rev()); + push_positive(ring, out); +} + +/// The fan about p from `from` at radius d0 turning `sweep` radians toward +y to radius d1: the +/// radius changes linearly with the turn, and the ends are the strokes' own corners. Its sides pass +/// the corners of the narrower layers at offsets `cuts` (at the start, at the end). +#[allow(clippy::too_many_arguments)] +pub fn pie_between( + p: P, + d0: f64, + d1: f64, + from: [f64; 2], + to: [f64; 2], + sweep: f64, + cuts: [&[f64]; 2], + out: &mut Vec>, +) { + if sweep <= 0.0 { + return; + } + let step = 2.0 * std::f64::consts::PI / f64::from(STEPS); + let a0 = libm::atan2(from[1], from[0]); + let mut ring = vec![p]; + ring.extend(ray(p, d0, from, cuts[0])); + ring.push(off(p, d0, from)); + let mut k = libm::floor(a0 / step) as i32 + 1; + loop { + let a = f64::from(k) * step - a0; + if a >= sweep - END_EPS { + break; + } + if a > END_EPS { + ring.push(off(p, d0 + (d1 - d0) * a / sweep, global_dir(k))); + } + k += 1; + } + ring.push(off(p, d1, to)); + ring.extend(ray(p, d1, to, cuts[1]).rev()); + push_positive(ring, out); +} + +/// Pushes a ring turned to a positive area; drops one with none. +pub fn push_positive(mut ring: Vec

, out: &mut Vec>) { + ring.dedup(); + if ring.len() > 1 && ring[0] == ring[ring.len() - 1] { + ring.pop(); + } + let a = area2(&ring); + if a == 0 { + return; + } + if a < 0 { + ring.reverse(); + } + out.push(ring); +} + +/// The pieces of the stroke of a line with offset `d[i]` (units) at point i: a quad per segment, a +/// pie on the outer side of each inner vertex, and a half disc at each end where `round` says so. +/// `closed` strokes a ring: every vertex is inner. `dirs[i]`, if given, is the direction of segment +/// i: a sample inserted on a segment keeps the segment's own direction on both sides, so its +/// sections meet the segment's. The end at the first and at the last point passes the corners at +/// offsets `cuts` (ascending) below d, so layers and ways that end on one line share its vertices. +/// +/// An inner vertex of an open line whose inner mitre point would turn a segment's edge back (a +/// segment shorter than the offset times the turn) is left out: the edges about it then meet at one +/// mitre point. Else the two segments' own corners stand apart there, and where the offset changes +/// along them (a taper) the edge steps. The line moves by at most that segment's length times the +/// turn. +pub fn pieces_along( + p: &[P], + d: &[f64], + dirs: &[Option<[f64; 2]>], + cuts: [&[f64]; 2], + round_ends: [bool; 2], + closed: bool, + out: &mut Vec>, +) { + let mut keep: Vec = (0..p.len()).collect(); + let mut k = 2; + while !closed && k + 2 < keep.len() { + let (a, v, b) = (keep[k - 1], keep[k], keep[k + 1]); + if let (Some(u1), Some(u2)) = (unit(p[a], p[v]), unit(p[v], p[b])) { + let c = u1[0] * u2[1] - u1[1] * u2[0]; + let dot = u1[0] * u2[0] + u1[1] * u2[1]; + let turn = libm::atan2(c, dot); + if turn != 0.0 && turn.abs() < MITRE && dot > 0.0 { + // Turning toward the left normal: the inner side is the left one. + let s = if turn > 0.0 { 1.0 } else { -1.0 }; + let (n1, n2) = (left(u1).map(|x| s * x), left(u2).map(|x| s * x)); + let m = [(n1[0] + n2[0]) / (1.0 + dot), (n1[1] + n2[1]) / (1.0 + dot)]; + let q = off(p[v], d[v], m); + let ahead = + |a: P, b: P, u: [f64; 2]| f64::from(b[0] - a[0]) * u[0] + f64::from(b[1] - a[1]) * u[1] > 0.0; + if !(ahead(off(p[a], d[a], n1), q, u1) && ahead(q, off(p[b], d[b], n2), u2)) { + keep.remove(k); + k = (k - 1).max(2); + continue; + } + } + } + k += 1; + } + if keep.len() < p.len() { + let p: Vec

= keep.iter().map(|&i| p[i]).collect(); + let d: Vec = keep.iter().map(|&i| d[i]).collect(); + let dirs: Vec> = + keep.windows(2).map(|w| if w[1] == w[0] + 1 { dirs.get(w[0]).copied().flatten() } else { None }).collect(); + return stroke(&p, &d, &dirs, cuts, round_ends, closed, out); + } + stroke(p, d, dirs, cuts, round_ends, closed, out) +} + +fn stroke( + p: &[P], + d: &[f64], + dirs: &[Option<[f64; 2]>], + cuts: [&[f64]; 2], + round_ends: [bool; 2], + closed: bool, + out: &mut Vec>, +) { + let n = p.len(); + if n == 0 { + return; + } + let segs = if closed { n } else { n - 1 }; + // The direction of each segment; a zero segment takes none. + let dirs: Vec> = (0..segs) + .map(|i| { + if p[i] == p[(i + 1) % n] { + None + } else { + dirs.get(i).copied().flatten().or_else(|| unit(p[i], p[(i + 1) % n])) + } + }) + .collect(); + // Per segment, its corners at start and end: left, right. + let mut corners: Vec<[[P; 2]; 2]> = (0..segs) + .map(|i| { + let j = (i + 1) % n; + let nl = dirs[i].map_or([0.0, 0.0], left); + let nr = [-nl[0], -nl[1]]; + [[off(p[i], d[i], nl), off(p[i], d[i], nr)], [off(p[j], d[j], nl), off(p[j], d[j], nr)]] + }) + .collect(); + // The joins: between each segment and the next one with a direction. A join that turns less than + // one arc step takes one mitre point per side for both segments: no step between two corners. On + // the inner side a mitre point that would turn either segment's edge back (a segment shorter than + // the offset times the turn) is left out: the segments' own corners there overlap. + let valid: Vec = (0..segs).filter(|&i| dirs[i].is_some()).collect(); + let pairs = valid.len().saturating_sub(usize::from(!closed)); + let mut pies = Vec::new(); + for k in 0..pairs { + let (i, j) = (valid[k], valid[(k + 1) % valid.len()]); + let (u1, u2) = (dirs[i].unwrap(), dirs[j].unwrap()); + let v = (i + 1) % n; + let c = u1[0] * u2[1] - u1[1] * u2[0]; + let dot = u1[0] * u2[0] + u1[1] * u2[1]; + let turn = libm::atan2(c, dot); + let (n1, n2) = (left(u1), left(u2)); + if turn.abs() < MITRE && dot > 0.0 { + let m = [(n1[0] + n2[0]) / (1.0 + dot), (n1[1] + n2[1]) / (1.0 + dot)]; + let q = [off(p[v], d[v], m), off(p[v], d[v], [-m[0], -m[1]])]; + // Turning toward the left normal: the inner side is the left one. + let inner = if turn > 0.0 { 0 } else { 1 }; + let ahead = |a: P, b: P, u: [f64; 2]| f64::from(b[0] - a[0]) * u[0] + f64::from(b[1] - a[1]) * u[1] > 0.0; + for side in 0..2 { + if side != inner || (ahead(corners[i][0][side], q[side], u1) && ahead(q[side], corners[j][1][side], u2)) + { + corners[i][1][side] = q[side]; + corners[j][0][side] = q[side]; + } + } + continue; + } + pies.push((v, turn, dot, c, n1, n2)); + } + let (first, last) = (valid.first().copied(), valid.last().copied()); + for i in 0..segs { + let Some(u) = dirs[i] else { continue }; + let [[sl, sr], [el, er]] = corners[i]; + let nl = left(u); + let nr = [-nl[0], -nl[1]]; + let j = (i + 1) % n; + let mut ring = vec![el]; + if !closed && Some(i) == last { + ring.extend(ray(p[j], d[j], nl, cuts[1]).rev()); + ring.extend(ray(p[j], d[j], nr, cuts[1])); + } + ring.extend([er, sr]); + if !closed && Some(i) == first { + ring.extend(ray(p[i], d[i], nr, cuts[0]).rev()); + ring.extend(ray(p[i], d[i], nl, cuts[0])); + } + ring.push(sl); + push_positive(ring, out); + } + for (v, turn, dot, c, n1, n2) in pies { + if turn > 0.0 || (turn == 0.0 && dot < 0.0) { + // Turning toward the left normal: the outer side is the right one. + pie( + p[v], + d[v], + [-n1[0], -n1[1]], + [-n2[0], -n2[1]], + turn.abs().max(if dot < 0.0 && c == 0.0 { std::f64::consts::PI } else { 0.0 }), + &[], + out, + ); + } else if turn < 0.0 { + pie(p[v], d[v], n2, n1, -turn, &[], out); + } + } + if !closed { + if let (true, Some(i)) = (round_ends[0], first) { + let u = dirs[i].unwrap(); + let back = [-u[0], -u[1]]; + pie(p[0], d[0], left(back).map(|x| -x), left(back), std::f64::consts::PI, cuts[0], out); + } + if let (true, Some(i)) = (round_ends[1], last) { + let u = dirs[i].unwrap(); + pie(p[n - 1], d[n - 1], left(u).map(|x| -x), left(u), std::f64::consts::PI, cuts[1], out); + } + } +} + +/// A boolean of two ring sets, NonZero, run in a frame about `anchor`, so that two cells that hold +/// the same rings about one global anchor get the same result. +pub fn boolean(subj: &[Vec

], clip: &[Vec

], rule: OverlayRule, anchor: P) -> Rings { + shapes(subj, clip, rule, anchor).into_iter().flatten().collect() +} + +/// A boolean whose result keeps its connected parts apart: each an outer ring and its holes. +pub fn shapes(subj: &[Vec

], clip: &[Vec

], rule: OverlayRule, anchor: P) -> Vec { + if subj.is_empty() && matches!(rule, OverlayRule::Subject | OverlayRule::Difference | OverlayRule::Intersect) { + return Vec::new(); + } + let shift = |rings: &[Vec

]| -> Vec> { + (rings.iter()) + .filter(|r| r.len() >= 3) + .map(|r| r.iter().map(|p| IntPoint::new(p[0] - anchor[0], p[1] - anchor[1])).collect()) + .collect() + }; + let (s, c) = (shift(subj), shift(clip)); + let out = Overlay::from_subj_and_clip_custom(&s, &c, options(), solver()).overlay(rule, FillRule::NonZero); + out.into_iter() + .map(|shape| { + shape.into_iter().map(|c| c.into_iter().map(|q| [q.x + anchor[0], q.y + anchor[1]]).collect()).collect() + }) + .collect() +} + +/// The pieces of rings (NonZero) that lines cut them into, in a frame about `anchor`: each an outer +/// ring and its holes. Every vertex of the rings stays. +pub fn cut(rings: &[Vec

], lines: &[[P; 2]], anchor: P) -> Vec { + let pt = |p: P| IntPoint::new(p[0] - anchor[0], p[1] - anchor[1]); + let keep = IntOverlayOptions { preserve_input_collinear: true, preserve_output_collinear: true, ..options() }; + let size = rings.iter().map(Vec::len).sum::() + lines.len(); + let mut overlay = StringOverlay::with_options(size, keep); + for r in rings.iter().filter(|r| r.len() >= 3) { + overlay.add_shape_contour(&r.iter().map(|&p| pt(p)).collect::>()); + } + for &[a, b] in lines { + overlay.add_string_line([pt(a), pt(b)]); + } + let Some(graph) = overlay.build_graph_view_with_solver(FillRule::NonZero, solver()) else { + return vec![rings.to_vec()]; + }; + (graph.extract_shapes_custom(StringRule::Slice, keep).into_iter()) + .map(|shape| { + shape.into_iter().map(|c| c.into_iter().map(|q| [q.x + anchor[0], q.y + anchor[1]]).collect()).collect() + }) + .collect() +} + +pub fn union(rings: &[Vec

], anchor: P) -> Rings { + boolean(rings, &[], OverlayRule::Subject, anchor) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_union_of_a_turn_fill_and_its_arm_pieces_completes() { + let rings: Vec> = vec![ + vec![ + [189391, 183582], + [189355, 183601], + [189505, 183496], + [189561, 183440], + [189967, 183440], + [189752, 183459], + [189541, 183516], + ], + vec![ + [189505, 181816], + [189358, 181713], + [189401, 181735], + [189546, 181798], + [189757, 181855], + [189974, 181874], + [191016, 181875], + [189563, 181874], + ], + vec![[188736, 183751], [187643, 183687], [187771, 181497], [188864, 181561]], + vec![ + [188800, 182656], + [188864, 181561], + [188990, 181576], + [189175, 181626], + [189348, 181706], + [189505, 181816], + [189640, 181951], + [189750, 182108], + [189830, 182281], + [189880, 182466], + [189896, 182656], + [189880, 182846], + [189830, 183031], + [189750, 183204], + [189640, 183361], + [189505, 183496], + [189348, 183606], + [189175, 183686], + [188990, 183736], + [188800, 183752], + [188736, 183751], + ], + vec![[188801, 181873], [190288, 181874], [190286, 183440], [188799, 183439]], + vec![ + [188800, 182656], + [188799, 183439], + [188664, 183427], + [188532, 183392], + [188408, 183334], + [188297, 183256], + [188200, 183159], + [188122, 183048], + [188064, 182924], + [188029, 182792], + [188017, 182656], + [188029, 182520], + [188064, 182388], + [188122, 182264], + [188200, 182153], + [188297, 182056], + [188408, 181978], + [188532, 181920], + [188664, 181885], + [188801, 181873], + ], + ]; + let u = super::union(&rings, [188800, 182656]); + assert_eq!(u.len(), 1, "one outer ring and no hole: {u:?}"); + } + + #[test] + fn a_tapered_bend_with_a_short_segment_strokes_without_a_step() { + // A taper on the inner side of a bend, with two samples 39 units apart: the short segment's + // inner mitres would turn its edge back. Its vertex is left out, so the inner edge turns by + // the bend only (under 20 degrees at every vertex), not by a step of two right angles. + let p = + [[-2338, 925], [-2267, 303], [-2123, -306], [-1904, -892], [-1888, -928], [-1590, -1479], [-1227, -1988]]; + let d = [2124.0, 2163.0, 2199.8, 2106.0, 2100.0, 2006.1, 1912.3]; + let mut out = Vec::new(); + super::pieces_along(&p, &d, &[], [&[], &[]], [false, false], false, &mut out); + let u = super::union(&out, [0, 0]); + assert_eq!(u.len(), 1); + let r = &u[0]; + let n = r.len(); + for i in 0..n { + let (a, b, c) = (r[(i + n - 1) % n], r[i], r[(i + 1) % n]); + let (u1, u2) = + ([f64::from(b[0] - a[0]), f64::from(b[1] - a[1])], [f64::from(c[0] - b[0]), f64::from(c[1] - b[1])]); + let turn = libm::atan2(u1[0] * u2[1] - u1[1] * u2[0], u1[0] * u2[0] + u1[1] * u2[1]).to_degrees(); + // The four corners of the square ends turn by a right angle; no other vertex may. + let end = [p[0], p[6]].iter().any(|e| libm::hypot(f64::from(b[0] - e[0]), f64::from(b[1] - e[1])) < 2200.0); + assert!(end || turn.abs() < 20.0, "vertex {b:?} turns {turn:.1} degrees"); + } + } +} diff --git a/host/obc-ground-plan/src/faces/tests.rs b/host/obc-ground-plan/src/faces/tests.rs new file mode 100644 index 0000000000..8198376b3a --- /dev/null +++ b/host/obc-ground-plan/src/faces/tests.rs @@ -0,0 +1,773 @@ +use super::check::partition; +use super::records::{self, check as records_check}; +use super::*; +use crate::frame::{from_lon_lat, metres_per_unit, GlobalPoint}; +use crate::graph::{build, WayGraph}; +use crate::terrain::{StoredPage, Terrain, PAGE}; +use crate::tile::{self, Alignment, Feature, Geometry, Tags}; + +pub(crate) fn cell() -> CellKey { + CellKey::of(from_lon_lat(8.40, 46.82)) +} + +pub(crate) fn mpu() -> f64 { + metres_per_unit(cell().origin().y + CELL_UNITS / 2) +} + +/// A point at metres east and south of the cell's centre. +pub(crate) fn at([x, y]: [f64; 2]) -> GlobalPoint { + let o = cell().origin(); + let half = CELL_UNITS / 2; + GlobalPoint { x: o.x + half + libm::round(x / mpu()) as i64, y: o.y + half + libm::round(y / mpu()) as i64 } +} + +#[derive(Clone)] +pub(crate) struct Line { + kind: &'static str, + tags: Vec<(&'static str, &'static str)>, + points: Vec<[f64; 2]>, + pub z: Vec, + /// Per vertex, the sides of the segment from it on with a sidewalk: 1 left, 2 right. + walk: Vec, +} + +pub(crate) fn line(kind: &'static str, tags: &[(&'static str, &'static str)], points: &[[f64; 2]]) -> Line { + let n = points.len(); + Line { kind, tags: tags.to_vec(), points: points.to_vec(), z: vec![500.0; n], walk: vec![0; n] } +} + +pub(crate) fn road(points: &[[f64; 2]]) -> Line { + line("road", &[("highway", "residential")], points) +} + +/// A road of a wall class (`leg_wall`). +pub(crate) fn main_road(points: &[[f64; 2]]) -> Line { + line("road", &[("highway", "tertiary")], points) +} + +/// A way of a class without walls. +pub(crate) fn track(points: &[[f64; 2]]) -> Line { + line("road", &[("highway", "track")], points) +} + +fn feature(l: &Line, tile: (u32, u32), index: u32) -> Feature { + let points: Vec = l.points.iter().map(|&p| at(p)).collect(); + let n = points.len(); + let chord = |i: usize, j: usize| { + libm::atan2((points[j].y - points[i].y) as f64, (points[j].x - points[i].x) as f64) + .rem_euclid(core::f64::consts::TAU) + }; + let tangent: Vec = (0..n) + .map(|i| match i { + 0 => chord(0, 1), + i if i == n - 1 => chord(n - 2, n - 1), + i => chord(i - 1, i + 1), + }) + .collect(); + let plan = Some(Alignment { + along_m: 0.0, + backward: false, + tangent, + grade: vec![0.0; n], + bank: vec![0.0; n], + widen: vec![0.0; n], + side: vec![0; n], + walk: l.walk.clone(), + }); + let tags: Tags = l.tags.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let heights = Some(l.z.iter().map(|&z| Some(z)).collect()); + let part = tile::Part { outer: false, tile, own: vec![true; n - 1], points, heights, plan }; + Feature { index, kind: l.kind.into(), tags, geometry: Geometry::Line, parts: vec![part] } +} + +pub(crate) fn input_of(key: CellKey, lines: &[Line]) -> CellInput { + let tile = cell().feature_tiles()[0]; + CellInput { + key, + features: lines.iter().zip(0..).map(|(l, index)| feature(l, tile, index)).collect(), + terrain: Terrain::new(key, Vec::new()), + } +} + +/// The terrain of a cell on every page that it reads: z of metres east and south of the centre of +/// `cell()`. +pub(crate) fn plane(key: CellKey, z: &dyn Fn(f64, f64) -> f64) -> Terrain { + let centre = at([0.0, 0.0]); + let pages = Terrain::wanted(key) + .into_iter() + .map(|k| { + let s = crate::frame::FRAME_BITS - 8 - u32::from(k.level); + let texel = |i: usize, base: u32| ((i64::from(base) << 8) + i as i64) << s | 1 << (s - 1); + let h: Vec = (0..PAGE * PAGE) + .map(|t| { + let (x, y) = (texel(t % PAGE, k.x), texel(t / PAGE, k.y)); + z((x - centre.x) as f64 * mpu(), (y - centre.y) as f64 * mpu()) + }) + .collect(); + let (min, max) = h.iter().fold((f64::MAX, f64::MIN), |(a, b), &v| (a.min(v), b.max(v))); + let scale = ((max - min) / 65534.0).max(1e-4); + let codes = h.iter().map(|v| ((v - min) / scale).round() as u16).collect(); + StoredPage { level: k.level, x: k.x, y: k.y, offset: min as f32, scale: scale as f32, codes } + }) + .collect(); + Terrain::new(key, pages) +} + +/// The plan of a cell from lines, with check 1 at 0 faults. +fn plan_of(key: CellKey, lines: &[Line]) -> (FacePlan, WayGraph) { + let input = input_of(key, lines); + let rules = Rules::embedded(); + let graph = build(key, &input, &rules.sections); + let plan = super::build(&graph, &input, rules, key, 0, true); + let faults = partition(&plan, window(key, 0.0)); + assert!(faults.is_empty(), "{} faults: {:?}", faults.len(), &faults[..faults.len().min(10)]); + (plan, graph) +} + +fn plan(lines: &[Line]) -> FacePlan { + plan_of(cell(), lines).0 +} + +fn count(plan: &FacePlan, surface: Surface) -> usize { + plan.faces.iter().filter(|f| f.surface == surface).count() +} + +#[test] +fn an_empty_cell_is_one_terrain_face() { + let p = plan(&[]); + assert!(p.faces.iter().all(|f| f.surface == Surface::Terrain)); + assert_eq!(p.faces.len(), 1); +} + +#[test] +fn a_straight_road_gives_a_carriageway_shoulders_and_slopes() { + let p = plan(&[road(&[[-300.0, 10.0], [300.0, 12.0]])]); + assert!(count(&p, Surface::Carriageway) >= 1); + assert!(count(&p, Surface::Shoulder) >= 1); + assert!(count(&p, Surface::Slope) >= 1); +} + +/// The surface at a point in metres from the cell's centre. +fn surface_at(p: &FacePlan, m: [f64; 2]) -> Surface { + let g = at(m); + let o = cell().origin(); + let q = [2 * (g.x - o.x), 2 * (g.y - o.y)]; + let face = p.faces.iter().find(|f| { + let rings: Vec> = + f.rings.iter().map(|r| r.iter().map(|&v| p.vertices[v as usize]).collect()).collect(); + geom::winding(&rings, q) != 0 + }); + face.map_or(Surface::Terrain, |f| f.surface) +} + +#[test] +fn the_land_between_hairpin_legs_stays_land_past_the_turns_corner_zone() { + // Residential: half-width 2.5 m, inner radius 3 m. Legs 3 m apart (under 2r) and 8 m apart. + let h = 2.5; + for gap in [3.0, 8.0] { + let r = gap / 2.0 + h; + let mut points = vec![[-r, 80.0], [-r, 0.0]]; + for k in 1..12 { + let a = core::f64::consts::PI * f64::from(k) / 12.0; + points.push([-r * libm::cos(a), -r * libm::sin(a)]); + } + points.extend([[r, 0.0], [r, 80.0]]); + let p = plan(&[road(&points)]); + for y in [20.0, 30.0, 45.0, 60.0] { + assert_ne!(surface_at(&p, [0.0, y]), Surface::Carriageway, "legs {gap} m apart, {y} m from the turn"); + } + assert_eq!(surface_at(&p, [0.0, -r]), Surface::Carriageway, "legs {gap} m apart: the turn"); + } +} + +#[test] +fn a_junction_corner_takes_the_lesser_class_radius_and_the_sidewalk_one_on_a_sidewalk_side() { + // A residential road runs south from a tertiary one, with a sidewalk on its left: the east. + let host = line("road", &[("highway", "tertiary")], &[[-80.0, 0.0], [0.0, 0.0], [80.0, 0.0]]); + let mut guest = road(&[[0.0, 0.0], [0.0, 80.0]]); + guest.walk[0] = 1; + let p = plan(&[host, guest]); + let sections = &Rules::embedded().sections; + let class = |name: &str| sections.way("road", &[("highway".into(), name.into())].into(), false); + let (tertiary, residential) = (class("tertiary"), class("residential")); + let o = cell().origin(); + let centre = at([0.0, 0.0]); + let radius = |east: bool| { + let c = p.corners.iter().find(|c| (o.x + i64::from(c.centre[0]) > centre.x) == east && c.radius_m > 0.0); + c.map(|c| c.radius_m).unwrap() + }; + let east = residential.corner_radius_walk_m.min(tertiary.corner_radius_walk_m); + let west = residential.corner_radius_m.min(tertiary.corner_radius_m); + assert!(east < west); + assert!((radius(true) - east).abs() < 0.01, "{} m east", radius(true)); + assert!((radius(false) - west).abs() < 0.01, "{} m west", radius(false)); +} + +#[test] +fn a_round_has_its_feet_on_its_circle_and_on_the_edges_it_joins() { + // A T of two ways of one class: a primary one (9 m rounds) and a residential one (4 m). + let sections = &Rules::embedded().sections; + for name in ["primary", "residential"] { + let host = line("road", &[("highway", name)], &[[-80.0, 0.0], [0.0, 0.0], [80.0, 0.0]]); + let guest = line("road", &[("highway", name)], &[[0.0, 0.0], [0.0, 80.0]]); + let p = plan(&[host, guest]); + let class = sections.way("road", &[("highway".into(), name.into())].into(), false); + let (o, centre) = (cell().origin(), at([0.0, 0.0])); + let (cx, cy) = ((centre.x - o.x) as i32, (centre.y - o.y) as i32); + let h = class.half_m / mpu(); + let rounds: Vec<&CornerArc> = p.corners.iter().filter(|c| c.radius_m > 0.0).collect(); + assert_eq!(rounds.len(), 2, "{name}"); + for c in rounds { + assert!((c.radius_m - class.corner_radius_m).abs() < 0.01, "{name}: a {} m round", c.radius_m); + let r = c.radius_m / mpu(); + let off = |q: &[i32; 2]| libm::hypot(f64::from(q[0] - c.centre[0]), f64::from(q[1] - c.centre[1])) - r; + for q in c.arc.iter().chain([&c.t_a, &c.t_b]) { + assert!(off(q).abs() < 2.0, "{name}: a point {} units off its circle", off(q)); + } + // One foot on the host's edge, the other on the guest's edge on the round's side. + let side = (c.centre[0] - cx).signum(); + let on_host = |q: &[i32; 2]| (f64::from((q[1] - cy).abs()) - h).abs() < 2.0; + let on_guest = + |q: &[i32; 2]| (q[0] - cx).signum() == side && (f64::from((q[0] - cx).abs()) - h).abs() < 2.0; + let [a, b] = [c.t_a, c.t_b]; + assert!((on_host(&a) && on_guest(&b)) || (on_host(&b) && on_guest(&a)), "{name}: feet {a:?} {b:?}"); + } + } +} + +#[test] +fn two_cells_round_a_point_alike_where_its_arm_ends_at_a_point_past_the_window() { + // A primary road runs east over the cell's east border. A guest leaves it 40 m past the border + // and another one 10 m on, 50 m past it: the first junction's east arm ends at the second, so its + // corner there takes a round under the class's 9 m. + let x = CELL_UNITS as f64 / 2.0 * mpu(); + let primary = |points: &[[f64; 2]]| line("road", &[("highway", "primary")], points); + let lines = [ + primary(&[[x - 30.0, 0.0], [x + 40.0, 0.0], [x + 50.0, 0.0], [x + 100.0, 0.0]]), + primary(&[[x + 40.0, 0.0], [x + 40.0, 60.0]]), + primary(&[[x + 50.0, 0.0], [x + 50.0, -60.0]]), + ]; + let p = at([x + 40.0, 0.0]); + let rounds = |key: CellKey| { + let (plan, graph) = plan_of(key, &lines); + let o = key.origin(); + let d = |q: [i32; 2]| (o.x + i64::from(q[0]) - p.x).pow(2) + (o.y + i64::from(q[1]) - p.y).pow(2); + let j = (0..graph.junctions.len()).min_by_key(|&j| d(graph.junctions[j].pos)).unwrap() as u32; + let mut out: Vec<([i64; 2], i64)> = (plan.corners.iter()) + .filter(|c| c.owner == Owner::Junction(j)) + .map(|c| { + ([o.x + i64::from(c.centre[0]), o.y + i64::from(c.centre[1])], libm::round(100.0 * c.radius_m) as i64) + }) + .collect(); + out.sort_unstable(); + out + }; + let (west, east) = (rounds(cell()), rounds(CellKey { x: cell().x + 1, y: cell().y })); + assert_eq!(west, east); + assert!(west.iter().any(|&(_, r)| r > 0 && r < 900), "{west:?}"); +} + +#[test] +fn two_cells_round_a_point_alike_where_its_round_meets_a_way_far_past_the_window() { + // A primary road runs east over the cell's east border, and a guest leaves it 45 m past the + // border to the north. A residential road starts 14 m north of the host, 67 m past the border, + // past the carriageways that the west cell builds: the junction's 9 m round there meets its + // carriageway, so it is smaller in both cells. + let x = CELL_UNITS as f64 / 2.0 * mpu(); + let primary = |points: &[[f64; 2]]| line("road", &[("highway", "primary")], points); + let lines = [ + primary(&[[x - 30.0, 0.0], [x + 45.0, 0.0], [x + 100.0, 0.0]]), + primary(&[[x + 45.0, 0.0], [x + 45.0, -60.0]]), + road(&[[x + 67.0, -14.0], [x + 67.0, -80.0]]), + ]; + let p = at([x + 45.0, 0.0]); + let rounds = |key: CellKey| { + let (plan, graph) = plan_of(key, &lines); + let o = key.origin(); + let d = |q: [i32; 2]| (o.x + i64::from(q[0]) - p.x).pow(2) + (o.y + i64::from(q[1]) - p.y).pow(2); + let j = (0..graph.junctions.len()).min_by_key(|&j| d(graph.junctions[j].pos)).unwrap() as u32; + let mut out: Vec<([i64; 2], i64)> = (plan.corners.iter()) + .filter(|c| c.owner == Owner::Junction(j)) + .map(|c| { + ([o.x + i64::from(c.centre[0]), o.y + i64::from(c.centre[1])], libm::round(100.0 * c.radius_m) as i64) + }) + .collect(); + out.sort_unstable(); + out + }; + let (west, east) = (rounds(cell()), rounds(CellKey { x: cell().x + 1, y: cell().y })); + assert_eq!(west, east); + assert!(west.iter().any(|&(_, r)| r > 0 && r < 900), "{west:?}"); +} + +#[test] +fn a_face_that_the_precision_cuts_in_two_keeps_its_hole_in_the_part_that_holds_it() { + // Two squares of one carriageway joined by a neck 3 units wide, which collapses on the grid, and + // a hole of terrain in the east square. + let win = window(cell(), 0.0); + let dumbbell = vec![ + [1000, 1000], + [2000, 1000], + [2000, 1498], + [3000, 1498], + [3000, 1000], + [4000, 1000], + [4000, 2000], + [3000, 2000], + [3000, 1501], + [2000, 1501], + [2000, 2000], + [1000, 2000], + ]; + let hole = vec![[3400, 1400], [3600, 1400], [3600, 1600], [3400, 1600]]; + let (patches, _) = slice::slice(win, &[dumbbell.clone(), hole.clone()], &[]); + let way = Label { owner: Owner::Way(0), surface: Surface::Carriageway, ..TERRAIN }; + let labels: Vec

= + [[0.0, 30.0], [0.0, 0.0], [-5.0, 0.0], [-5.8, 0.0], q, [q[0], -30.0], [30.0, -30.0], [30.0, 30.0]] + .iter() + .map(|&[u, w]| at(u, w)) + .collect(); + // The paved side on the left: outer rings turn counter-clockwise. + if (0..ring.len()).map(|i| geom::cross([0, 0], ring[i], ring[(i + 1) % ring.len()])).sum::() < 0 { + ring.reverse(); + } + let other: Vec

= + [[200.0, -30.0], [260.0, -30.0], [260.0, 30.0], [200.0, 30.0]].iter().map(|&[u, w]| at(u, w)).collect(); + let fills = |paved: &Rings| { + let fills = outline::rounds(paved, &lines, &[], &|_| 0.0, &|m, _| m * k, 10.0, 5.0); + let mut out: Vec<(P, i64, Vec

, [i64; 2])> = fills + .iter() + .map(|f| (f.circle.centre, libm::round(f.circle.radius) as i64, f.ring.clone(), f.inside)) + .collect(); + out.sort(); + out + }; + let first = fills(&vec![ring.clone(), other.clone()]); + assert_eq!(first.len(), 1, "{first:?}"); + for start in 0..ring.len() { + let mut turned = ring.clone(); + turned.rotate_left(start); + assert_eq!(fills(&vec![other.clone(), turned]), first, "the ring from vertex {start}"); + } +} + +#[test] +fn the_paved_outline_holds_no_water() { + // A stream that runs on past the window crosses a road under it: no round fills a corner between the road's + // edge and the water, on either side of either. + let mut stream = line("stream", &[("waterway", "stream")], &[[0.0, -300.0], [0.0, 300.0]]); + stream.z = vec![499.0; 2]; + let p = plan(&[road(&[[-300.0, 0.0], [300.0, 0.0]]), stream]); + assert!(p.corners.is_empty(), "rounds at {:?}", p.corners.iter().map(|c| c.centre).collect::>()); +} + +/// A cell's records with its graph and feature names, for the records' checks. +fn records_of(key: CellKey, lines: &[Line]) -> (Vec, WayGraph, Vec<[u32; 3]>) { + let input = input_of(key, lines); + let rules = Rules::embedded(); + let graph = build(key, &input, &rules.sections); + let words = records::build(&graph, &input, rules, key, 0, true).near.words; + (words, graph, check::feature_names(&input)) +} + +#[test] +fn the_records_give_each_point_its_face_label_and_the_far_level_keeps_every_other_label() { + // A junction of a primary road and a residential one, a rail that a road crosses, and a road + // beside the rail over its bed's edge. + let primary = line("road", &[("highway", "primary")], &[[-20.0, -200.0], [0.0, -38.0], [30.0, 200.0]]); + let rail = line("railway", &[("railway", "rail")], &[[-150.0, 60.0], [150.0, 60.0]]); + let lines = + [road(&[[-200.0, -40.0], [0.0, -38.0], [180.0, -60.0]]), primary, rail, road(&[[60.0, 63.5], [150.0, 63.5]])]; + let (key, input, rules) = (cell(), input_of(cell(), &lines), Rules::embedded()); + let graph = build(key, &input, &rules.sections); + let built = records::build(&graph, &input, rules, key, 0, true); + let (plan, near) = (built.faces, built.near.words); + let a = + records_check::agreement(&near, &plan, &records_check::Overlay::new(&graph, &input, rules, key, true), 6, 8.0); + assert!(a.points > 10_000, "{} points", a.points); + assert!(a.area.is_empty(), "{} of {} points: {:?}", a.area.len(), a.points, &a.area[..a.area.len().min(4)]); + let far = built.far_records.words; + let [points, differ] = records_check::far_agreement(&near, &far, 6); + assert!(points > 10_000, "{points} points"); + assert_eq!(differ, 0); +} + +#[test] +fn the_far_block_check_finds_a_way_in_reach_that_the_block_leaves_out() { + let lines = [road(&[[-200.0, -40.0], [0.0, -38.0], [180.0, -60.0]]), road(&[[-20.0, -200.0], [30.0, 200.0]])]; + let (key, input, rules) = (cell(), input_of(cell(), &lines), Rules::embedded()); + let graph = build(key, &input, &rules.sections); + let built = records::build(&graph, &input, rules, key, 0, true); + let near = built.near.words; + let (faults, counts) = records_check::far_matches_near(&near, &built.far_block.unwrap(), key); + assert!(faults.is_empty() && counts["lines"] >= 2, "{faults:?} {counts:?}"); + // A block without the first way, and an empty block. + let mut all = record_lines(&graph, &input, rules, key); + all.remove(0); + for lines in [&all[..], &[]] { + let block = records::far::encode(key, &graph, &input, rules, lines).unwrap(); + let faults = records_check::far_matches_near(&near, &block, key).0; + assert!(faults.iter().any(|f| f.ends_with("segments in reach, no far line")), "{faults:?}"); + } +} + +#[test] +fn two_cells_give_one_label_on_their_line_where_an_edge_and_vertices_lie_on_it() { + // A road runs north with its carriageway's east edge on the east cell line (a vertex within 2 + // units moves onto it); another one crosses the line, so its rings have vertices on it, and meets + // a third one 4 m past the line, so both cells read that junction's region. + let x = CELL_UNITS as f64 / 2.0 * mpu(); + let lines = [ + road(&[[x - 2.5, -250.0], [x - 2.5, -50.0]]), + road(&[[x - 100.0, 150.0], [x + 4.0, 151.0], [x + 100.0, 152.0]]), + road(&[[x + 4.0, 151.0], [x + 4.0, 300.0]]), + ]; + let (a, b) = (records_of(cell(), &lines), records_of(CellKey { x: cell().x + 1, y: cell().y }, &lines)); + let c = CELL_UNITS as i32; + let (vertices, edges) = records_check::on_line(&a.0, true, c); + assert!(edges > 0 && vertices.len() > 4, "{edges} edges and {} vertices on the line", vertices.len()); + let (points, blend, differ) = records_check::border((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), true, 37); + assert!(points > 7_000 && blend > 100, "{points} points, {blend} with a blend edge near"); + assert!(differ.is_empty(), "{} differ: {:?}", differ.len(), &differ[..differ.len().min(4)]); +} + +#[test] +fn a_junction_label_names_its_record_with_the_arms_ranges_flags_and_directions() { + // A residential road runs east, and a dirt path leaves it to the north and stops there. + let lines = [ + road(&[[-80.0, 0.0], [0.0, 0.0], [80.0, 0.0]]), + line("path", &[("highway", "path"), ("surface", "dirt")], &[[0.0, 0.0], [0.0, -30.0], [0.0, -80.0]]), + ]; + let (words, graph, _) = records_of(cell(), &lines); + let ids: Vec = (0..words[2]).filter(|&id| records::junction(&words, id).is_some()).collect(); + assert!(!ids.is_empty()); + let jr = records::junction(&words, ids[0]).unwrap(); + for &id in &ids { + assert_eq!(records::junction(&words, id), Some(jr), "every label of the junction names one record"); + assert_eq!(records::owner(&words, id), jr[2] >> 16); + } + let j = &graph.junctions[(jr[2] >> 16) as usize]; + assert_eq!([jr[0] as i32, jr[1] as i32], j.pos); + assert_eq!(jr[2] & 0xff, 3); + let sample = |line: u32, i: u32| { + let first = words[words[6] as usize + records::LINE * line as usize + 2]; + let s = &words[words[7] as usize + records::SAMPLE * (first + i) as usize..]; + [f64::from(s[0] as i32 - j.pos[0]), f64::from(s[1] as i32 - j.pos[1])] + }; + // Per arm: its flags and its direction at the node, east, west or north (frame y runs south). + let mut arms: Vec<(u32, [i32; 2])> = Vec::new(); + for a in jr[records::JR..].chunks(records::JR_ARM) { + let (line, node, last) = (a[0] & 0xffff, a[1] & 0xffff, a[1] >> 16); + let d = [f64::from((a[2] & 0xffff) as u16 as i16), f64::from((a[2] >> 16) as u16 as i16)].map(|v| v / 32767.0); + assert_eq!(sample(line, node), [0.0, 0.0], "the node sample lies on the node"); + // The arm runs from the node in its direction to the first sample past its seam, some metres on. + let p = sample(line, last); + let ahead = (p[0] * d[0] + p[1] * d[1]) * mpu(); + assert!(ahead > 3.0 && ahead < 40.0, "the last sample lies {ahead} m ahead"); + arms.push((a[0] >> 16, [libm::round(d[0]) as i32, libm::round(d[1]) as i32])); + } + arms.sort_unstable(); + let (host, stop) = (records::ARM_HOST >> 16, records::ARM_STOP >> 16); + assert_eq!(arms, vec![(host, [-1, 0]), (host, [1, 0]), (stop, [0, -1])]); +} + +/// Whether q (metres east and south of the junction's node) keeps the route in the stop mouth of junction record `jr`, +/// as `terrain/mouth.wgsl` decides it (a port of it); none outside a sector with a stop arm. +fn keeps_route(words: &[u32], jr: &[u32], q: [f64; 2]) -> Option { + let m = mpu(); + let node = [f64::from(jr[0] as i32), f64::from(jr[1] as i32)]; + let v = [q[0] / m, q[1] / m]; + let p = [node[0] + v[0], node[1] + v[1]]; + let sample = |line: u32, i: u32| { + let first = words[words[6] as usize + records::LINE * line as usize + 2]; + let s = &words[words[7] as usize + records::SAMPLE * (first + i) as usize..]; + ([f64::from(s[0] as i32), f64::from(s[1] as i32)], f64::from(f32::from_bits(s[2]))) + }; + let arms: Vec<&[u32]> = jr[records::JR..].chunks(records::JR_ARM).collect(); + let dir = |a: &[u32]| [a[2] & 0xffff, a[2] >> 16].map(|x| f64::from(x as u16 as i16) / 32767.0); + let stop = |a: &[u32]| a[0] & records::ARM_STOP != 0; + let wrap = |x: f64| x.rem_euclid(std::f64::consts::TAU); + let angle = |u: [f64; 2]| libm::atan2(u[1], u[0]); + let aq = angle(v); + let route: Vec<&&[u32]> = arms.iter().filter(|a| !stop(a)).collect(); + let a = route.iter().min_by(|x, y| wrap(aq - angle(dir(x))).total_cmp(&wrap(aq - angle(dir(y)))))?; + let b = route.iter().min_by(|x, y| wrap(angle(dir(x)) - aq).total_cmp(&wrap(angle(dir(y)) - aq)))?; + let span = wrap(aq - angle(dir(a))) + wrap(angle(dir(b)) - aq); + if !arms.iter().any(|s| stop(s) && wrap(angle(dir(s)) - angle(dir(a))) < span) { + return None; + } + let (ua, ub) = (dir(a), dir(b)); + let (ha, hb) = (sample(a[0] & 0xffff, a[1] & 0xffff).1, sample(b[0] & 0xffff, b[1] & 0xffff).1); + let (na, nb) = ([-ua[1], ua[0]], [ub[1], -ub[0]]); + // Where one facing edge corner lies past the other's edge line, the other arm widens to it at the node. + let two = if a != b { 1.0 } else { 0.0 }; + let dot = |x: [f64; 2], y: [f64; 2]| x[0] * y[0] + x[1] * y[1]; + let (wa, wb) = (two * (dot(nb, na) * hb - ha).max(0.0), two * (dot(na, nb) * ha - hb).max(0.0)); + // The strokes, flat at the node, and the mitre. + let mut d = f64::INFINITY; + for r in &route { + let (n, last) = (r[1] & 0xffff, r[1] >> 16); + let (side, widen) = if r == a { + (two, wa) + } else if r == b { + (-two, wb) + } else { + (0.0, 0.0) + }; + let step: i64 = if last > n { 1 } else { -1 }; + let at = |k: i64| sample(r[0] & 0xffff, (i64::from(n) + k * step) as u32); + let segments = (i64::from(last) - i64::from(n)).abs(); + let total: f64 = + (0..segments).map(|k| libm::hypot(at(k + 1).0[0] - at(k).0[0], at(k + 1).0[1] - at(k).0[1])).sum(); + let mut along = 0.0; + for k in 0..segments { + let ((s0, h0), (s1, h1)) = (at(k), at(k + 1)); + let u = [s1[0] - s0[0], s1[1] - s0[1]]; + let len = libm::hypot(u[0], u[1]); + let t = ((p[0] - s0[0]) * u[0] + (p[1] - s0[1]) * u[1]) / (len * len); + let c = t.clamp(0.0, 1.0); + let cross = u[0] * (p[1] - s0[1]) - u[1] * (p[0] - s0[0]); + let wider = if side * cross > 0.0 { widen * (1.0 - (along + c * len) / total) } else { 0.0 }; + d = d.min(if k == 0 && t < 0.0 { + (cross.abs() / len - h0 - wider).max(-t * len) + } else { + libm::hypot(p[0] - s0[0] - c * u[0], p[1] - s0[1] - c * u[1]) - (h0 + c * (h1 - h0)) - wider + }); + along += len; + } + } + if a != b { + let edges = (dot(v, na) - ha - wa).max(dot(v, nb) - hb - wb); + let behind = dot(v, ua).max(dot(v, ub)); + d = d.min(edges.max(libm::hypot(v[0], v[1]) - 4.0 * ha.max(hb)).max(behind)); + } + Some(d * m <= 0.02) +} + +#[test] +fn a_stop_mouth_keeps_the_routes_own_edge_and_its_mitre_at_a_bend() { + let dirt = |points: &[[f64; 2]]| line("path", &[("highway", "path"), ("surface", "dirt")], points); + // A road turns north at the node and a dirt path leaves the outer side of the bend to the east. + let lines = [road(&[[-80.0, 0.0], [0.0, 0.0], [0.0, -80.0]]), dirt(&[[0.0, 0.0], [40.0, 10.0], [80.0, 10.0]])]; + let (words, _, _) = records_of(cell(), &lines); + let id = (0..words[2]).find(|&id| records::junction(&words, id).is_some()).unwrap(); + let jr = records::junction(&words, id).unwrap(); + // The route arms that bound the outer sector, as the record has them: a turns counter-clockwise to b through it. + let arm = |k: usize| &jr[records::JR + records::JR_ARM * k..][..records::JR_ARM]; + let dir = |a: &[u32]| [a[2] & 0xffff, a[2] >> 16].map(|x| f64::from(x as u16 as i16) / 32767.0); + let route: Vec<&[u32]> = (0..(jr[2] & 0xff) as usize).map(arm).filter(|a| a[0] & records::ARM_STOP == 0).collect(); + let south = |a: &[u32]| dir(a)[1] > 0.0; + let (a, b) = if south(route[0]) { (route[1], route[0]) } else { (route[0], route[1]) }; + let half = |a: &[u32]| { + let line = &words[words[6] as usize + records::LINE * (a[0] & 0xffff) as usize..]; + f64::from(f32::from_bits(words[words[7] as usize + records::SAMPLE * (line[2] + (a[1] & 0xffff)) as usize + 2])) + * mpu() + }; + let (ua, ub, ha, hb) = (dir(a), dir(b), half(a), half(b)); + let (na, nb) = ([-ua[1], ua[0]], [ub[1], -ub[0]]); + // Their facing edges meet at the mitre's corner m behind the node. + let det = na[0] * nb[1] - na[1] * nb[0]; + let m = [(ha * nb[1] - hb * na[1]) / det, (na[0] * hb - nb[0] * ha) / det]; + let at = |p: [f64; 2], n: [f64; 2], s: f64| [p[0] + s * n[0], p[1] + s * n[1]]; + assert_eq!(keeps_route(&words, jr, at(m, m, -0.1)), Some(true), "inside the mitre's corner"); + assert_eq!(keeps_route(&words, jr, at(at(m, ua, 0.3), na, 0.3)), Some(false), "past a's edge, straight on"); + assert_eq!(keeps_route(&words, jr, at(at(m, ub, 0.3), nb, 0.3)), Some(false), "past b's edge, straight on"); + // Beside each arm the edge is the arm's own: no tab beside the mouth. + for (u, n, h) in [(ua, na, ha), (ub, nb, hb)] { + assert_eq!(keeps_route(&words, jr, at(at([0.0; 2], u, 1.0), n, h - 0.3)), Some(true)); + assert_eq!(keeps_route(&words, jr, at(at([0.0; 2], u, 1.0), n, h + 0.3)), Some(false)); + } +} + +#[test] +fn a_stop_mouth_between_two_widths_widens_the_narrow_arm_without_a_step() { + let dirt = |points: &[[f64; 2]]| line("path", &[("highway", "path"), ("surface", "dirt")], points); + // A wide road runs on as a narrow one through the node, and a dirt path leaves it to the north. + let lines = [ + line("road", &[("highway", "primary")], &[[-80.0, 0.0], [0.0, 0.0]]), + road(&[[0.0, 0.0], [80.0, 0.0]]), + dirt(&[[0.0, 0.0], [0.0, -40.0], [0.0, -80.0]]), + ]; + let (words, _, _) = records_of(cell(), &lines); + let id = (0..words[2]).find(|&id| records::junction(&words, id).is_some()).unwrap(); + let jr = records::junction(&words, id).unwrap(); + let half = |west: bool| { + let a = jr[records::JR..].chunks(records::JR_ARM).find(|a| { + let x = f64::from((a[2] & 0xffff) as u16 as i16); + a[0] & records::ARM_STOP == 0 && (x < 0.0) == west + }); + let a = a.unwrap(); + let line = &words[words[6] as usize + records::LINE * (a[0] & 0xffff) as usize..]; + f64::from(f32::from_bits(words[words[7] as usize + records::SAMPLE * (line[2] + (a[1] & 0xffff)) as usize + 2])) + * mpu() + }; + let (wide, narrow) = (half(true), half(false)); + assert!(wide > narrow + 0.5, "{wide} m and {narrow} m"); + // Just east of the node the narrow arm is as wide as the wide one on the path's side: no step. + assert_eq!(keeps_route(&words, jr, [0.2, -(wide - 0.1)]), Some(true)); + assert_eq!(keeps_route(&words, jr, [0.2, -(wide + 0.1)]), Some(false)); + // The other side has no stop arm: the junction keeps its own look there. + assert_eq!(keeps_route(&words, jr, [0.2, narrow + 0.1]), None); +} + +#[test] +fn two_cells_give_one_side_to_their_line_where_an_edge_passes_a_tile_corner_on_it() { + // A ring's edge leaves the cell line x = C at y = t + 27 or t + 15 and crosses the tile line y = t + // 0.53 or 0.30 units off the cell line, beside the tile corner (C, t); or it crosses the cell line + // at that corner. Each also mirrored and reversed. Per window, the segments on the cell line after + // the snap rounding, each with whether its patch lies in the ring, which goes through `prepare` + // twice (as `split_legs` does) and then gets its tile-line points, as `candidates` gives them. + let (c, t) = (CELL_UNITS as i32, 7 * slice::TILE as i32); + let sides = |window: [i32; 4], ring: &[P]| { + let rings: Rings = + prepare(&prepare(&vec![ring.to_vec()])).iter().map(|r| geom::with_grid_lines(r, slice::TILE)).collect(); + let (patches, _) = slice(window, &rings, &[]); + let snapped = snap_round(&patches); + let at = |i: u32| snapped.verts[i as usize]; + let mut on: Vec<([P; 2], bool)> = (patches.iter().zip(&snapped.patches)) + .flat_map(|(patch, segs)| { + let inside = inner_point(patch).is_some_and(|q| geom::winding(&rings, q) != 0); + segs.iter().map(move |&[a, b]| ([at(a), at(b)], inside)) + }) + .filter(|([a, b], _)| a[0] == c && b[0] == c) + .map(|([a, b], inside)| (if a < b { [a, b] } else { [b, a] }, inside)) + .collect(); + on.sort_unstable(); + on + }; + let wedge = |on: [P; 2], low: P| { + vec![[c - 40, t + 300], on[0], on[1], low, [c + 300, t - 379], [c + 300, t + 300], [c, t + 300]] + }; + let mut rings = Vec::new(); + for ring in [ + wedge([[c - 20, t + 200], [c, t + 27]], [c + 8, t - 379]), + wedge([[c - 20, t + 200], [c, t + 15]], [c + 8, t - 379]), + wedge([[c - 8, t + 8], [c, t]], [c + 8, t - 8]), + ] { + rings.push(ring.iter().map(|p| [2 * c - p[0], p[1]]).collect::>()); + rings.push(ring.iter().rev().copied().collect()); + rings.push(ring); + } + for ring in rings { + let west = sides([c - 400, t - 400, c, t + 400], &ring); + let east = sides([c, t - 400, c + 400, t + 400], &ring); + assert!(west.len() >= 3, "{west:?}"); + assert_eq!(west, east, "ring {ring:?}"); + } +} diff --git a/host/obc-ground-plan/src/faces/types.rs b/host/obc-ground-plan/src/faces/types.rs new file mode 100644 index 0000000000..35c8c29ebf --- /dev/null +++ b/host/obc-ground-plan/src/faces/types.rs @@ -0,0 +1,193 @@ +//! The face plan of one cell and level: the bytes that GP4 to GP7 read. + +/// The index of a way of the cell's graph (`WayGraph::ways`) and of a junction +/// (`WayGraph::junctions`): local to the cell. +pub type WayId = u32; +pub type JunctionId = u32; + +/// What a face belongs to. Band layers (shoulder, verge, slope) and terrain belong to `Terrain`: one +/// face per layer, whatever ways made it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Owner { + Terrain, + Way(WayId), + Junction(JunctionId), + /// A platform: the index of its feature in the cell's input. + Platform(u32), +} + +/// The codes are bytes of the plan: later items append and never reuse one. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[repr(u8)] +pub enum Surface { + Terrain = 0, + Slope = 1, + Carriageway = 2, + Shoulder = 3, + Verge = 4, + CornerFill = 5, + Crossing = 6, + RailBed = 7, + Platform = 8, + /// Line water: its face lies at the water level. + Water = 9, + /// The band from a waterline to the bank top. + Bank = 10, + /// Ground over line water at a culvert under a way (`culverts`): the water does not show there, and the + /// slopes shape it. + Zone = 11, + /// The band about a deck's paved stroke, the seat of its parapet or railing (`faces::deck`). + DeckEdge = 12, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[repr(u8)] +pub enum HeightRule { + Terrain = 0, + Slope = 1, + Owner = 2, + Blend = 3, + KerbOffset = 4, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[repr(u8)] +pub enum EdgeKind { + Continuous = 0, + Kerb = 1, + Wall = 2, + Headwall = 3, + Portal = 4, + DeckEdge = 5, + CellBorder = 6, +} + +/// Edge flags. `SEAM`: a guest's blend part meets its host's seam face (the give-way line). +/// `BLEND_JOIN`: two blend faces, one blend region. `UNRELATED`: two owners that no way, junction, +/// bend or joint relates. +pub const SEAM: u8 = 1; +pub const BLEND_JOIN: u8 = 2; +pub const UNRELATED: u8 = 4; +/// The face index past the window's edge. +pub const OUTSIDE: u32 = u32::MAX; + +#[derive(Clone, Debug, PartialEq)] +pub struct Face { + pub id: u32, + pub owner: Owner, + pub surface: Surface, + pub level: i8, + pub rule: HeightRule, + /// The way whose class and tags give the look. + pub material: Option, + /// The rail way under a crossing face. + pub crossing: Option, + /// The index of the face's rank in `plan.json`'s `ranks`: 0 wins. + pub rank: u8, + /// The face lies in the cell square. + pub inside: bool, + /// The slope reach of the face's class; 0 for slope and terrain. + pub reach_m: f32, + /// The legs of `material` and `crossing`: a way that passes beside itself splits into legs + /// (`faces::legs`); 0 for a way with one. + pub legs: [u8; 2], + /// Vertex indices; ring 0 has a positive shoelace sum (x east, y south), each hole a negative one. + pub rings: Vec>, +} + +/// One edge of the planar map: `left` is the face on the side where the shoelace sum of (a, b, point) +/// is positive. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Edge { + pub a: u32, + pub b: u32, + pub left: u32, + pub right: u32, + pub kind: EdgeKind, + pub flags: u8, +} + +/// What the stages built. Counts over the cell's inputs. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FaceStats { + pub ways: u32, + pub junctions: u32, + pub joints: u32, + pub turns: u32, + pub candidates: u32, + pub patches: u32, + pub slice_segments: u32, + pub faces: u32, + pub vertices: u32, + pub edges: u32, + /// Platforms near the window without vertex heights: they get no face. + pub platforms_skipped: u32, +} + +impl FaceStats { + /// Every counter, by name. + pub fn counters(&self) -> [(&'static str, u32); 11] { + [ + ("ways", self.ways), + ("junctions", self.junctions), + ("joints", self.joints), + ("turns", self.turns), + ("candidates", self.candidates), + ("patches", self.patches), + ("slice_segments", self.slice_segments), + ("faces", self.faces), + ("vertices", self.vertices), + ("edges", self.edges), + ("platforms_skipped", self.platforms_skipped), + ] + } +} + +/// One round, in cell units: its centre, its radius, its feet `t_a` and `t_b` (the tangent points on +/// the two edges it joins: the ends of its arc), and its arc's points at the global directions +/// strictly between the feet, from `t_a` to `t_b`. A sharp corner (radius 0) has the corner as its +/// centre, its feet and its arc. +#[derive(Clone, Debug, PartialEq)] +pub struct CornerArc { + pub owner: Owner, + pub centre: [i32; 2], + pub radius_m: f64, + pub t_a: [i32; 2], + pub t_b: [i32; 2], + pub arc: Vec<[i32; 2]>, +} + +impl CornerArc { + /// `mpu`: metres per unit at the centre. + pub(crate) fn new(owner: Owner, c: &super::points::Circle, mpu: f64) -> Self { + let [t_a, t_b] = c.feet; + CornerArc { owner, centre: c.centre, radius_m: c.radius * mpu, t_a, t_b, arc: c.arc.clone() } + } +} + +/// A culvert's mouth (`culverts`): where the water's middle line meets a zone's outline. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CulvertMouth { + /// Frame units from the cell's origin. + pub at: [f64; 2], + /// The unit direction of the water into the zone, and of the zone's outline there (x east, y south). + pub into: [f64; 2], + pub edge: [f64; 2], + /// The water's half-width, metres: at most half of `culvert_width_m` at an untagged crossing, a road's or a + /// railway's ford included (the classifier's rule), at most `HALF_MAX_M` at a mapped culvert and a tunnel's + /// start, which carry any water. + pub half_m: f64, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct FacePlan { + pub cell: crate::frame::CellKey, + pub level: i8, + pub vertices: Vec<[i32; 2]>, + pub faces: Vec, + pub edges: Vec, + pub corners: Vec, + /// The mouths of the culverts' zones about the cell. + pub mouths: Vec, + pub stats: FaceStats, +} diff --git a/host/obc-ground-plan/src/frame.rs b/host/obc-ground-plan/src/frame.rs new file mode 100644 index 0000000000..8a9355eb42 --- /dev/null +++ b/host/obc-ground-plan/src/frame.rs @@ -0,0 +1,187 @@ +//! The integer frame: Web Mercator in 2^-34 of the square, the zoom-16 cells and their input margin. +//! +//! Every position is an integer. Tile units become frame units by one exact shift; metres come from +//! `metres_per_unit` at the point and enter a position only through one rounding. + +use core::f64::consts::PI; + +/// A frame unit is 2^-34 of the Web Mercator square: 1/16 of a world unit, about 1.6 mm at 47° N. +pub const FRAME_BITS: u32 = 34; +const SQUARE: f64 = (1u64 << FRAME_BITS) as f64; +/// The bake's metres (the format's along, grades and widening are in them). +pub const EQUATOR_M: f64 = 40075016.686; +pub const CELL_ZOOM: u32 = 16; +pub const CELL_UNITS: i64 = 1 << (FRAME_BITS - CELL_ZOOM); +/// The input margin about a cell. +pub const MARGIN_M: f64 = 192.0; +/// The longest chain of rules: 1 m of the margin is left for the Mercator scale over a cell and the +/// rounding to frame units. +pub const CHAIN_MAX_M: f64 = MARGIN_M - 1.0; +/// A curve leaves its chord by up to this much, so the curve within `MARGIN_M` lies on segments that +/// meet the cell grown by `margin()`. +const CHORD_M: f64 = 2.0; +/// The zoom of the feature tiles that a cell reads. +pub const FEATURE_ZOOM: u32 = 13; +const FEATURE_UNITS: i64 = 1 << (FRAME_BITS - FEATURE_ZOOM); + +/// A point of the frame: x east, y south, from the north-west corner of the square. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct GlobalPoint { + pub x: i64, + pub y: i64, +} + +/// Frame units from a cell's origin. A cell and its margin span about 4 × 10^5 units. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct CellPoint { + pub x: i32, + pub y: i32, +} + +/// The zoom-16 tile that a cell is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct CellKey { + pub x: u32, + pub y: u32, +} + +impl CellKey { + /// The cell that holds a point: a point on a cell line belongs to the cell east or south of it. + pub fn of(p: GlobalPoint) -> CellKey { + let shift = FRAME_BITS - CELL_ZOOM; + CellKey { x: (p.x >> shift) as u32, y: (p.y >> shift) as u32 } + } + + pub fn origin(self) -> GlobalPoint { + GlobalPoint { x: i64::from(self.x) * CELL_UNITS, y: i64::from(self.y) * CELL_UNITS } + } + + pub fn contains(self, p: GlobalPoint) -> bool { + let o = self.origin(); + (o.x..o.x + CELL_UNITS).contains(&p.x) && (o.y..o.y + CELL_UNITS).contains(&p.y) + } + + /// The margin in frame units: `MARGIN_M` and the chord's 2 m at the cell edge nearer the pole, so + /// at least that on the ground at every point of the cell. + pub fn margin(self) -> i64 { + let o = self.origin(); + let pole = if o.y < 1 << (FRAME_BITS - 1) { o.y } else { o.y + CELL_UNITS }; + ((MARGIN_M + CHORD_M) / metres_per_unit(pole)).floor() as i64 + } + + /// The closed square [x0, y0, x1, y1] of the cell grown by its margin. + pub fn grown(self) -> [i64; 4] { + let (o, m) = (self.origin(), self.margin()); + [o.x - m, o.y - m, o.x + CELL_UNITS + m, o.y + CELL_UNITS + m] + } + + /// The zoom-13 tiles (column, row) that the cell grown by its margin meets, by row, then column: + /// one to four. + pub fn feature_tiles(self) -> Vec<(u32, u32)> { + let [x0, y0, x1, y1] = self.grown(); + let last = (1i64 << FEATURE_ZOOM) - 1; + let span = |lo: i64, hi: i64| (lo / FEATURE_UNITS).max(0)..=(hi / FEATURE_UNITS).min(last); + span(y0.max(0), y1).flat_map(|row| span(x0.max(0), x1).map(move |column| (column as u32, row as u32))).collect() + } + + /// The point in units from the origin, or None past `i32`. + pub fn local(self, p: GlobalPoint) -> Option { + let o = self.origin(); + Some(CellPoint { x: i32::try_from(p.x - o.x).ok()?, y: i32::try_from(p.y - o.y).ok()? }) + } + + pub fn global(self, p: CellPoint) -> GlobalPoint { + let o = self.origin(); + GlobalPoint { x: o.x + i64::from(p.x), y: o.y + i64::from(p.y) } + } +} + +/// Metres per frame unit at frame row y: the Mercator scale. `1 / cosh t` is the bake's +/// `cos(atan(sinh t))`. +pub fn metres_per_unit(y: i64) -> f64 { + metres_per_unit_at(y as f64) +} + +/// `metres_per_unit` at a row between two frame units. +pub fn metres_per_unit_at(y: f64) -> f64 { + EQUATOR_M / SQUARE / libm::cosh(PI * (1.0 - 2.0 * y / SQUARE)) +} + +/// The point at tile units (quarters of them for `fine`) of tile (column, row) at zoom z. Exact. +pub fn tile_point(z: u32, column: u32, row: u32, fine: bool, x: i64, y: i64) -> GlobalPoint { + assert!(z <= 18, "a tile of zoom {z} is finer than the frame"); + let k = if fine { 16 } else { 14 }; + let s = FRAME_BITS - z - k; + GlobalPoint { x: ((i64::from(column) << k) + x) << s, y: ((i64::from(row) << k) + y) << s } +} + +/// The point at a longitude and a latitude in degrees, rounded half to even. For tools and tests. +pub fn from_lon_lat(lon: f64, lat: f64) -> GlobalPoint { + let x = (lon + 180.0) / 360.0; + let y = (1.0 - libm::asinh(libm::tan(lat.to_radians())) / PI) / 2.0; + GlobalPoint { x: (x * SQUARE).round_ties_even() as i64, y: (y * SQUARE).round_ties_even() as i64 } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cell_at(lat: f64) -> CellKey { + CellKey::of(from_lon_lat(8.4, lat)) + } + + #[test] + fn tile_units_and_quarters_are_exact_and_reversible() { + let (column, row) = (4286, 2888); + // Both ends of the buffer, about 40 m (200 units) past the square, and a far cut end. + for (x, y) in [(-210, 16594), (0, 0), (16383, 8192), (-90_000, 400_000)] { + let p = tile_point(13, column, row, false, x, y); + let q = tile_point(13, column, row, true, 4 * x, 4 * y); + assert_eq!(p, q); + let unit = 1 << 7; + assert_eq!(((p.x >> 7) - (i64::from(column) << 14), (p.y >> 7) - (i64::from(row) << 14)), (x, y)); + assert_eq!((p.x % unit, p.y % unit), (0, 0)); + } + let quarter = tile_point(13, column, row, true, 1, 3); + assert_eq!(quarter.x - tile_point(13, column, row, false, 0, 0).x, 32); + } + + #[test] + fn a_point_on_a_cell_line_is_in_one_cell() { + let key = cell_at(46.8); + let line = GlobalPoint { x: key.origin().x + CELL_UNITS, y: key.origin().y }; + assert!(!key.contains(line)); + assert_eq!(CellKey::of(line), CellKey { x: key.x + 1, y: key.y }); + assert!(CellKey::of(line).contains(line)); + assert!(key.contains(key.origin())); + let local = key.local(GlobalPoint { x: line.x - 1, y: line.y + 5 }).unwrap(); + assert_eq!(key.global(local), GlobalPoint { x: line.x - 1, y: line.y + 5 }); + assert!(key.local(GlobalPoint { x: 0, y: 0 }).is_none()); + } + + #[test] + fn the_scale_is_the_bakes_and_the_margin_holds_194_m() { + for lat in [0.0, 47.0, 70.0] { + let y = from_lon_lat(8.4, lat).y; + let t = PI * (1.0 - 2.0 * y as f64 / SQUARE); + let bake = EQUATOR_M * libm::cos(libm::atan(libm::sinh(t))) / SQUARE; + assert!((metres_per_unit(y) / bake - 1.0).abs() < 1e-12, "{lat}"); + let key = cell_at(lat); + let pole = if key.origin().y < 1 << 33 { key.origin().y } else { key.origin().y + CELL_UNITS }; + let metres = key.margin() as f64 * metres_per_unit(pole); + assert!(metres <= 194.0 && metres > 194.0 - metres_per_unit(pole), "{lat}: {metres}"); + } + } + + #[test] + fn a_cell_reads_one_two_or_four_feature_tiles() { + let tile = |column: i64, row: i64| GlobalPoint { x: column * FEATURE_UNITS, y: row * FEATURE_UNITS }; + let middle = tile(4286, 2888); + let inside = CellKey::of(GlobalPoint { x: middle.x + FEATURE_UNITS / 2, y: middle.y + FEATURE_UNITS / 2 }); + assert_eq!(inside.feature_tiles(), [(4286, 2888)]); + let west_edge = CellKey::of(GlobalPoint { x: middle.x, y: middle.y + FEATURE_UNITS / 2 }); + assert_eq!(west_edge.feature_tiles(), [(4285, 2888), (4286, 2888)]); + let corner = CellKey::of(middle); + assert_eq!(corner.feature_tiles(), [(4285, 2887), (4286, 2887), (4285, 2888), (4286, 2888)]); + } +} diff --git a/host/obc-ground-plan/src/graph/crossings.rs b/host/obc-ground-plan/src/graph/crossings.rs new file mode 100644 index 0000000000..6bea035930 --- /dev/null +++ b/host/obc-ground-plan/src/graph/crossings.rs @@ -0,0 +1,538 @@ +//! Stage 4: crossings without a shared vertex. Whether two pieces cross, and how, is decided on +//! their mapped vertex chords by exact orientation tests, as the bake decides it; the stations lie +//! where their curves cross. The type table gives each a type; synthetic decks split the upper piece. + +use std::cmp::Ordering; +use std::collections::BTreeMap; + +use super::curve::{insert, point}; +use super::parts::{fords, Rule}; +use super::points::{advance, key, metres, nodes, Anchor, Node, NodeKind, Piece, Plan}; +use super::{ + Crossing, CrossingKind, Family, GraphStats, Level, Network, Part, Sample, Source, Station, BUCKET_M, + DECK_HALF_MAX_M, DECK_SIDE_M, PLACE_M, WATER_BANK_M, +}; +use crate::frame::{metres_per_unit, CellKey, GlobalPoint}; +use crate::sections::GRAZE_DEG; + +/// A chord between two neighbouring samples of a piece, in global positions. +#[derive(Clone, Debug)] +pub(crate) struct Seg { + pub piece: usize, + pub a: [i64; 2], + pub b: [i64; 2], + /// The stations at a and at b, both on a's span. + pub sa: Station, + pub ub: f64, +} + +impl Seg { + pub fn at(&self, t: f64) -> Station { + Station { u: self.sa.u + t * (self.ub - self.sa.u), ..self.sa } + } +} + +/// The sample segments of the pieces in buckets of `BUCKET_M`: (bucket, segment), sorted. +pub(crate) struct Grid { + pub size: i64, + pub segs: Vec, + pub cells: Vec<([i64; 2], u32)>, +} + +/// The samples of a piece. +pub(crate) fn piece_samples<'a>(samples: &'a [Sample], piece: &Piece) -> impl Iterator { + let (from, to) = (key(&piece.from), key(&piece.to)); + samples.iter().filter(move |s| (s.span, s.u) >= from && (s.span, s.u) <= to) +} + +impl Grid { + pub fn new(cell: CellKey, samples: &[Vec], pieces: &[Piece]) -> Grid { + let o = cell.origin(); + let size = ((BUCKET_M / metres_per_unit(o.y)) as i64).max(1); + let mut grid = Grid { size, segs: Vec::new(), cells: Vec::new() }; + let push = |grid: &mut Grid, seg: Seg| { + let id = grid.segs.len() as u32; + let cells = &mut grid.cells; + cover(size, seg.a, seg.b, 0, |cell| cells.push((cell, id))); + grid.segs.push(seg); + }; + for (index, piece) in pieces.iter().enumerate() { + let list: Vec<&Sample> = piece_samples(&samples[piece.part], piece).collect(); + for pair in list.windows(2) { + let global = |s: &Sample| [o.x + i64::from(s.pos[0]), o.y + i64::from(s.pos[1])]; + let ub = if pair[1].span == pair[0].span { pair[1].u } else { 1.0 }; + let sa = Station { part: piece.part as u32, span: pair[0].span, u: pair[0].u }; + push(&mut grid, Seg { piece: index, a: global(pair[0]), b: global(pair[1]), sa, ub }); + } + } + grid.cells.sort_unstable(); + grid + } + + /// The mapped vertex chords of the pieces. + pub fn chords(cell: CellKey, parts: &[Part], pieces: &[Piece]) -> Grid { + let size = ((BUCKET_M / metres_per_unit(cell.origin().y)) as i64).max(1); + let mut grid = Grid { size, segs: Vec::new(), cells: Vec::new() }; + for (index, piece) in pieces.iter().enumerate() { + let part = &parts[piece.part]; + let last = if piece.to.u > 0.0 { piece.to.span + 1 } else { piece.to.span }; + for k in piece.from.span..last { + let (a, b) = (part.vertices[k as usize].pos, part.vertices[k as usize + 1].pos); + let sa = Station { part: piece.part as u32, span: k, u: 0.0 }; + let id = grid.segs.len() as u32; + let cells = &mut grid.cells; + cover(size, a, b, 0, |cell| cells.push((cell, id))); + grid.segs.push(Seg { piece: index, a, b, sa, ub: 1.0 }); + } + } + grid.cells.sort_unstable(); + grid + } + + /// The segments of each bucket. + pub fn buckets(&self) -> impl Iterator { + self.cells.chunk_by(|a, b| a.0 == b.0) + } + + /// The segments whose buckets the box of a and b grown by `reach` units meets, once each, in id order. + pub fn near(&self, a: [i64; 2], b: [i64; 2], reach: i64) -> Vec { + let mut out: Vec = Vec::new(); + cover(self.size, a, b, reach, |cell| { + let from = self.cells.partition_point(|c| c.0 < cell); + out.extend(self.cells[from..].iter().take_while(|c| c.0 == cell).map(|c| c.1)); + }); + out.sort_unstable(); + out.dedup(); + out + } +} + +/// Each bucket that the box of a and b grown by `reach` units meets. +fn cover(size: i64, a: [i64; 2], b: [i64; 2], reach: i64, mut f: impl FnMut([i64; 2])) { + let lo = |i: usize| (a[i].min(b[i]) - reach).div_euclid(size); + let hi = |i: usize| (a[i].max(b[i]) + reach).div_euclid(size); + for y in lo(1)..=hi(1) { + for x in lo(0)..=hi(0) { + f([x, y]); + } + } +} + +fn orient(a: [i64; 2], b: [i64; 2], c: [i64; 2]) -> i8 { + let d = |p: i64, q: i64| i128::from(p) - i128::from(q); + let v = d(b[0], a[0]) * d(c[1], a[1]) - d(b[1], a[1]) * d(c[0], a[0]); + v.signum() as i8 +} + +/// Where the half-open segments [a, b) and [c, d) cross, exactly: the parameters on each. Collinear +/// segments do not cross. +pub(crate) fn cross(a: [i64; 2], b: [i64; 2], c: [i64; 2], d: [i64; 2]) -> Option<(f64, f64)> { + let (o1, o2, o3, o4) = (orient(a, b, c), orient(a, b, d), orient(c, d, a), orient(c, d, b)); + if o1 == 0 && o2 == 0 { + return None; + } + let first = o1 * o2 < 0 || (o1 == 0 && o2 != 0); + let second = o3 * o4 < 0 || (o3 == 0 && o4 != 0); + if !(first && second) { + return None; + } + let r = [(b[0] - a[0]) as f64, (b[1] - a[1]) as f64]; + let s = [(d[0] - c[0]) as f64, (d[1] - c[1]) as f64]; + let q = [(c[0] - a[0]) as f64, (c[1] - a[1]) as f64]; + let rs = r[0] * s[1] - r[1] * s[0]; + Some(((q[0] * s[1] - q[1] * s[0]) / rs, (q[0] * r[1] - q[1] * r[0]) / rs)) +} + +/// Whether the end vertex of one way lies on the vertex chord a–b of another, the chord's ends +/// included, exactly: the way ends on the other, and there is no crossing. The points are global +/// integers as the tiles quantize them; `end` is the first or last vertex of a GP2 part (a decoded +/// part, also split where heights are unknown), and a–b the vertex chord of the other part where the +/// two meet. The bake asks the same. +pub fn end_on_chord(end: GlobalPoint, a: GlobalPoint, b: GlobalPoint) -> bool { + let (e, a, b) = ([end.x, end.y], [a.x, a.y], [b.x, b.y]); + orient(a, b, e) == 0 + && (a[0].min(b[0])..=a[0].max(b[0])).contains(&e[0]) + && (a[1].min(b[1])..=a[1].max(b[1])).contains(&e[1]) +} + +/// The stations of a chord crossing at x on the curves of pieces p and q: where their sample +/// polylines cross nearest x within `reach` units; else each curve's foot of x. And the position. +fn place(curves: &Grid, chords: (&Seg, &Seg), parts: &[Part], x: [f64; 2]) -> (Station, Station, [i64; 2]) { + let (p, q) = (chords.0.piece, chords.1.piece); + let xi = [libm::round(x[0]) as i64, libm::round(x[1]) as i64]; + // Only what lies within `PLACE_M` of x, in metres at x: the buckets differ between cells. + let mpu = metres_per_unit(xi[1]); + let reach = (PLACE_M / mpu).ceil() as i64; + let within = |d2: f64| d2.sqrt() * mpu <= PLACE_M; + let near: Vec<&Seg> = (curves.near(xi, xi, reach).iter()) + .map(|&id| &curves.segs[id as usize]) + .filter(|s| within(projection(s, x).0)) + .collect(); + let (ps, qs): (Vec<&Seg>, Vec<&Seg>) = ( + near.iter().copied().filter(|s| s.piece == p).collect(), + near.iter().copied().filter(|s| s.piece == q).collect(), + ); + let mut best: Option<((f64, [i64; 2]), Station, Station)> = None; + for a in &ps { + for b in &qs { + let Some((ta, tb)) = cross(a.a, a.b, b.a, b.b) else { continue }; + let r = [(a.b[0] - a.a[0]) as f64, (a.b[1] - a.a[1]) as f64]; + let pos = [a.a[0] + libm::round(ta * r[0]) as i64, a.a[1] + libm::round(ta * r[1]) as i64]; + let d = [pos[0] as f64 - x[0], pos[1] as f64 - x[1]]; + let k = (d[0] * d[0] + d[1] * d[1], pos); + if !within(k.0) { + continue; + } + if best.as_ref().is_none_or(|(b, ..)| k.partial_cmp(b) == Some(Ordering::Less)) { + best = Some((k, a.at(ta), b.at(tb))); + } + } + } + if let Some(((_, pos), sa, sb)) = best { + return (sa, sb, pos); + } + // No crossing of the curves near: each curve's foot of the chord crossing. + let foot_on = |segs: &[&Seg], chord: &Seg| { + let nearest = segs + .iter() + .map(|s| (projection(s, x), *s)) + .min_by(|a, b| a.0 .0.total_cmp(&b.0 .0).then(a.1.a.cmp(&b.1.a))); + let st = match nearest { + Some(((_, f), s)) => s.at(f), + None => chord.at(projection(chord, x).1), + }; + let part = &parts[st.part as usize]; + Station { u: super::snap::foot(part, st.span as usize, st.u, xi), ..st } + }; + (foot_on(&ps, chords.0), foot_on(&qs, chords.1), xi) +} + +/// The squared distance of x from a segment, and the parameter of its foot. +fn projection(s: &Seg, x: [f64; 2]) -> (f64, f64) { + let r = [(s.b[0] - s.a[0]) as f64, (s.b[1] - s.a[1]) as f64]; + let v = [x[0] - s.a[0] as f64, x[1] - s.a[1] as f64]; + let length2 = r[0] * r[0] + r[1] * r[1]; + let f = if length2 > 0.0 { ((v[0] * r[0] + v[1] * r[1]) / length2).clamp(0.0, 1.0) } else { 0.0 }; + let e = [v[0] - f * r[0], v[1] - f * r[1]]; + (e[0] * e[0] + e[1] * e[1], f) +} + +/// The end of a synthetic stretch: metres along its piece, and its station. +type StretchEnd = (f64, Station); + +/// One side of a crossing. +#[derive(Clone, Copy)] +struct Side<'a> { + piece: usize, + st: Station, + family: Family, + level: Level, + z: f64, + rule: &'a Rule<'a>, +} + +/// What the table gives a crossing. +enum Outcome { + Record(CrossingKind, Source), + Implicit, + /// A synthetic deck or footbridge over the lower side, and the half-width that it spans. + Synthetic(CrossingKind, f64), + /// A tunnel way under the other side. Its stations are no samples: storey 0 stays as it is. + Bore, +} + +/// The length of a culvert chain about a station, read up to `limit` metres each way. +fn chain(parts: &[Part], plan: &Plan, at: &BTreeMap<([i64; 2], Network), &Node>, side: &Side, limit: f64) -> f64 { + let mut total = 0.0; + for start in [1i8, -1] { + let (mut piece, mut m, mut dir, mut run) = + (side.piece, metres(parts, &plan.pieces[side.piece], &side.st), start, 0.0); + for _ in 0..64 { + let p = &plan.pieces[piece]; + let rest = if dir > 0 { metres(parts, p, &p.to) - m } else { m }; + run += rest; + if run > limit { + break; + } + let end = if dir > 0 { p.to } else { p.from }; + let pos = super::points::position(parts, &end); + let Some(node) = at.get(&(pos, Network::Water)).filter(|n| n.kind == NodeKind::Joint) else { break }; + let Some(other) = node.arms.iter().find(|a| a.piece != piece || a.dir == dir) else { break }; + if plan.pieces[other.piece].level != Level::Tunnel { + break; + } + (piece, m, dir) = (other.piece, other.m, other.dir); + } + total += run; + } + total +} + +/// The crossings of the pieces, the implicit junctions, and the pieces split at synthetic decks. +pub(crate) fn crossings( + cell: CellKey, + area: [i64; 4], + parts: &[Part], + rules: &[Rule<'_>], + samples: &mut [Vec], + mut plan: Plan, + stats: &mut GraphStats, +) -> Plan { + let prelim = nodes(parts, &plan, area, None); + let at: BTreeMap<([i64; 2], Network), &Node> = prelim.nodes.iter().map(|n| ((n.pos, n.network), n)).collect(); + let grid = Grid::chords(cell, parts, &plan.pieces); + let curves = Grid::new(cell, samples, &plan.pieces); + let mut pairs: Vec<(u32, u32)> = Vec::new(); + for ids in grid.buckets() { + for (i, &(_, x)) in ids.iter().enumerate() { + pairs.extend(ids[i + 1..].iter().map(|&(_, y)| (x.min(y), x.max(y)))); + } + } + pairs.sort_unstable(); + pairs.dedup(); + let o = cell.origin(); + let graze = GRAZE_DEG.to_radians(); + // (position, upper side, lower side, kind, source); synthetic decks wait for their test. + let mut found: Vec<([i64; 2], Side, Side, Outcome, f64)> = Vec::new(); + for (x, y) in pairs { + let (s, t) = (&grid.segs[x as usize], &grid.segs[y as usize]); + let (pa, pb) = (&plan.pieces[s.piece], &plan.pieces[t.piece]); + if pa.part == pb.part && s.sa.span.abs_diff(t.sa.span) <= 1 { + continue; + } + let Some((ta, _)) = cross(s.a, s.b, t.a, t.b) else { continue }; + let r = [(s.b[0] - s.a[0]) as f64, (s.b[1] - s.a[1]) as f64]; + let exact = [s.a[0] as f64 + ta * r[0], s.a[1] as f64 + ta * r[1]]; + let meet = [libm::round(exact[0]) as i64, libm::round(exact[1]) as i64]; + if prelim.meets.get(&meet).is_some_and(|p| p.contains(&s.piece) && p.contains(&t.piece)) { + continue; + } + // A way whose first vertex lies on the other's chord ends on it. Half-open chords never + // meet at a last vertex. + let ends_on = |e: &Seg, o: &Seg| { + let part = &parts[e.sa.part as usize]; + let first = GlobalPoint { x: part.vertices[0].pos[0], y: part.vertices[0].pos[1] }; + let chord = |v: [i64; 2]| GlobalPoint { x: v[0], y: v[1] }; + e.sa.span == 0 && end_on_chord(first, chord(o.a), chord(o.b)) + }; + if ends_on(s, t) || ends_on(t, s) { + stats.end_on_other += 1; + continue; + } + let (st_a, st_b, pos) = place(&curves, (s, t), parts, exact); + let side = |piece_index: usize, st: Station| { + let piece = &plan.pieces[piece_index]; + let part = &parts[piece.part]; + Side { + piece: piece_index, + st, + family: part.family, + level: piece.level, + z: point(part, st.span as usize, st.u).z_m, + rule: &rules[piece.part], + } + }; + let (a, b) = (side(s.piece, st_a), side(t.piece, st_b)); + let q = [(t.b[0] - t.a[0]) as f64, (t.b[1] - t.a[1]) as f64]; + let angle = libm::atan2((r[0] * q[1] - r[1] * q[0]).abs(), (r[0] * q[0] + r[1] * q[1]).abs()); + let water = |x: &Side| x.family == Family::Water; + let culvert = + |w: &Side, x: &Side| water(w) && w.level == Level::Tunnel && !water(x) && x.level == Level::Ground; + if (a.level == Level::Tunnel || b.level == Level::Tunnel) && !culvert(&a, &b) && !culvert(&b, &a) { + let water_tunnel = |x: &Side| water(x) && x.level == Level::Tunnel; + if water_tunnel(&a) || water_tunnel(&b) || (a.level == b.level && angle < graze) { + continue; + } + // The tag gives the roles: the tunnel way is under; of two, the heights. + let tunnel = |x: &Side| x.level == Level::Tunnel; + let (u, l) = if tunnel(&a) && (!tunnel(&b) || b.z > a.z) { (b, a) } else { (a, b) }; + found.push((pos, u, l, Outcome::Bore, angle)); + continue; + } + if water(&a) && water(&b) { + stats.water_water += 1; + continue; + } + if !water(&a) && !water(&b) && a.level == b.level && angle < graze { + stats.grazing += 1; + continue; + } + let outcome = if a.level == Level::Deck || b.level == Level::Deck { + let over_a = b.level != Level::Deck || (a.level == Level::Deck && a.z >= b.z); + let (u, l) = if over_a { (a, b) } else { (b, a) }; + (Outcome::Record(CrossingKind::Deck, Source::Tag), u, l) + } else if water(&a) || water(&b) { + let (w, x) = if water(&a) { (a, b) } else { (b, a) }; + let out = if w.level == Level::Tunnel { + let limit = w.rule.water().culvert_max_m; + if chain(parts, &plan, &at, &w, limit) <= limit { + Outcome::Record(CrossingKind::Culvert, Source::Tag) + } else { + stats.buried += 1; + Outcome::Record(CrossingKind::Culvert, Source::Fallback) + } + } else if x.rule.ford() && fords(x.family, w.rule.water()) { + Outcome::Record(CrossingKind::Ford, Source::Tag) + } else if angle < graze { + stats.grazing_water += 1; + Outcome::Record(CrossingKind::Stacked, Source::Fallback) + } else { + let water = w.rule.water(); + let width = water.width_m; + let half = width / 2.0 + WATER_BANK_M + DECK_SIDE_M; + match x.family { + Family::Path if width <= water.pipe_width_m => { + Outcome::Record(CrossingKind::PipeInStones, Source::Rule) + } + Family::Path if width <= water.stones_width_m => { + Outcome::Record(CrossingKind::SteppingStones, Source::Rule) + } + Family::Path => Outcome::Synthetic(CrossingKind::Footbridge, half), + _ if width <= water.culvert_width_m => Outcome::Record(CrossingKind::Culvert, Source::Rule), + _ => Outcome::Synthetic(CrossingKind::Deck, half), + } + }; + (out, x, w) + } else { + let (u, l) = if a.z >= b.z { (a, b) } else { (b, a) }; + let dz = u.z - l.z; + let level = dz <= a.rule.way().snap_height_m.min(b.rule.way().snap_height_m); + let rail = |x: &Side| x.family == Family::Rail; + let out = if level && rail(&a) != rail(&b) { + Outcome::Record(CrossingKind::LevelCrossing, Source::Rule) + } else if level && !rail(&a) && !rail(&b) { + Outcome::Implicit + } else if dz >= l.rule.way().clearance_m { + Outcome::Synthetic(CrossingKind::Deck, l.rule.outer_m() + DECK_SIDE_M) + } else { + Outcome::Record(CrossingKind::Stacked, Source::Fallback) + }; + (out, u, l) + }; + let (outcome, upper, lower) = outcome; + found.push((pos, upper, lower, outcome, angle)); + } + found.sort_by_key(|a| (a.0, a.1.piece.min(a.2.piece), a.1.piece.max(a.2.piece))); + // Two chord crossings of one pair at one curve crossing are one crossing. + found.dedup_by_key(|a| (a.0, a.1.piece.min(a.2.piece), a.1.piece.max(a.2.piece))); + let local = |p: [i64; 2]| [(p[0] - o.x) as i32, (p[1] - o.y) as i32]; + let record = |pos, over: Station, under: Station, kind, source, angle| Crossing { + pos: local(pos), + over, + under, + kind, + source, + angle_rad: angle, + deck: None, + owned: false, + ladder: None, + }; + // Synthetic stretches by piece: the metres and the stations of their ends. + let mut stretches: BTreeMap> = BTreeMap::new(); + let mut stations: Vec<(usize, Station)> = Vec::new(); + for (pos, upper, lower, outcome, _) in &found { + if let Outcome::Implicit = outcome { + for side in [upper, lower] { + plan.anchors.push(Anchor { pos: *pos, at: side.st, implicit: true }); + stations.push((plan.pieces[side.piece].part, side.st)); + } + } + } + for (pos, upper, lower, outcome, angle) in found { + let piece = &plan.pieces[upper.piece]; + match outcome { + Outcome::Implicit => {} + Outcome::Bore => { + plan.crossings.push(record(pos, upper.st, lower.st, CrossingKind::Bore, Source::Tag, angle)); + } + Outcome::Record(kind, source) => { + stations.push((piece.part, upper.st)); + stations.push((plan.pieces[lower.piece].part, lower.st)); + plan.crossings.push(record(pos, upper.st, lower.st, kind, source, angle)); + } + Outcome::Synthetic(kind, half) => { + let d = half / libm::sin(angle); + let m = metres(parts, piece, &upper.st); + let near = |m2: f64| (m2 - m).abs() <= d; + let on_piece = |st: &Station| { + st.part as usize == piece.part && key(&piece.from) <= key(st) && key(st) <= key(&piece.to) + }; + let holds = + prelim.nodes.iter().flat_map(|n| &n.arms).any(|arm| arm.piece == upper.piece && near(arm.m)) + || plan.anchors.iter().any(|a| on_piece(&a.at) && near(metres(parts, piece, &a.at))); + if !d.is_finite() || d > DECK_HALF_MAX_M || holds { + stats.deck_fallback += 1; + plan.crossings.push(record( + pos, + upper.st, + lower.st, + CrossingKind::Stacked, + Source::Fallback, + angle, + )); + continue; + } + let length = metres(parts, piece, &piece.to); + if m - d < 0.0 || m + d > length { + stats.deck_cut += 1; + } + let ends = ((m - d).max(0.0), (m + d).min(length)); + let at = |delta: f64| advance(parts, piece, &upper.st, delta); + stretches.entry(upper.piece).or_default().push(((ends.0, at(-d)), (ends.1, at(d)))); + stations.push((plan.pieces[lower.piece].part, lower.st)); + plan.crossings.push(record(pos, upper.st, lower.st, kind, Source::Rule, angle)); + } + } + } + // Every crossing point and implicit junction is a sample of both pieces. + let mut moved: BTreeMap<(usize, u32, u64), Station> = BTreeMap::new(); + for (part, st) in stations { + let taken = insert(&parts[part], &mut samples[part], st, cell); + moved.insert((part, st.span, st.u.to_bits()), taken); + } + let take = |st: &Station| moved.get(&(st.part as usize, st.span, st.u.to_bits())).copied().unwrap_or(*st); + for a in &mut plan.anchors { + a.at = take(&a.at); + } + for c in &mut plan.crossings { + (c.over, c.under) = (take(&c.over), take(&c.under)); + } + // Split each piece at its merged stretches: the middle is a synthetic deck. + let mut out = Vec::new(); + for (index, piece) in plan.pieces.iter().enumerate() { + let Some(list) = stretches.get_mut(&index) else { + out.push(piece.clone()); + continue; + }; + list.sort_by(|a, b| a.0 .0.total_cmp(&b.0 .0)); + let mut merged: Vec<(StretchEnd, StretchEnd)> = Vec::new(); + for &(a, b) in list.iter() { + match merged.last_mut() { + Some(last) if a.0 <= last.1 .0 => { + if b.0 > last.1 .0 { + last.1 = b; + } + } + _ => merged.push((a, b)), + } + } + let part = &parts[piece.part]; + let mut cut = |st: Station| insert(part, &mut samples[piece.part], st, cell); + let mut from = piece.from; + for (a, b) in merged { + let (sa, sb) = (cut(a.1), cut(b.1)); + if key(&from) < key(&sa) { + out.push(Piece { from, to: sa, ..piece.clone() }); + } + if key(&sa) < key(&sb) { + out.push(Piece { from: sa, to: sb, level: Level::Deck, synthetic: true, ..piece.clone() }); + } + from = sb; + } + if key(&from) < key(&piece.to) { + out.push(Piece { from, ..piece.clone() }); + } + } + plan.pieces = out; + plan +} diff --git a/host/obc-ground-plan/src/graph/curve.rs b/host/obc-ground-plan/src/graph/curve.rs new file mode 100644 index 0000000000..a985eb09b9 --- /dev/null +++ b/host/obc-ground-plan/src/graph/curve.rs @@ -0,0 +1,652 @@ +//! The curve of a span: the cubic Hermite of format 4 in frame units, its arc metres, its roots on +//! the cell lines, and its samples on a dyadic grid of span metres. + +use super::parts::Rule; +use super::{ + Part, Sample, SampleKind, Span, Vertex, BASE_STEP_M, KNOTS, LEVELS, MIN_STEP_M, NEWTON_STEPS, ROOT_STEPS, SPIKE_DEG, +}; +use crate::frame::{metres_per_unit, CellKey, CELL_UNITS}; + +/// A point of a span's curve. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SpanPoint { + /// Frame units from the span's start vertex. + pub d: [f64; 2], + /// The unit tangent. + pub tangent: [f64; 2], + pub z_m: f64, + pub grade: f64, + pub bank: f64, + pub widen_m: f64, +} + +/// The plan of a span: the start vertex, the chord in frame units and its length, the unit tangents. +#[derive(Clone, Copy, Debug)] +pub(super) struct Geo { + pub p0: [i64; 2], + pub d: [f64; 2], + pub c: f64, + t0: [f64; 2], + t1: [f64; 2], + /// The length of the end tangents: the chord's length times the span's handle. + k: f64, + /// Metres per frame unit at the chord's middle. + pub mpu: f64, + chord: bool, +} + +/// The plan of a span from its vertices' tangents, with a full handle. +pub(super) fn geo(a: &Vertex, b: &Vertex, chord: bool) -> Geo { + shaped(a, b, chord, [a.tangent, b.tangent], 1.0) +} + +/// The plan of a span of a part. +pub(super) fn geo_of(a: &Vertex, b: &Vertex, span: &Span) -> Geo { + shaped(a, b, span.chord, span.ends, span.handle) +} + +fn shaped(a: &Vertex, b: &Vertex, chord: bool, ends: [f64; 2], handle: f64) -> Geo { + let d = [(b.pos[0] - a.pos[0]) as f64, (b.pos[1] - a.pos[1]) as f64]; + let mpu = metres_per_unit((a.pos[1] + b.pos[1]).div_euclid(2)); + Geo { p0: a.pos, mpu, chord, ..curve(d, ends[0], ends[1], handle) } +} + +/// The curve of a span from its start: chord `d`, tangent angles t0 and t1 and the handle, in the units +/// of `d`. +fn curve(d: [f64; 2], t0: f64, t1: f64, handle: f64) -> Geo { + let c = (d[0] * d[0] + d[1] * d[1]).sqrt(); + let unit = |angle: f64| [libm::cos(angle), libm::sin(angle)]; + Geo { p0: [0; 2], d, c, t0: unit(t0), t1: unit(t1), k: c * handle, mpu: 1.0, chord: false } +} + +impl Geo { + /// The position from p0, the first and the second derivative in u. + pub fn eval(&self, u: f64) -> [[f64; 2]; 3] { + if self.chord { + return [[u * self.d[0], u * self.d[1]], self.d, [0.0; 2]]; + } + let (u2, u3) = (u * u, u * u * u); + let h = [u3 - 2.0 * u2 + u, 3.0 * u2 - 2.0 * u3, u3 - u2]; + let dh = [3.0 * u2 - 4.0 * u + 1.0, 6.0 * u - 6.0 * u2, 3.0 * u2 - 2.0 * u]; + let ddh = [6.0 * u - 4.0, 6.0 - 12.0 * u, 6.0 * u - 2.0]; + let at = |w: [f64; 3], i: usize| w[0] * self.k * self.t0[i] + w[1] * self.d[i] + w[2] * self.k * self.t1[i]; + [[at(h, 0), at(h, 1)], [at(dh, 0), at(dh, 1)], [at(ddh, 0), at(ddh, 1)]] + } + + fn speed_m(&self, u: f64) -> f64 { + let d = if self.chord { + self.d + } else { + let u2 = u * u; + let dh = [3.0 * u2 - 4.0 * u + 1.0, 6.0 * u - 6.0 * u2, 3.0 * u2 - 2.0 * u]; + let at = |i: usize| dh[0] * self.k * self.t0[i] + dh[1] * self.d[i] + dh[2] * self.k * self.t1[i]; + [at(0), at(1)] + }; + (d[0] * d[0] + d[1] * d[1]).sqrt() * self.mpu + } + + /// The Bézier control points from p0: the curve lies in their hull. + pub fn hull(&self) -> [[f64; 2]; 4] { + if self.chord { + return [[0.0; 2], self.d, self.d, self.d]; + } + let k = self.k / 3.0; + [[0.0; 2], [k * self.t0[0], k * self.t0[1]], [self.d[0] - k * self.t1[0], self.d[1] - k * self.t1[1]], self.d] + } +} + +/// The tangents of water, which the tiles do not hold, per point its angle and whether it is a corner: +/// the bisector of its unit chords to the nearest other points, which leans to neither chord's length; +/// at an end its one chord. A point where the water turns by more than `turn_max_deg` (at most +/// `SPIKE_DEG`) is a corner. The reader and the bake's added water vertices share this curve. +pub(crate) fn water_tangents(points: &[[f64; 2]], turn_max_deg: f64) -> Vec<(f64, bool)> { + let cos_max = libm::cos(turn_max_deg.min(SPIKE_DEG).to_radians()); + let unit = |a: [f64; 2], b: [f64; 2]| { + let d = [b[0] - a[0], b[1] - a[1]]; + let length = (d[0] * d[0] + d[1] * d[1]).sqrt(); + [d[0] / length, d[1] / length] + }; + let tangent = |i: usize| { + let here = points[i]; + let prev = points[..i].iter().rev().find(|&&q| q != here); + match (prev, points[i + 1..].iter().find(|&&q| q != here)) { + (Some(&a), Some(&b)) => { + let (u, v) = (unit(a, here), unit(here, b)); + let sum = [u[0] + v[0], u[1] + v[1]]; + (if sum[0] * sum[0] + sum[1] * sum[1] > 1e-12 { sum } else { v }, u[0] * v[0] + u[1] * v[1] < cos_max) + } + (Some(&a), None) => (unit(a, here), false), + (None, Some(&b)) => (unit(here, b), false), + (None, None) => ([1.0, 0.0], false), + } + }; + (0..points.len()).map(tangent).map(|(t, corner)| (libm::atan2(t[1], t[0]), corner)).collect() +} + +/// The most that this curve leaves its chord, in the units of `d`, at 32 steps of u. +pub(crate) fn off_chord(d: [f64; 2], t0: f64, t1: f64) -> f64 { + let g = curve(d, t0, t1, 1.0); + let unit = [g.d[0] / g.c, g.d[1] / g.c]; + let off = |j: u32| { + let q = g.eval(f64::from(j) / 32.0)[0]; + (unit[0] * q[1] - unit[1] * q[0]).abs() + }; + (1..32).map(off).fold(0.0, f64::max) +} + +/// The shapes of the spans of water through `points`, with their tangents and corners +/// (`water_tangents`) and `metres` per unit of a span from its two points: per span None where it is +/// its chord (a corner at an end, no length, its curve leaves the chord by more than `off_max_m`, or it +/// folds back), else its end tangents and handle. A curve's end at a vertex whose other span is a chord +/// takes that chord's direction, so the outline turns smoothly there; where the curve then leaves its +/// chord by more than `off_max_m`, its tangents shorten until it leaves by that much. The curve's +/// distance from its chord scales with the handle. +pub(crate) fn water_spans( + points: &[[f64; 2]], + tangents: &[(f64, bool)], + metres: impl Fn([f64; 2], [f64; 2]) -> f64, + off_max_m: f64, +) -> Vec> { + let n = points.len().saturating_sub(1); + let chord_of = |k: usize| [points[k + 1][0] - points[k][0], points[k + 1][1] - points[k][1]]; + let off_m = |k: usize, t0: f64, t1: f64| off_chord(chord_of(k), t0, t1) * metres(points[k], points[k + 1]); + let chord: Vec = (0..n) + .map(|k| { + let (d, (t0, c0), (t1, c1)) = (chord_of(k), tangents[k], tangents[k + 1]); + c0 || c1 || d == [0.0; 2] || off_m(k, t0, t1) > off_max_m || folds(d, t0, t1) + }) + .collect(); + let along = |k: usize| { + let d = chord_of(k); + libm::atan2(d[1], d[0]) + }; + (0..n) + .map(|k| { + if chord[k] { + return None; + } + let start = if k > 0 && chord[k - 1] { along(k - 1) } else { tangents[k].0 }; + let end = if k + 1 < n && chord[k + 1] { along(k + 1) } else { tangents[k + 1].0 }; + if folds(chord_of(k), start, end) { + return None; + } + let off = off_m(k, start, end); + Some(([start, end], if off > off_max_m { off_max_m / off } else { 1.0 })) + }) + .collect() +} + +/// The grades (rise per metre) of water at `points` with levels `z` along its line: the harmonic mean of +/// the grades of its two chords where they fall the same way, else 0, and at an end or beside an unknown +/// level its one chord's. Heights between two vertices then follow `water_level`, which never rises past +/// either level and turns smoothly at a vertex. +pub fn water_grades(points: &[[f64; 2]], z: &[Option], metres: impl Fn([f64; 2], [f64; 2]) -> f64) -> Vec { + let chord = |k: usize| match (z[k], z[k + 1]) { + (Some(a), Some(b)) => { + let (p, q) = (points[k], points[k + 1]); + let m = libm::hypot(q[0] - p[0], q[1] - p[1]) * metres(p, q); + (m > 0.0).then(|| (b - a) / m) + } + _ => None, + }; + let n = points.len(); + (0..n) + .map(|k| { + let before = if k > 0 { chord(k - 1) } else { None }; + let after = if k + 1 < n { chord(k) } else { None }; + match (before, after) { + (Some(a), Some(b)) if a * b > 0.0 => 2.0 * a * b / (a + b), + (Some(_), Some(_)) | (None, None) => 0.0, + (Some(g), None) | (None, Some(g)) => g, + } + }) + .collect() +} + +/// The level of water and its grade at share t of the arc of a span `len_m` long, between the levels +/// `z` and the grades `grade` (`water_grades`) of its vertices: the cubic Hermite of both. +pub fn water_level(z: [f64; 2], grade: [f64; 2], len_m: f64, t: f64) -> (f64, f64) { + let (t2, t3) = (t * t, t * t * t); + let h = [2.0 * t3 - 3.0 * t2 + 1.0, t3 - 2.0 * t2 + t, 3.0 * t2 - 2.0 * t3, t3 - t2]; + let dh = [6.0 * t2 - 6.0 * t, 3.0 * t2 - 4.0 * t + 1.0, 6.0 * t - 6.0 * t2, 3.0 * t2 - 2.0 * t]; + let at = |w: [f64; 4]| w[0] * z[0] + w[1] * len_m * grade[0] + w[2] * z[1] + w[3] * len_m * grade[1]; + (at(h), at(dh) / len_m) +} + +/// Per span of water through `points` its curve (`water_tangents`, `water_spans`), from the span's start, +/// with `metres` per unit of a span from its two points. +pub fn water_curves( + points: &[[f64; 2]], + turn_max_deg: f64, + off_max_m: f64, + metres: impl Fn([f64; 2], [f64; 2]) -> f64, +) -> Vec { + let shapes = water_spans(points, &water_tangents(points, turn_max_deg), metres, off_max_m); + let chord = |w: &[[f64; 2]]| [w[1][0] - w[0][0], w[1][1] - w[0][1]]; + points.windows(2).zip(shapes).map(|(w, shape)| WaterCurve::new(chord(w), shape)).collect() +} + +/// The curve of a span of water with chord `d` and its shape from `water_spans` (None: its chord), in the +/// units of `d`, with its arc measured as a span's knots measure it. +pub struct WaterCurve { + g: Geo, + len: f64, + knots: [f64; KNOTS + 1], +} + +impl WaterCurve { + fn new(d: [f64; 2], shape: Option<([f64; 2], f64)>) -> WaterCurve { + let g = match shape { + Some((ends, handle)) => curve(d, ends[0], ends[1], handle), + None => Geo { chord: true, ..curve(d, 0.0, 0.0, 1.0) }, + }; + let (len, knots) = arc(&g); + WaterCurve { g, len, knots } + } + + /// The length of its arc in the units of `d`. + pub fn length(&self) -> f64 { + self.len + } + + /// The point at a share of its arc's length, from its start. + pub fn at_share(&self, share: f64) -> [f64; 2] { + self.g.eval(u_of(&self.knots, self.len, share * self.len))[0] + } + + /// The share of its arc's length at the point nearest to `p` (from its start), from a first share: + /// the Newton steps of the reader's foot of a point on a span. + pub fn share_near(&self, p: [f64; 2], share: f64) -> f64 { + let mut u = u_of(&self.knots, self.len, share * self.len); + for _ in 0..NEWTON_STEPS { + let [q, d, dd] = self.g.eval(u); + let v = [q[0] - p[0], q[1] - p[1]]; + let f = v[0] * d[0] + v[1] * d[1]; + let df = d[0] * d[0] + d[1] * d[1] + v[0] * dd[0] + v[1] * dd[1]; + if df <= 0.0 { + break; + } + u = (u - f / df).clamp(0.0, 1.0); + } + if self.len > 0.0 { + s_of(&self.knots, u) / self.len + } else { + 0.0 + } + } +} + +/// Whether a tangent points back against the chord: the curve folds, and the span is its chord. +pub(crate) fn folds(d: [f64; 2], t0: f64, t1: f64) -> bool { + let dot = |t: f64| libm::cos(t) * d[0] + libm::sin(t) * d[1]; + dot(t0) <= 0.0 || dot(t1) <= 0.0 +} + +/// The 5-point Simpson rule over an interval of width w of the values f at its quarters. +fn simpson(w: f64, f: &[f64]) -> f64 { + w * (f[0] + 4.0 * f[1] + 2.0 * f[2] + 4.0 * f[3] + f[4]) / 12.0 +} + +/// The metres of a span: the bake's `arc`, one 5-point Simpson rule with the scale at the chord's middle. +pub(super) fn length(a: &Vertex, b: &Vertex, chord: bool) -> f64 { + let g = geo(a, b, chord); + if chord { + return g.c * g.mpu; + } + simpson(1.0, &[0.0, 0.25, 0.5, 0.75, 1.0].map(|u| g.speed_m(u))) +} + +impl Span { + pub(super) fn new(a: &Vertex, b: &Vertex, chord: bool, along0_m: f64) -> Span { + Span::shaped(a, b, chord, [a.tangent, b.tangent], 1.0, along0_m) + } + + /// A span with its own end tangents and handle (`water_spans`). + pub(super) fn shaped(a: &Vertex, b: &Vertex, chord: bool, ends: [f64; 2], handle: f64, along0_m: f64) -> Span { + let (len_m, knots) = arc(&shaped(a, b, chord, ends, handle)); + Span { len_m, knots, along0_m, chord, ends, handle, water_z: false, owner: [0; 3] } + } +} + +/// The length of a curve in metres and its metres at the knots: a 5-point Simpson rule over the curve and +/// over each knot interval, scaled to the curve's length. +fn arc(g: &Geo) -> (f64, [f64; KNOTS + 1]) { + let f: Vec = (0..=4 * KNOTS).map(|j| g.speed_m(j as f64 / (4 * KNOTS) as f64)).collect(); + let len_m = if g.chord { g.c * g.mpu } else { simpson(1.0, &[f[0], f[16], f[32], f[48], f[64]]) }; + let mut knots = [0.0; KNOTS + 1]; + for k in 0..KNOTS { + let width = 1.0 / KNOTS as f64; + knots[k + 1] = knots[k] + if g.chord { width } else { simpson(width, &f[4 * k..4 * k + 5]) }; + } + let scale = len_m / knots[KNOTS]; + knots.iter_mut().for_each(|k| *k *= scale); + knots[KNOTS] = len_m; + (len_m, knots) +} + +/// The span metres at u: linear between the knots. +pub fn s_at(span: &Span, u: f64) -> f64 { + s_of(&span.knots, u) +} + +fn s_of(knots: &[f64; KNOTS + 1], u: f64) -> f64 { + let x = u.clamp(0.0, 1.0) * KNOTS as f64; + let k = (x as usize).min(KNOTS - 1); + knots[k] + (x - k as f64) * (knots[k + 1] - knots[k]) +} + +/// The u at span metres s: the inverse of `s_at`. +pub fn u_at(span: &Span, s: f64) -> f64 { + u_of(&span.knots, span.len_m, s) +} + +fn u_of(knots: &[f64; KNOTS + 1], len_m: f64, s: f64) -> f64 { + let s = s.clamp(0.0, len_m); + let k = knots[1..KNOTS].partition_point(|&knot| knot <= s); + let (a, b) = (knots[k], knots[k + 1]); + let f = if b > a { (s - a) / (b - a) } else { 0.0 }; + ((k as f64 + f) / KNOTS as f64).clamp(0.0, 1.0) +} + +/// The point of span `span` of a part at u. +pub fn point(part: &Part, span: usize, u: f64) -> SpanPoint { + let (a, b) = (&part.vertices[span], &part.vertices[span + 1]); + let data = &part.spans[span]; + point_of(&Of { g: geo_of(a, b, data), a, b, span: data }, u) +} + +/// The global point and the height at u of a span from its vertices. +pub(super) fn level_at(a: &Vertex, b: &Vertex, span: &Span, u: f64) -> ([i64; 2], f64) { + let g = geo_of(a, b, span); + let p = point_of(&Of { g, a, b, span }, u); + (round(&g, p.d), p.z_m) +} + +/// A span with its vertices and its plan. +struct Of<'a> { + g: Geo, + a: &'a Vertex, + b: &'a Vertex, + span: &'a Span, +} + +fn point_of(of: &Of, u: f64) -> SpanPoint { + let (g, a, b) = (&of.g, of.a, of.b); + let [d, dp, _] = g.eval(u); + let length = (dp[0] * dp[0] + dp[1] * dp[1]).sqrt(); + let tangent = if length > 0.0 { [dp[0] / length, dp[1] / length] } else { [1.0, 0.0] }; + let c_m = g.c * g.mpu; + let (z_m, grade) = if of.span.water_z { + let len = of.span.len_m; + water_level([a.z_m, b.z_m], [a.grade, b.grade], len, s_at(of.span, u) / len) + } else if g.chord { + (a.z_m + u * (b.z_m - a.z_m), (b.z_m - a.z_m) / c_m) + } else { + let (u2, u3) = (u * u, u * u * u); + let h = [2.0 * u3 - 3.0 * u2 + 1.0, u3 - 2.0 * u2 + u, 3.0 * u2 - 2.0 * u3, u3 - u2]; + let dh = [6.0 * u2 - 6.0 * u, 3.0 * u2 - 4.0 * u + 1.0, 6.0 * u - 6.0 * u2, 3.0 * u2 - 2.0 * u]; + let z = |w: [f64; 4]| w[0] * a.z_m + w[1] * c_m * a.grade + w[2] * b.z_m + w[3] * c_m * b.grade; + (z(h), z(dh) / (length * g.mpu)) + }; + let lerp = |p: f64, q: f64| p + u * (q - p); + SpanPoint { d, tangent, z_m, grade, bank: lerp(a.bank, b.bank), widen_m: lerp(a.widen_m, b.widen_m) } +} + +/// The global position of a point at u: p0 + δ rounded half away from zero. +pub(super) fn round(g: &Geo, d: [f64; 2]) -> [i64; 2] { + [g.p0[0] + libm::round(d[0]) as i64, g.p0[1] + libm::round(d[1]) as i64] +} + +/// The u where the curve crosses the line `axis` = value: the sign at the 17 knots, then +/// `ROOT_STEPS` bisections in each interval with a change. A touch without a change is no root. +pub(super) fn line_roots(g: &Geo, axis: usize, value: i64) -> Vec { + let offset = (value - g.p0[axis]) as f64; + let f = |u: f64| g.eval(u)[0][axis] - offset; + let sign = |u: f64| { + let v = f(u); + i8::from(v > 0.0) - i8::from(v < 0.0) + }; + let signs: Vec = (0..=KNOTS).map(|k| sign(k as f64 / KNOTS as f64)).collect(); + let mut roots = Vec::new(); + for k in 0..KNOTS { + if k > 0 && signs[k] == 0 && signs[k - 1] * signs[k + 1] < 0 { + roots.push(k as f64 / KNOTS as f64); + } + if signs[k] * signs[k + 1] < 0 { + let (mut lo, mut hi) = (k as f64 / KNOTS as f64, (k + 1) as f64 / KNOTS as f64); + for _ in 0..ROOT_STEPS { + let mid = (lo + hi) / 2.0; + if sign(mid) == signs[k] { + lo = mid; + } else { + hi = mid; + } + } + roots.push((lo + hi) / 2.0); + } + } + roots +} + +/// One sample before evaluation: u, span metres, kind and global position. +#[derive(Clone, Copy, Debug)] +struct Pt { + u: f64, + s: f64, + kind: SampleKind, + pos: [i64; 2], +} + +/// Whether the box of a span's control points meets the closed square. +pub(super) fn meets(part: &Part, span: usize, [x0, y0, x1, y1]: [i64; 4]) -> bool { + let g = geo_of(&part.vertices[span], &part.vertices[span + 1], &part.spans[span]); + let hull = g.hull(); + let lo = |i: usize| hull.iter().map(|p| p[i]).fold(f64::INFINITY, f64::min).floor() as i64 + g.p0[i]; + let hi = |i: usize| hull.iter().map(|p| p[i]).fold(f64::NEG_INFINITY, f64::max).ceil() as i64 + g.p0[i]; + hi(0) >= x0 && lo(0) <= x1 && hi(1) >= y0 && lo(1) <= y1 +} + +/// The samples of every span of a part whose control points' box meets the work area, ordered by +/// (span, u), and which spans those are. A vertex is (v, 0), but the part's last one. +pub(super) fn samples(part: &Part, rule: &Rule<'_>, cell: CellKey, area: [i64; 4]) -> (Vec, Vec) { + let mut out: Vec = Vec::new(); + let mut sampled = vec![false; part.spans.len()]; + for span in 0..part.spans.len() { + let before = span > 0 && sampled[span - 1]; + if !meets(part, span, area) { + if let (true, Some(last)) = (before, out.last_mut()) { + *last = Sample { span: span as u32, u: 0.0, s_m: 0.0, walk: part.vertices[span].walk, ..last.clone() }; + } + continue; + } + if before { + out.pop(); + } + let g = geo_of(&part.vertices[span], &part.vertices[span + 1], &part.spans[span]); + out.extend(span_samples(part, rule, span).into_iter().map(|pt| sample(part, g, span, pt, cell))); + sampled[span] = true; + } + (out, sampled) +} + +/// Insert a `Station` sample at a station of a sampled span, and give the station that it takes: a +/// sample other than a grid point within `MIN_STEP_M / 2` serves instead, and grid points that close go. +pub(super) fn insert(part: &Part, samples: &mut Vec, st: super::Station, cell: CellKey) -> super::Station { + let span = &part.spans[st.span as usize]; + let s = s_at(span, st.u); + let near = MIN_STEP_M / 2.0; + let vertex = |span: u32, u: f64| super::points::norm(part, super::Station { span, u, ..st }); + if s < near { + return vertex(st.span, 0.0); + } + if span.len_m - s < near { + return vertex(st.span, 1.0); + } + let same = |x: &Sample| x.span == st.span && x.u > 0.0 && (x.s_m - s).abs() < near; + if let Some(x) = samples.iter().find(|x| same(x) && x.kind != SampleKind::Grid) { + return super::Station { u: x.u, ..st }; + } + samples.retain(|x| !same(x)); + let at = samples.partition_point(|x| (x.span, x.u) < (st.span, st.u)); + samples.insert(at, station_sample(part, st.span as usize, st.u, cell)); + st +} + +/// A sample at a station of a span: the curve point rounded. +pub(super) fn station_sample(part: &Part, span: usize, u: f64, cell: CellKey) -> Sample { + let g = geo_of(&part.vertices[span], &part.vertices[span + 1], &part.spans[span]); + let pos = round(&g, g.eval(u)[0]); + sample(part, g, span, Pt { u, s: s_at(&part.spans[span], u), kind: SampleKind::Station, pos }, cell) +} + +fn sample(part: &Part, g: Geo, span: usize, pt: Pt, cell: CellKey) -> Sample { + let (a, b) = (&part.vertices[span], &part.vertices[span + 1]); + let p = point_of(&Of { g, a, b, span: &part.spans[span] }, pt.u); + let o = cell.origin(); + let sign = if part.backward { -1.0 } else { 1.0 }; + Sample { + pos: [(pt.pos[0] - o.x) as i32, (pt.pos[1] - o.y) as i32], + span: span as u32, + u: pt.u, + s_m: pt.s, + along_m: part.spans[span].along0_m + sign * pt.s, + z_m: p.z_m, + tangent: p.tangent, + grade: p.grade, + bank: p.bank, + widen_m: p.widen_m, + walk: a.walk, + kind: pt.kind, + } +} + +/// The samples of one span: its vertices, its cell-line breaks and the dyadic grid refined until each +/// chord holds the sag rules. +fn span_samples(part: &Part, rule: &Rule<'_>, span: usize) -> Vec { + let (a, b) = (&part.vertices[span], &part.vertices[span + 1]); + let data = &part.spans[span]; + let g = geo_of(a, b, data); + let at = |u: f64, kind: SampleKind, pos: [i64; 2]| Pt { u, s: s_at(data, u), kind, pos }; + let mut breaks = vec![at(0.0, SampleKind::Vertex, a.pos), at(1.0, SampleKind::Vertex, b.pos)]; + let hull = g.hull(); + for axis in 0..2 { + let lo = hull.iter().map(|p| p[axis]).fold(f64::INFINITY, f64::min).floor() as i64 + g.p0[axis]; + let hi = hull.iter().map(|p| p[axis]).fold(f64::NEG_INFINITY, f64::max).ceil() as i64 + g.p0[axis]; + for line in lo.div_euclid(CELL_UNITS) + 1..=hi.div_euclid(CELL_UNITS) { + for u in line_roots(&g, axis, line * CELL_UNITS) { + let mut pos = round(&g, g.eval(u)[0]); + pos[axis] = line * CELL_UNITS; + breaks.push(at(u, SampleKind::CellLine, pos)); + } + } + } + breaks.sort_by(|p, q| p.u.total_cmp(&q.u)); + let mut merged: Vec = Vec::with_capacity(breaks.len()); + for p in breaks { + match merged.last_mut() { + Some(last) if last.pos == p.pos => { + if p.kind == SampleKind::Vertex { + *last = p; + } + } + _ => merged.push(p), + } + } + let sag = Sag::of(rule); + let of = Of { g, a, b, span: data }; + let near_break = |s: f64| merged.iter().any(|p| (p.s - s).abs() < MIN_STEP_M / 2.0); + let grid = |level: u32, from: f64, to: f64| -> Vec { + let step = BASE_STEP_M / f64::from(1u32 << level); + let mut k = (from / step).floor() as i64 + 1; + let mut out = Vec::new(); + while (k as f64) * step < to { + let s = k as f64 * step; + if s > from && !near_break(s) { + let u = u_at(data, s); + out.push(Pt { u, s, kind: SampleKind::Grid, pos: round(&g, g.eval(u)[0]) }); + } + k += 1; + } + out + }; + let mut out = Vec::new(); + for pair in merged.windows(2) { + let (p, q) = (pair[0], pair[1]); + out.push(p); + let mut prev = p; + for r in grid(0, p.s, q.s) { + refine(&of, &sag, prev, r, 0, &grid, &mut out); + out.push(r); + prev = r; + } + refine(&of, &sag, prev, q, 0, &grid, &mut out); + } + out.extend(merged.last().copied()); + out +} + +/// The sag rules of a part: its outer half-width, and the most that a chord may leave the curve. +struct Sag { + outer_m: f64, + plan_m: f64, + height_m: f64, +} + +impl Sag { + fn of(rule: &Rule<'_>) -> Sag { + match rule { + Rule::Way(s, _) => Sag { outer_m: s.outer_m(), plan_m: s.sag_plan_m, height_m: s.sag_height_m }, + Rule::Water(w) => Sag { outer_m: w.half_m, plan_m: w.sag_plan_m, height_m: w.sag_height_m }, + } + } +} + +/// Push the grid points strictly between p and q that the sag test asks for, in order. +fn refine( + of: &Of, + sag: &Sag, + p: Pt, + q: Pt, + mut level: u32, + grid: &dyn Fn(u32, f64, f64) -> Vec, + out: &mut Vec, +) { + while level < LEVELS && sags(of, sag, p.u, q.u) { + level += 1; + let inner = grid(level, p.s, q.s); + if inner.is_empty() { + continue; + } + let mut prev = p; + for r in inner { + refine(of, sag, prev, r, level, grid, out); + out.push(r); + prev = r; + } + refine(of, sag, prev, q, level, grid, out); + return; + } +} + +/// Whether the chord from u0 to u1 leaves the curve by more than the sag rules: in plan at the +/// outer edge, or in height. +fn sags(of: &Of, sag: &Sag, u0: f64, u1: f64) -> bool { + let g = &of.g; + let (p, q) = (point_of(of, u0), point_of(of, u1)); + let chord = [q.d[0] - p.d[0], q.d[1] - p.d[1]]; + let length2 = chord[0] * chord[0] + chord[1] * chord[1]; + let mut plan: f64 = 0.0; + for f in [0.25, 0.5, 0.75] { + let m = g.eval(u0 + f * (u1 - u0))[0]; + let v = [m[0] - p.d[0], m[1] - p.d[1]]; + let t = if length2 > 0.0 { ((v[0] * chord[0] + v[1] * chord[1]) / length2).clamp(0.0, 1.0) } else { 0.0 }; + let e = [v[0] - t * chord[0], v[1] - t * chord[1]]; + plan = plan.max((e[0] * e[0] + e[1] * e[1]).sqrt() * g.mpu); + } + let cross = p.tangent[0] * q.tangent[1] - p.tangent[1] * q.tangent[0]; + let dot = p.tangent[0] * q.tangent[0] + p.tangent[1] * q.tangent[1]; + let turn = libm::atan2(cross.abs(), dot); + plan += (sag.outer_m + p.widen_m.max(q.widen_m)) * turn * turn / 8.0; + let mid = point_of(of, (u0 + u1) / 2.0); + plan > sag.plan_m || (mid.z_m - (p.z_m + q.z_m) / 2.0).abs() > sag.height_m +} diff --git a/host/obc-ground-plan/src/graph/level_tags.rs b/host/obc-ground-plan/src/graph/level_tags.rs new file mode 100644 index 0000000000..bba22b8087 --- /dev/null +++ b/host/obc-ground-plan/src/graph/level_tags.rs @@ -0,0 +1,566 @@ +//! The levels of the way graph as the feature tiles carry them: the bake runs `levels` on each cell and writes the +//! tags of each way from what the cells decide (`found`, `merge`); a cell's graph splits its ways at the end lines that +//! the tags give and takes the level of each stretch's state (`split`). +//! +//! A place on a way is its metres along its stroke (`Sample::along_m`): the same in every cell, as the spans are. + +use std::collections::BTreeMap; + +use super::curve::{insert, point, s_at, u_at}; +use super::parts::{classify, Rule}; +use super::points::{exact, key, norm, Piece, Plan}; +use super::{CrossingKind, EndKind, EndLine, Family, Level, Part, Run, Sample, State, Station, Step, WayGraph}; +use crate::faces::records::FLAT_TURN_DEG; +use crate::frame::{metres_per_unit_at, CellKey, GlobalPoint}; +use crate::sections::Sections; +use crate::tile::Tags; +use crate::CellInput; + +/// The states along a way: `S (m K S)*`, a state, then per end line its metres along the stroke, its kind and the +/// state past it, in rising metres. +pub const LEVELS: &str = "levels"; +/// The storey of a deck way over another deck, 2 or more. +pub const STOREY: &str = "storey"; +/// The depth of a deck way's slab on ladder step 2, metres. +pub const SLAB: &str = "slab"; +/// Two metres along that a cell and the bake read on one station are this near. +const SAME_M: f64 = 1e-6; +/// A chain of decks over decks is short; a loop (a spiral ramp) stops growing here. +const CHAIN_ROUNDS: usize = 8; + +const STATES: [(State, char); 4] = [(State::Deck, 'D'), (State::Bore, 'B'), (State::Open, 'O'), (State::Hidden, 'H')]; +const KINDS: [(EndKind, char); 3] = [(EndKind::A, 'A'), (EndKind::Portal, 'P'), (EndKind::Closed, 'C')]; + +/// What a cell decides of one feature: the runs and end lines of its ways inside the cell's square, in metres along +/// its stroke; the least depth of its slab on ladder step 2. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Found { + pub runs: Vec<(f64, f64, State)>, + pub lines: Vec<(f64, EndKind)>, + pub slab: Option, +} + +/// What one cell decides: per feature, by its zoom-13 tile and its position there, what `Found` holds; each deck group +/// (`WayGraph::decks`) whose ways belong to two features or more, as their keys; and the cell's own crossings of a +/// deck over a deck, as the keys of the lower and the upper feature. One deck group has one storey. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Cell { + pub found: BTreeMap<[u32; 3], Found>, + pub groups: Vec>, + pub over: Vec<([u32; 3], [u32; 3])>, +} + +/// The metres along the stroke at a station. +fn along(g: &WayGraph, st: &Station) -> f64 { + let part = &g.parts[st.part as usize]; + let span = &part.spans[st.span as usize]; + span.along0_m + if part.backward { -1.0 } else { 1.0 } * s_at(span, st.u) +} + +/// Whether every part of the feature of a way has an alignment: else its metres along start again in each tile. +fn aligned(g: &WayGraph, input: &CellInput, w: u32) -> bool { + let f = &input.features[g.parts[g.ways[w as usize].part as usize].feature.0 as usize]; + f.parts.iter().all(|p| p.plan.is_some()) +} + +fn deck_way(g: &WayGraph, w: u32) -> bool { + let x = &g.ways[w as usize]; + x.level == Level::Deck && x.family != Family::Water +} + +/// The crossings of a deck over a deck that the cell owns, whose ladder gives a deck (full or thin), as (lower way, +/// upper way). A deck is a DECK run of a bridge way, or a synthetic deck whole. +fn over(g: &WayGraph) -> Vec<(u32, u32)> { + let mut decked: BTreeMap> = BTreeMap::new(); + for r in g.levels.runs.iter().filter(|r| r.state == State::Deck && deck_way(g, r.way)) { + decked.entry(r.way).or_default().push((r.from, r.to)); + } + let tagged: Vec = g.levels.runs.iter().map(|r| r.way).collect(); + for w in (0..g.ways.len() as u32).filter(|&w| deck_way(g, w) && !tagged.contains(&w)) { + decked.insert(w, vec![(g.ways[w as usize].from, g.ways[w as usize].to)]); + } + let inside = |w: u32, st: &Station| { + decked.get(&w).is_some_and(|ps| ps.iter().any(|(a, b)| key(a) <= key(st) && key(st) <= key(b))) + }; + (g.crossings.iter()) + .filter(|c| c.kind == CrossingKind::Deck && c.owned) + .filter_map(|c| { + let l = c.ladder.as_ref().filter(|l| matches!(l.step, Step::Full | Step::Thin))?; + (inside(l.upper, &c.over) && inside(l.lower, &c.under)).then_some((l.lower, l.upper)) + }) + .collect() +} + +/// Whether way w lies inside the cell's square: a way lies on one side of each cell line, and the middle of its first +/// chord tells which. +pub fn inside(g: &WayGraph, w: u32) -> bool { + let r = &g.ways[w as usize].samples; + if r.is_empty() { + return false; + } + let (a, b) = (g.samples[r.start as usize].pos, g.samples[(r.start as usize + 1).min(r.end as usize - 1)].pos); + let (o, mid) = (g.cell.origin(), |k: usize| (i64::from(a[k]) + i64::from(b[k])) / 2); + g.cell.contains(GlobalPoint { x: o.x + mid(0), y: o.y + mid(1) }) +} + +/// What a cell's graph after `levels` decides of each feature that a way inside the cell's square has, and the deck +/// groups that join features. +pub fn found(g: &WayGraph, input: &CellInput, sections: &Sections) -> Cell { + let feature = |w: u32| { + let f = &input.features[g.parts[g.ways[w as usize].part as usize].feature.0 as usize]; + [f.parts[0].tile.0, f.parts[0].tile.1, f.index] + }; + let mut groups = Vec::new(); + for d in &g.decks { + let mut keys: Vec<[u32; 3]> = d.ways.iter().filter(|&&w| aligned(g, input, w)).map(|&w| feature(w)).collect(); + keys.sort_unstable(); + keys.dedup(); + if keys.len() > 1 { + groups.push(keys); + } + } + let pairs = over(g).into_iter().filter(|&(l, u)| aligned(g, input, l) && aligned(g, input, u)); + let over = pairs.map(|(l, u)| (feature(l), feature(u))).collect(); + let mut out: BTreeMap<[u32; 3], Found> = BTreeMap::new(); + for w in (0..g.ways.len() as u32).filter(|&w| inside(g, w) && aligned(g, input, w)) { + let runs: Vec<&Run> = g.levels.runs.iter().filter(|r| r.way == w).collect(); + let lines: Vec<&EndLine> = g.levels.end_lines.iter().filter(|l| l.way == w).collect(); + let thin = (g.crossings.iter().filter_map(|c| c.ladder.as_ref())) + .filter(|l| l.upper == w && l.step == Step::Thin && deck_way(g, w)) + .map(|l| { + let f = &input.features[g.parts[g.ways[w as usize].part as usize].feature.0 as usize]; + let least = sections.way(&f.kind, &f.tags, false).deck_least_m; + (l.room_m - l.least_m + least).max(least) + }) + .reduce(f64::min); + if runs.is_empty() && thin.is_none() { + continue; + } + let found = out.entry(feature(w)).or_default(); + found.runs.extend(runs.iter().map(|r| (along(g, &r.from), along(g, &r.to), r.state))); + found.lines.extend(lines.iter().map(|l| (along(g, &l.at), l.kind))); + found.slab = match (found.slab, thin) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + }; + } + Cell { found: out, groups, over } +} + +/// The kind of the end line between two states. +pub fn kind_between(a: State, b: State) -> EndKind { + match (a, b) { + (State::Hidden, _) | (_, State::Hidden) => EndKind::Closed, + (State::Deck, _) | (_, State::Deck) => EndKind::A, + _ => EndKind::Portal, + } +} + +/// The tags of each feature id from what the cells found of it, in the order of the cells, from the deck groups that +/// join ids and from the crossings of a deck over a deck (lower id, upper id). The features of one deck group, joined +/// over all cells, have one storey: 1, and one more than each group under them. +pub fn merge(found: &BTreeMap>, groups: &[Vec], over: &[(u32, u32)]) -> BTreeMap { + let ends = over.iter().flat_map(|&(l, u)| [l, u]); + let mut ids: Vec = found.keys().copied().chain(groups.iter().flatten().copied()).chain(ends).collect(); + ids.sort_unstable(); + ids.dedup(); + let at = |id: u32| ids.binary_search(&id).unwrap(); + let mut root: Vec = (0..ids.len()).collect(); + fn find(root: &mut [usize], mut i: usize) -> usize { + while root[i] != i { + root[i] = root[root[i]]; + i = root[i]; + } + i + } + for g in groups { + for pair in g.windows(2) { + let (a, b) = (find(&mut root, at(pair[0])), find(&mut root, at(pair[1]))); + root[a.max(b)] = a.min(b); + } + } + // The chain on the joined groups; a crossing of a group over itself lifts nothing. + let pairs: Vec<(usize, usize)> = + over.iter().map(|&(l, u)| (find(&mut root, at(l)), find(&mut root, at(u)))).collect(); + let mut storey = vec![1i8; ids.len()]; + for _ in 0..CHAIN_ROUNDS { + let mut changed = false; + for &(low, up) in pairs.iter().filter(|p| p.0 != p.1) { + if storey[up] <= storey[low] { + storey[up] = storey[low] + 1; + changed = true; + } + } + if !changed { + break; + } + } + let mut out = BTreeMap::new(); + for (k, &id) in ids.iter().enumerate() { + let r = find(&mut root, k); + let t = tags(found.get(&id).map_or(&[], Vec::as_slice), storey[r]); + if !t.is_empty() { + out.insert(id, t); + } + } + out +} + +/// The tags of one feature from what each cell found of it, with the storey of its deck group. The runs join in +/// rising metres; a change of state that no cell gives a line keeps the line of its two states. Lines at one metre +/// come in the order of their kinds (A, portal, closed). +fn tags(found: &[Found], storey: i8) -> Tags { + let (mut runs, mut lines, mut slab) = (Vec::new(), Vec::new(), None::); + for f in found { + runs.extend(f.runs.iter().map(|&(a, b, s)| (a.min(b), a.max(b), s))); + lines.extend(f.lines.iter().copied()); + slab = f.slab.map_or(slab, |s| Some(slab.map_or(s, |x: f64| x.min(s)))); + } + runs.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.2.cmp(&b.2))); + for k in 1..runs.len() { + if runs[k].2 != runs[k - 1].2 && !lines.iter().any(|l| (l.0 - runs[k].0).abs() <= SAME_M) { + lines.push((runs[k].0, kind_between(runs[k - 1].2, runs[k].2))); + } + } + lines.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + lines.dedup_by(|a, b| (a.0 - b.0).abs() <= SAME_M && a.1 == b.1); + let mut out = Tags::new(); + if let Some(first) = runs.first() { + // The state past each line: of the run that starts there, else of the run that holds it. + let past = |m: f64| { + let k = runs.partition_point(|r| r.0 <= m + SAME_M); + runs[k.saturating_sub(1)].2 + }; + let letter = |s: State| STATES.iter().find(|x| x.0 == s).unwrap().1; + let mut text = letter(first.2).to_string(); + for &(m, kind) in &lines { + let k = KINDS.iter().find(|x| x.0 == kind).unwrap().1; + text.push_str(&format!(" {m} {k} {}", letter(past(m)))); + } + out.insert(LEVELS.into(), text); + } + if storey > 1 { + out.insert(STOREY.into(), storey.to_string()); + } + if let Some(s) = slab { + out.insert(SLAB.into(), s.to_string()); + } + out +} + +/// An end line of `levels`: its metres along, its kind and the state past it. +type Line = (f64, EndKind, State); + +/// A feature's `levels`: its first state and its lines. +fn parse(text: &str) -> Option<(State, Vec)> { + let state = |t: &str| STATES.iter().find(|x| t.len() == 1 && t.starts_with(x.1)).map(|x| x.0); + let kind = |t: &str| KINDS.iter().find(|x| t.len() == 1 && t.starts_with(x.1)).map(|x| x.0); + let mut t = text.split(' '); + let first = state(t.next()?)?; + let mut lines = Vec::new(); + while let Some(m) = t.next() { + lines.push((m.parse().ok()?, kind(t.next()?)?, state(t.next()?)?)); + } + Some((first, lines)) +} + +/// The end line of way w at a station: across its stroke, and its band where `structure` is a deck or a bore. +pub fn end_line( + g: &WayGraph, + input: &CellInput, + sections: &Sections, + edge_band_m: f64, + (w, st, kind, structure): (u32, Station, EndKind, State), +) -> EndLine { + let part = &g.parts[st.part as usize]; + let sp = point(part, st.span as usize, st.u); + let p = exact(&g.parts, &st); + let half = match classify(&input.features[part.feature.0 as usize], sections).map(|c| c.3) { + Some(Rule::Way(s, _)) => s.half_m + sp.widen_m, + Some(Rule::Water(r)) => r.half_m, + None => 0.0, + }; + let band = if matches!(structure, State::Deck | State::Bore) { edge_band_m } else { 0.0 }; + let h = (half + band) / metres_per_unit_at(p[1]); + let (n, o) = ([-sp.tangent[1], sp.tangent[0]], g.cell.origin()); + let local = |s: f64| { + let q = [p[0] + s * n[0] * h, p[1] + s * n[1] * h]; + [(libm::round(q[0]) - o.x as f64) as i32, (libm::round(q[1]) - o.y as f64) as i32] + }; + EndLine { kind, way: w, at: st, ends: [local(1.0), local(-1.0)] } +} + +/// The pieces of a plan split at the end lines that the tiles carry (`LEVELS`), each with the level of its state: a +/// DECK stretch on its deck, an OPEN stretch on the ground (a bridge way's stub, or any way of the road solver), a +/// HIDDEN stretch not at all. A tunnel way keeps its level, and so does a synthetic deck. Each cut is a sample of its +/// part, so the stretches meet at a joint. +pub(crate) fn split(cell: CellKey, parts: &[Part], input: &CellInput, samples: &mut [Vec], plan: Plan) -> Plan { + let mut out = Vec::with_capacity(plan.pieces.len()); + for piece in &plan.pieces { + let part = &parts[piece.part]; + let f = &input.features[part.feature.0 as usize]; + let tag = f.tags.get(LEVELS).filter(|_| f.parts.iter().all(|p| p.plan.is_some())); + let levels = tag.and_then(|t| parse(t)).filter(|_| !piece.synthetic && part.level != Level::Tunnel); + let Some((first, lines)) = levels else { + out.push(piece.clone()); + continue; + }; + let sign = if part.backward { -1.0 } else { 1.0 }; + let along = |st: &Station| { + let span = &part.spans[st.span as usize]; + span.along0_m + sign * s_at(span, st.u) + }; + let state_at = |m: f64| lines.iter().take_while(|l| l.0 <= m).last().map_or(first, |l| l.2); + let (a0, a1) = (along(&piece.from), along(&piece.to)); + let (lo, hi) = (a0.min(a1) + SAME_M, a0.max(a1) - SAME_M); + // The station at metres m along the piece: on the first of its spans whose metres hold m. + let at = |m: f64| { + let span = (piece.from.span..=piece.to.span) + .find(|&k| { + (0.0..=part.spans[k as usize].len_m).contains(&(sign * (m - part.spans[k as usize].along0_m))) + }) + .unwrap_or(piece.to.span); + let s = sign * (m - part.spans[span as usize].along0_m); + norm(part, Station { part: piece.part as u32, span, u: u_at(&part.spans[span as usize], s) }) + }; + let mut cuts: Vec<(Station, f64)> = vec![(piece.from, a0)]; + let inner = lines.iter().map(|l| l.0).filter(|&m| (lo..=hi).contains(&m)); + let mut inner: Vec<(Station, f64)> = + inner.map(|m| (insert(part, &mut samples[piece.part], at(m), cell), m)).collect(); + if a1 < a0 { + inner.reverse(); + } + cuts.extend(inner.into_iter().filter(|c| key(&c.0) > key(&piece.from) && key(&c.0) < key(&piece.to))); + cuts.push((piece.to, a1)); + for c in cuts.windows(2) { + let level = match state_at((c[0].1 + c[1].1) / 2.0) { + State::Deck => Level::Deck, + State::Open => Level::Ground, + State::Bore => part.level, + State::Hidden => continue, + }; + match out.last_mut() { + Some(p) if p.part == piece.part && p.to == c[0].0 && p.level == level && p.link == piece.link => { + p.to = c[1].0 + } + _ => out.push(Piece { from: c[0].0, to: c[1].0, level, ..piece.clone() }), + } + } + } + Plan { pieces: out, ..plan } +} + +/// A junction with arms on the ground and on a deck lies on the ground: its arms meet at one height there, and the +/// ground's junction rounds its corners. Each deck arm's stretch from the junction up to its mouth, its first sample +/// where its stroke (its outer half-width and `band_m`) has left the strokes of the junction's ground arms that leave +/// across it, is a ground piece, which meets the rest of the deck at a joint as a stub meets its deck. A deck arm that +/// never leaves them is a ground piece as a whole. The mouth is a sample of the deck, so no new sample lies a few +/// centimetres from an old one. +/// Piece ends this near (frame units) are one node: a station's point is a curve point, not its vertex's exact one. +const NODE_UNITS: f64 = 4.0; + +pub(crate) fn ground_junctions( + parts: &[Part], + input: &CellInput, + sections: &Sections, + band_m: f64, + samples: &[Vec], + mut plan: Plan, +) -> Plan { + // A mouth can land on another node of the deck (a junction of two decks near the ground's): it lies on the + // ground then too. Each round only lowers deck to the ground at the samples of the decks, so the rounds end. + loop { + let next = ground_junctions_once(parts, input, sections, band_m, samples, plan.clone()); + if next.pieces == plan.pieces { + return plan; + } + plan = next; + } +} + +/// A piece's arm at a node: the piece, its end (0, 1) or 2 where it runs through, the station, the direction away. +type NodeArm = (usize, usize, Station, [f64; 2]); + +fn ground_junctions_once( + parts: &[Part], + input: &CellInput, + sections: &Sections, + band_m: f64, + samples: &[Vec], + plan: Plan, +) -> Plan { + let feature = |p: &Piece| &input.features[parts[p.part].feature.0 as usize]; + let half_m = |p: &Piece| sections.way(&feature(p).kind, &feature(p).tags, false).outer_m(); + let global = |part: &Part, st: &Station| { + let sp = point(part, st.span as usize, st.u); + let v = part.vertices[st.span as usize].pos; + ([v[0] as f64 + sp.d[0], v[1] as f64 + sp.d[1]], sp.tangent) + }; + let units = |m: f64, y: f64| m / metres_per_unit_at(y); + // The nodes of the pieces on the ground or on a (real) deck: per node, each piece's arm there, an end (0 or 1) or + // a vertex that it runs through (2), with its way's direction away from the node. + let nodes = |plan: &Plan| { + // The arms, and per arm its node's key (y, then x, in `NODE_UNITS`) and its place in the arms, sorted. + let mut arms: Vec = Vec::new(); + let mut keys: Vec<(u64, u32)> = Vec::new(); + for (i, p) in plan.pieces.iter().enumerate() { + let part = &parts[p.part]; + let deck = p.level == Level::Deck && !p.synthetic; + if part.family == Family::Water || !(p.level == Level::Ground || deck) { + continue; + } + let through = (p.from.span + 1..=p.to.span).map(|k| Station { span: k, u: 0.0, ..p.from }); + let ends = [(0, p.from), (1, p.to)].into_iter().chain(through.map(|st| (2, st))); + for (e, st) in ends.filter(|(e, st)| *e < 2 || key(st) < key(&p.to)) { + let (pos, t) = global(part, &st); + let node = |v: f64| u64::from((v / NODE_UNITS).round() as i64 as u32); + let back = [-t[0], -t[1]]; + let new: &[NodeArm] = match e { + 0 => &[(i, 0, st, t)], + 1 => &[(i, 1, st, back)], + _ => &[(i, 2, st, t), (i, 2, st, back)], + }; + for a in new { + keys.push((node(pos[1]) << 32 | node(pos[0]), arms.len() as u32)); + arms.push(*a); + } + } + } + keys.sort_unstable(); + keys.chunk_by(|a, b| a.0 == b.0) + .map(|c| c.iter().map(|k| arms[k.1 as usize]).collect::>()) + .collect::>() + }; + let mixed = |arms: &[NodeArm], plan: &Plan| { + arms.len() >= 3 + && arms.iter().any(|a| plan.pieces[a.0].level == Level::Ground) + && arms.iter().any(|a| plan.pieces[a.0].level == Level::Deck) + }; + // A deck that runs through such a node ends there. + let mut cuts: Vec<(usize, Station)> = Vec::new(); + for arms in nodes(&plan).iter().filter(|arms| mixed(arms, &plan)) { + for a in arms.iter().filter(|a| a.1 == 2 && plan.pieces[a.0].level == Level::Deck) { + if !cuts.contains(&(a.0, a.2)) { + // In order along the piece: a few cuts. + let at = cuts.iter().position(|c| (c.0, key(&c.1)) > (a.0, key(&a.2))).unwrap_or(cuts.len()); + cuts.insert(at, (a.0, a.2)); + } + } + } + let plan = if cuts.is_empty() { + plan + } else { + let mut pieces = Vec::with_capacity(plan.pieces.len() + cuts.len()); + for (i, p) in plan.pieces.iter().enumerate() { + let mut from = p.from; + for c in cuts.iter().filter(|c| c.0 == i) { + pieces.push(Piece { from, to: c.1, ..p.clone() }); + from = c.1; + } + pieces.push(Piece { from, ..p.clone() }); + } + Plan { pieces, ..plan } + }; + let ends = nodes(&plan); + // Per piece and end, the station of its mouth (none: the piece lies in the junction as a whole). + let mut mouths: Vec<((usize, usize), Option)> = Vec::new(); + for arms in ends.iter().filter(|a| mixed(a, &plan)) { + let ground: Vec<(usize, [f64; 2])> = + arms.iter().filter(|a| plan.pieces[a.0].level == Level::Ground).map(|a| (a.0, a.3)).collect(); + // The ground arms' strokes: points along their lines, their half-widths (units) and their directions. + let lines: Vec<(Vec<[f64; 2]>, f64, [f64; 2])> = (ground.iter().map(|&(g, dir)| (&plan.pieces[g], dir))) + .map(|(p, dir)| { + let part = &parts[p.part]; + let pts: Vec<[f64; 2]> = (p.from.span..=p.to.span) + .flat_map(|k| (0..=8).map(move |j| (k, f64::from(j) / 8.0))) + .filter(|&(k, u)| (k, u) >= (p.from.span, p.from.u) && (k, u) <= (p.to.span, p.to.u)) + .map(|(k, u)| global(part, &Station { part: p.from.part, span: k, u }).0) + .collect(); + let y = pts.first().map_or(0.0, |q| q[1]); + (pts, units(half_m(p), y), dir) + }) + .collect(); + // A ground arm within `FLAT_TURN_DEG` of the deck arm runs beside it, as two ways that meet side by side: it + // holds no mouth. + let across = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1] < libm::cos(FLAT_TURN_DEG.to_radians()); + let near = |q: [f64; 2], d: [f64; 2]| { + lines.iter().filter(|l| across(l.2, d)).any(|(pts, h, _)| { + pts.windows(2).any(|w| { + let (a, b) = (w[0], w[1]); + let d = [b[0] - a[0], b[1] - a[1]]; + let l2 = (d[0] * d[0] + d[1] * d[1]).max(1e-9); + let t = (((q[0] - a[0]) * d[0] + (q[1] - a[1]) * d[1]) / l2).clamp(0.0, 1.0); + libm::hypot(q[0] - a[0] - t * d[0], q[1] - a[1] - t * d[1]) < *h + }) + }) + }; + for &(i, e, _, dir) in arms.iter().filter(|a| a.1 < 2 && plan.pieces[a.0].level == Level::Deck) { + let p = &plan.pieces[i]; + let part = &parts[p.part]; + let k = |x: &Sample| (x.span, x.u); + let mut inner: Vec = (samples[p.part].iter()) + .filter(|x| k(x) > (p.from.span, p.from.u) && k(x) < (p.to.span, p.to.u)) + .map(|x| Station { part: p.from.part, span: x.span, u: x.u }) + .collect(); + if e == 1 { + inner.reverse(); + } + let clear = |st: &Station| { + let (c, t) = global(part, st); + let h = units(half_m(p) + band_m, c[1]); + let cross = [-1.0, -0.5, 0.0, 0.5, 1.0].map(|k| [c[0] - t[1] * h * k, c[1] + t[0] * h * k]); + !cross.iter().any(|&q| near(q, dir)) + }; + mouths.push(((i, e), inner.into_iter().find(clear))); + } + } + if mouths.is_empty() { + return plan; + } + let mut out = Vec::with_capacity(plan.pieces.len() + mouths.len()); + for (i, p) in plan.pieces.iter().enumerate() { + let mouth = |e: usize| mouths.iter().find(|m| m.0 == (i, e)).map(|m| m.1); + let (a, b) = (mouth(0), mouth(1)); + if a.is_none() && b.is_none() { + out.push(p.clone()); + continue; + } + // The deck between the mouths, the junctions' stretches on the ground. + let (lo, hi) = (a.unwrap_or(Some(p.from)), b.unwrap_or(Some(p.to))); + match lo.zip(hi).filter(|(l, h)| key(l) < key(h)) { + None => out.push(Piece { level: Level::Ground, ..p.clone() }), + Some((l, h)) => { + if l != p.from { + out.push(Piece { to: l, level: Level::Ground, ..p.clone() }); + } + out.push(Piece { from: l, to: h, ..p.clone() }); + if h != p.to { + out.push(Piece { from: h, level: Level::Ground, ..p.clone() }); + } + } + } + } + Plan { pieces: out, ..plan } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A viaduct of two features joined on its deck, and a third feature joined to the second: only the first crosses + /// over a deck L, and a deck U crosses over the second, each far from the other and from the joints, so no cell sees + /// two of them at once. The viaduct takes storey 2 as a whole and U storey 3; a crossing of the viaduct over itself + /// lifts nothing; L and a lone deck keep storey 1. + #[test] + fn the_storey_chain_runs_over_the_deck_groups_of_all_cells() { + let deck = || Found { runs: vec![(0.0, 50.0, State::Deck)], lines: Vec::new(), slab: None }; + let found = + BTreeMap::from([(1, vec![deck(), deck()]), (3, vec![deck()]), (5, vec![deck()]), (20, vec![deck()])]); + let tags = merge(&found, &[vec![1, 3], vec![3, 7]], &[(10, 1), (3, 20), (1, 7)]); + let storey = |id: u32| tags.get(&id).and_then(|t| t.get(STOREY)).map(String::as_str); + assert_eq!([storey(1), storey(3), storey(7)], [Some("2"); 3]); + assert_eq!(storey(20), Some("3"), "U over the viaduct"); + assert_eq!([storey(10), storey(5)], [None, None], "a deck on storey 1 has no tag"); + assert_eq!(tags[&7].get(LEVELS), None, "a feature that no cell decides has only the storey"); + } +} diff --git a/host/obc-ground-plan/src/graph/levels.rs b/host/obc-ground-plan/src/graph/levels.rs new file mode 100644 index 0000000000..a50f42c173 --- /dev/null +++ b/host/obc-ground-plan/src/graph/levels.rs @@ -0,0 +1,1141 @@ +//! The levels of bridges and tunnels, after `build`: per crossing the room between its two ways and +//! its step of the ladder; per station of a tagged way its state; the end lines where a state changes. +//! The bake runs it on every cell and the tiles carry what it decides (`level_tags`); the device reads that. +//! +//! Every decision reads within the row of `Structures::reach`: a crossing's corners along each way up +//! to `PLACE_M`; a station's tag end along its way up to `open_max_m`, an A line up to `A_MAX_M`; the +//! bodies and strokes within `GRID_M` of a station. + +use super::curve::point; +use super::level_tags::{end_line, kind_between}; +use super::parts::{classify, Rule}; +use super::points::{advance, between, exact, key, Piece}; +use super::{CrossingKind, Family, Fault, Level, Sample, Station, Way, WayGraph, PLACE_M}; +use crate::frame::{metres_per_unit_at, GlobalPoint}; +use crate::sections::{Reach, Sections, HALF_MAX_M}; +use crate::CellInput; + +/// The rule values of the structures: `plan.json` `structures`. +#[derive(Clone, Debug, PartialEq)] +pub struct Structures { + /// The cover over a full bore. + pub cover_m: f64, + /// Free ground over a bore may lack this much of the least room. + pub lift_max_m: f64, + /// A tunnel way is open only this far along from a tag end: the longest open cut of the crossing design. + pub open_max_m: f64, + /// A deck shorter than this between its end lines is a ground way. + pub deck_min_m: f64, + /// The band past a deck's paved edge. + pub edge_band_m: f64, + /// A closed end gets a door from this step on. + pub door_min_m: f64, + /// A deck narrower than this, band to band, gets a railing in place of a parapet (`mesh::shell`). + pub railing_width_m: f64, + /// A railing's posts stand at every multiple of this along its deck way. + pub post_spacing_m: f64, + /// A pier stands this far into the ground under it. + pub pier_depth_m: f64, +} + +impl Structures { + pub const FIELDS: [&'static str; 9] = [ + "cover_m", + "lift_max_m", + "open_max_m", + "deck_min_m", + "edge_band_m", + "door_min_m", + "railing_width_m", + "post_spacing_m", + "pier_depth_m", + ]; + + pub fn new( + [cover_m, lift_max_m, open_max_m, deck_min_m, edge_band_m, door_min_m, railing_width_m, post_spacing_m, pier_depth_m]: [f64; 9], + ) -> Structures { + Structures { + cover_m, + lift_max_m, + open_max_m, + deck_min_m, + edge_band_m, + door_min_m, + railing_width_m, + post_spacing_m, + pier_depth_m, + } + } + + /// The row of the reach table: the graph's own longest chain, then a station's read along its way, + /// the reads about it, and a crossing's corners. + pub fn reach(&self, graph_m: f64) -> Reach { + let terms = [ + ("the graph's longest chain", graph_m), + ("along the way: max(open_max_m, A_MAX_M)", self.open_max_m.max(A_MAX_M)), + ("about a station: GRID_M", GRID_M), + ("a crossing's corners along each way: PLACE_M", PLACE_M), + ]; + Reach { + name: "graph levels".into(), + owner: "graph", + chain: true, + terms: terms.iter().map(|&(what, m)| (what.to_string(), m)).collect(), + } + } +} + +/// The ladder: what the room between two crossing ways allows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Step { + Full, + Thin, + Closed, + AtGrade, + /// The heights put the lower way over the upper one: drawn as `Closed`. + Inverted, +} + +/// The step of room `r` between the rooms `full` and `least`, with `snap` the at-grade band. +pub fn step(r: f64, full: f64, least: f64, snap: f64) -> Step { + if r < -snap { + Step::Inverted + } else if r <= snap { + Step::AtGrade + } else if r < least { + Step::Closed + } else if r < full { + Step::Thin + } else { + Step::Full + } +} + +/// The ladder of a crossing: the roles, the room and its step, and on step 3 the way that ends. +#[derive(Clone, Debug, PartialEq)] +pub struct Ladder { + pub upper: u32, + pub lower: u32, + pub room_m: f64, + pub full_m: f64, + pub least_m: f64, + pub step: Step, + /// On `Closed` and `Inverted`: the way that ends; None over water (a culvert). + pub ends: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum State { + Deck, + Bore, + /// A ground way. + Open, + /// Not drawn: storey 0 over it is whole. + Hidden, +} + +/// A stretch of one state of a way, from station to station. +#[derive(Clone, Debug, PartialEq)] +pub struct Run { + pub way: u32, + pub from: Station, + pub to: Station, + pub state: State, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum EndKind { + A, + Portal, + Closed, +} + +/// One straight line across a way where its state changes, normal to its curve there. +#[derive(Clone, Debug, PartialEq)] +pub struct EndLine { + pub kind: EndKind, + pub way: u32, + pub at: Station, + /// Frame units from the cell's origin. + pub ends: [[i32; 2]; 2], +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Levels { + pub runs: Vec, + pub end_lines: Vec, +} + +/// A body read past the widest half-width: the widest class reach and widening. +const BODY_M: f64 = 12.0; +/// The farthest read about a station: a bore's side or a deck stroke, and a body there. +const GRID_M: f64 = HALF_MAX_M + BODY_M + 13.0; +/// An A line lies at most this far into its deck from the tag end; farther, the way is ground. +const A_MAX_M: f64 = 40.0; +/// The steps of the search for an end line A, metres. +const A_STEP_M: f64 = 0.1; +/// End lines are placed to this, metres. +const PLACE_TO_M: f64 = 0.01; + +/// The nearest point of a way's centre polyline: segment `k` (sample index), share `t`, distance and +/// metres across in frame units. +#[derive(Clone, Copy, Debug)] +struct Foot { + way: u32, + k: usize, + t: f64, + d: f64, + across: f64, +} + +/// A point on a way at a station, in global frame units. +#[derive(Clone, Copy, Debug)] +struct At { + st: Station, + p: [f64; 2], + tangent: [f64; 2], + z: f64, + bank: f64, + widen: f64, +} + +fn sub(a: [f64; 2], b: [f64; 2]) -> [f64; 2] { + [a[0] - b[0], a[1] - b[1]] +} + +fn dot(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[0] + a[1] * b[1] +} + +fn cross(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[1] - a[1] * b[0] +} + +fn add(a: [f64; 2], b: [f64; 2], s: f64) -> [f64; 2] { + [a[0] + s * b[0], a[1] + s * b[1]] +} + +/// The distance of p from segment ab, and the share of its foot. +fn seg_foot(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> (f64, f64) { + let ab = sub(b, a); + let l2 = dot(ab, ab); + let t = if l2 > 0.0 { (dot(sub(p, a), ab) / l2).clamp(0.0, 1.0) } else { 0.0 }; + let e = sub(p, add(a, ab, t)); + (dot(e, e).sqrt(), t) +} + +/// The distance between segments ab and cd. +fn segs_dist(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> f64 { + let side = |p, q, r| cross(sub(q, p), sub(r, p)).signum(); + if side(a, b, c) * side(a, b, d) < 0.0 && side(c, d, a) * side(c, d, b) < 0.0 { + return 0.0; + } + let f = |p, q, r| seg_foot(p, q, r).0; + f(a, c, d).min(f(b, c, d)).min(f(c, a, b)).min(f(d, a, b)) +} + +struct Ctx<'a> { + g: &'a WayGraph, + input: &'a CellInput, + sections: &'a Sections, + rules: Vec>, + s: &'a Structures, + origin: [f64; 2], + /// Sample segments near a way with a state, by bucket: (bucket, first sample index). + grid: Vec<([i64; 2], u32)>, + /// The way of each sample. + way_of: Vec, + size: f64, + /// The other arms at each end of a way: (way, at its start); None where the graph holds no point. + nodes: Vec>>, + lengths: Vec, +} + +impl<'a> Ctx<'a> { + fn new(g: &'a WayGraph, input: &'a CellInput, sections: &'a Sections, s: &'a Structures) -> Ctx<'a> { + let o = g.cell.origin(); + let origin = [o.x as f64, o.y as f64]; + let rules = (g.parts.iter()) + .map(|p| classify(&input.features[p.feature.0 as usize], sections).expect("a part of a line feature").3) + .collect(); + let mut nodes: Vec>> = vec![None; 2 * g.ways.len()]; + let sets = (g.junctions.iter().map(|j| j.arms.iter().collect::>())) + .chain(g.joints.iter().map(|j| j.arms.iter().collect())) + .chain(g.ends.iter().map(|e| vec![&e.arm])); + for arms in sets { + for a in &arms { + let others = arms.iter().filter(|b| !std::ptr::eq(**b, *a)).map(|b| (b.way, b.dir > 0)).collect(); + nodes[2 * a.way as usize + usize::from(a.dir > 0)] = Some(others); + } + } + let mut way_of = vec![0; g.samples.len()]; + for w in &g.ways { + way_of[w.samples.start as usize..w.samples.end as usize].fill(w.id); + } + Ctx { + g, + input, + sections, + rules, + s, + origin, + grid: Vec::new(), + way_of, + size: super::BUCKET_M / metres_per_unit_at(origin[1]), + nodes, + lengths: g.ways.iter().map(|w| between(&g.parts, &w.from, &w.to)).collect(), + } + } + + fn others(&self, w: u32, start: bool) -> Option<&[(u32, bool)]> { + self.nodes[2 * w as usize + usize::from(start)].as_deref() + } + + fn rule(&self, w: u32) -> &Rule<'a> { + &self.rules[self.g.ways[w as usize].part as usize] + } + + fn samples(&self, w: u32) -> &'a [Sample] { + let r = &self.g.ways[w as usize].samples; + &self.g.samples[r.start as usize..r.end as usize] + } + + fn global(&self, s: &Sample) -> [f64; 2] { + [self.origin[0] + f64::from(s.pos[0]), self.origin[1] + f64::from(s.pos[1])] + } + + fn mpu(&self, p: [f64; 2]) -> f64 { + metres_per_unit_at(p[1]) + } + + fn water(&self, w: u32) -> bool { + self.g.ways[w as usize].family == Family::Water + } + + /// A bridge way of the tiles (not a synthetic deck) or a tunnel way that is not water. + fn tagged(&self, w: u32) -> bool { + self.deck_tagged(w) || self.tunnel(w) + } + + fn deck_tagged(&self, w: u32) -> bool { + let way = &self.g.ways[w as usize]; + way.level == Level::Deck && self.g.parts[way.part as usize].level == Level::Deck + } + + fn tunnel(&self, w: u32) -> bool { + self.g.ways[w as usize].level == Level::Tunnel && !self.water(w) + } + + fn station(&self, w: u32, s: &Sample) -> Station { + Station { part: self.g.ways[w as usize].part, span: s.span, u: s.u } + } + + fn at_station(&self, st: Station) -> At { + let part = &self.g.parts[st.part as usize]; + let sp = point(part, st.span as usize, st.u); + At { st, p: exact(&self.g.parts, &st), tangent: sp.tangent, z: sp.z_m, bank: sp.bank, widen: sp.widen_m } + } + + /// The point `d` metres along the part of a station, at most to the part's ends. + fn along(&self, st: &Station, d: f64) -> At { + let part = &self.g.parts[st.part as usize]; + let n = part.spans.len() as u32; + let to = Station { part: st.part, span: n - 1, u: 1.0 }; + let whole = Piece { + part: st.part as usize, + from: Station { part: st.part, span: 0, u: 0.0 }, + to, + level: Level::Ground, + link: None, + synthetic: false, + }; + self.at_station(advance(&self.g.parts, &whole, st, d)) + } + + fn at(&self, w: u32, m: f64) -> At { + self.along(&self.g.ways[w as usize].from, m.min(self.lengths[w as usize])) + } + + /// The paved half-width of a way, metres. + fn half(&self, w: u32, widen: f64) -> f64 { + match self.rule(w) { + Rule::Way(s, _) => s.half_m + widen, + Rule::Water(r) => r.half_m, + } + } + + fn snap_m(&self, w: u32) -> f64 { + match self.rule(w) { + Rule::Way(s, _) => s.snap_height_m, + Rule::Water(_) => 0.0, + } + } + + /// The nearest point of each way within `reach_m` of q, in way order: the one search of the stage. + fn feet(&self, q: [f64; 2], reach_m: f64) -> Vec { + let r = reach_m / self.mpu(q); + let b = |v: f64| (v / self.size).floor() as i64; + let mut ks: Vec = Vec::new(); + for y in b(q[1] - r)..=b(q[1] + r) { + for x in b(q[0] - r)..=b(q[0] + r) { + let from = self.grid.partition_point(|e| e.0 < [x, y]); + ks.extend(self.grid[from..].iter().take_while(|e| e.0 == [x, y]).map(|e| e.1)); + } + } + ks.sort_unstable(); + ks.dedup(); + let mut best: Vec = Vec::new(); + for k in ks { + let (a, c) = (&self.g.samples[k as usize], &self.g.samples[k as usize + 1]); + let (pa, pc) = (self.global(a), self.global(c)); + let (d, t) = seg_foot(q, pa, pc); + let ab = sub(pc, pa); + let l = dot(ab, ab).sqrt(); + let u = if l > 0.0 { [ab[0] / l, ab[1] / l] } else { a.tangent }; + let f = Foot { way: self.way_of[k as usize], k: k as usize, t, d, across: -cross(u, sub(q, pa)) }; + match best.iter_mut().find(|b| b.way == f.way) { + Some(b) if f.d < b.d => *b = f, + Some(_) => {} + None => best.push(f), + } + } + best.sort_by_key(|f| f.way); + best + } + + /// The surface of the way at its foot: its curve's height there plus the bank times the metres across. + fn surface(&self, f: &Foot, q: [f64; 2]) -> f64 { + let (a, b) = (&self.g.samples[f.k], &self.g.samples[f.k + 1]); + let lerp = |x: f64, y: f64| x + f.t * (y - x); + lerp(a.z_m, b.z_m) + lerp(a.bank, b.bank) * f.across * self.mpu(q) + } + + fn foot_half(&self, f: &Foot) -> f64 { + let (a, b) = (&self.g.samples[f.k], &self.g.samples[f.k + 1]); + self.half(f.way, a.widen_m + f.t * (b.widen_m - a.widen_m)) + } + + fn terrain(&self, q: [f64; 2]) -> f64 { + let p = GlobalPoint { x: libm::round(q[0]) as i64, y: libm::round(q[1]) as i64 }; + self.input.terrain.height(p).unwrap_or(f64::NEG_INFINITY) + } + + /// Whether way o meets way w at one of w's ends: it goes on from w, it does not lie over it. + fn joined(&self, w: u32, o: u32) -> bool { + [true, false].iter().any(|&start| self.others(w, start).is_some_and(|x| x.iter().any(|a| a.0 == o))) + } + + /// Storey 0 at q without way `not` and the ways that go on from its ends: the terrain and the bodies + /// of the ground ways near q (their surface less their `fill` times the metres past the paved + /// stroke). And the highest paved stroke that covers q, less the at-grade band of it and `not` (the + /// lower of their `snap_height_m`, as at a crossing); None where none covers q. + fn ground(&self, q: [f64; 2], not: u32) -> (f64, Option) { + let mpu = self.mpu(q); + let (mut z, mut paved) = (self.terrain(q), None::); + for f in self.feet(q, HALF_MAX_M + BODY_M) { + if f.way == not || self.g.ways[f.way as usize].level != Level::Ground || self.joined(not, f.way) { + continue; + } + let Rule::Way(s, _) = self.rule(f.way) else { continue }; + let past = f.d * mpu - self.foot_half(&f); + if past <= s.reach_m { + let surface = self.surface(&f, q); + if past <= 0.0 { + let top = surface - s.snap_height_m.min(self.snap_m(not)); + paved = Some(paved.map_or(top, |p| p.max(top))); + } + z = z.max(surface - s.fill * past.max(0.0)); + } + } + (z, paved) + } + + /// Whether q lies over the body of way `g`: its paved stroke and, for a ground way, its bank down + /// to the terrain. + fn in_body(&self, g: u32, q: [f64; 2]) -> bool { + let Some(f) = self.feet(q, HALF_MAX_M + BODY_M).into_iter().find(|f| f.way == g) else { return false }; + let past = f.d * self.mpu(q) - self.foot_half(&f); + match self.rule(g) { + _ if past <= 0.0 => true, + Rule::Way(s, _) if self.g.ways[g as usize].level == Level::Ground && s.fill > 0.0 => { + past <= ((self.surface(&f, q) - self.terrain(q)) / s.fill).clamp(0.0, s.reach_m) + } + _ => false, + } + } + + /// The bore test at a point of a tunnel way: `c` less what it needs (the least room, or that less + /// `lift_max_m` on free ground, where no paved stroke lies: a paved face never moves). `c` is the + /// least of storey 0 over the bore's width less the floor. + fn bore(&self, w: u32, a: &At) -> f64 { + let Rule::Way(s, _) = self.rule(w) else { return f64::NEG_INFINITY }; + let half = (s.half_m + a.widen) / self.mpu(a.p); + let n = [-a.tangent[1], a.tangent[0]]; + let (mut c, mut free) = (f64::INFINITY, true); + for side in [-1.0, 0.0, 1.0] { + let q = add(a.p, n, side * half); + let (z, paved) = self.ground(q, w); + let across = -cross(a.tangent, sub(q, a.p)) * self.mpu(a.p); + c = c.min(z - (a.z + a.bank * across)); + free &= paved.is_none(); + } + let least = s.bore_least_m + s.roof_least_m; + c - if free { least - self.s.lift_max_m } else { least } + } + + /// The state of a tunnel station by its own test: BORE where the bore fits; else OPEN within + /// `open_max_m` of a tag end, wherever its floor lies against the terrain (the way goes on as a ground + /// way, on its bank where the floor lies over the terrain, until the cover holds), unless a way lies on + /// top: a paved stroke over the floor by more than the at-grade band; else HIDDEN. + fn tunnel_state(&self, w: u32, a: &At, tag_m: f64) -> State { + let on_top = || self.ground(a.p, w).1.is_some_and(|top| top > a.z); + if self.bore(w, a) >= 0.0 { + State::Bore + } else if tag_m > self.s.open_max_m || on_top() { + State::Hidden + } else { + State::Open + } + } + + /// Metres from an end of way w on through the ways that `same` accepts to the first end where + /// none goes on: 0 there; infinite where the graph does not hold the point or past `limit`. + fn onward(&self, w: u32, start: bool, limit: f64, same: &dyn Fn(u32) -> bool, depth: u32) -> f64 { + let Some(others) = self.others(w, start) else { return f64::INFINITY }; + let mut best = f64::INFINITY; + let mut any = false; + for &(o, o_start) in others.iter().filter(|(o, _)| same(*o)) { + any = true; + let len = self.lengths[o as usize]; + let rest = if len >= limit || depth >= 8 { + f64::INFINITY + } else { + self.onward(o, !o_start, limit - len, same, depth + 1) + }; + best = best.min(len + rest); + } + if any { + best + } else { + 0.0 + } + } + + /// The metres to the tag end behind and ahead of a way of the same kind, read up to `limit`. + fn tag_ends(&self, w: u32, limit: f64) -> (f64, f64) { + let same: &dyn Fn(u32) -> bool = if self.tunnel(w) { &|o| self.tunnel(o) } else { &|o| self.deck_tagged(o) }; + (self.onward(w, true, limit, same, 0), self.onward(w, false, limit, same, 0)) + } + + /// How far the deck stroke at metres m stands clear of the paved strokes of the arms, metres. + fn clear(&self, w: u32, m: f64, arms: &[u32]) -> f64 { + let a = self.at(w, m); + let mpu = self.mpu(a.p); + let h = (self.half(w, a.widen) + self.s.edge_band_m) / mpu; + let n = [-a.tangent[1], a.tangent[0]]; + let (p1, p2) = (add(a.p, n, h), add(a.p, n, -h)); + let mut best = f64::INFINITY; + for f in self.feet(a.p, h * mpu + HALF_MAX_M).into_iter().filter(|f| arms.contains(&f.way)) { + // The way's segments near its foot: its stroke can come nearer the line than the foot. + let r = &self.g.ways[f.way as usize].samples; + for k in f.k.saturating_sub(8).max(r.start as usize)..(f.k + 9).min(r.end as usize - 1) { + let (sa, sb) = (&self.g.samples[k], &self.g.samples[k + 1]); + let d = segs_dist(p1, p2, self.global(sa), self.global(sb)) * mpu; + best = best.min(d - self.half(f.way, sa.widen_m.max(sb.widen_m))); + } + } + best + } +} + +/// The levels of a graph: the ladders of its crossings, then the states and end lines of its ways. +pub fn levels(g: &mut WayGraph, input: &CellInput, sections: &Sections, s: &Structures) { + let (ladders, levels) = { + let mut ctx = Ctx::new(g, input, sections, s); + let ladders: Vec> = g.crossings.iter().map(|c| ladder(&ctx, c)).collect(); + ctx.grid = grid(&ctx, &ladders); + let levels = states(&ctx, &ladders); + (ladders, levels) + }; + for (c, l) in g.crossings.iter_mut().zip(ladders) { + c.ladder = l; + } + g.levels = levels; +} + +/// The sample segments of every way near a way that gets a state, in buckets: the reads of the +/// states reach no farther than `GRID_M` from such a way. +fn grid(ctx: &Ctx, ladders: &[Option]) -> Vec<([i64; 2], u32)> { + let g = ctx.g; + let ended = ladders.iter().flatten().filter_map(|l| l.ends); + let mut boxes: Vec<[f64; 4]> = Vec::new(); + for w in (0..g.ways.len() as u32).filter(|&w| ctx.tagged(w)).chain(ended) { + let pts: Vec<[f64; 2]> = ctx.samples(w).iter().map(|s| ctx.global(s)).collect(); + let grow = GRID_M / ctx.mpu(pts[0]); + let lo = |i: usize| pts.iter().map(|p| p[i]).fold(f64::INFINITY, f64::min) - grow; + let hi = |i: usize| pts.iter().map(|p| p[i]).fold(f64::NEG_INFINITY, f64::max) + grow; + boxes.push([lo(0), lo(1), hi(0), hi(1)]); + } + let mut grid = Vec::new(); + for w in g.ways.iter().filter(|_| !boxes.is_empty()) { + for k in w.samples.start..w.samples.end.saturating_sub(1) { + let (a, b) = (ctx.global(&g.samples[k as usize]), ctx.global(&g.samples[k as usize + 1])); + let near = |x: &[f64; 4]| { + a[0].max(b[0]) >= x[0] && a[0].min(b[0]) <= x[2] && a[1].max(b[1]) >= x[1] && a[1].min(b[1]) <= x[3] + }; + if !boxes.iter().any(near) { + continue; + } + let lo = |i: usize| (a[i].min(b[i]) / ctx.size).floor() as i64; + let hi = |i: usize| (a[i].max(b[i]) / ctx.size).floor() as i64; + for y in lo(1)..=hi(1) { + for x in lo(0)..=hi(0) { + grid.push(([x, y], k)); + } + } + } + } + grid.sort_unstable(); + grid +} + +/// The way of a crossing's station. +fn way_of(g: &WayGraph, st: &Station) -> Option { + let inside = |w: &&Way| w.part == st.part && key(&w.from) <= key(st) && key(st) <= key(&w.to); + g.ways.iter().find(inside).map(|w| w.id) +} + +/// The deck depth of a bridge way (`WayGraph::deck_depth`). +fn deck_depth(ctx: &Ctx, w: u32) -> f64 { + let Rule::Way(s, _) = ctx.rule(w) else { return 0.0 }; + ctx.g.deck_depth(ctx.input, w, s) +} + +fn ladder(ctx: &Ctx, c: &super::Crossing) -> Option { + let g = ctx.g; + let (upper, lower) = (way_of(g, &c.over)?, way_of(g, &c.under)?); + let water = ctx.water(lower); + let rated = match c.kind { + CrossingKind::Bore | CrossingKind::Stacked => !ctx.water(upper) && !water, + CrossingKind::Deck | CrossingKind::Footbridge => !ctx.water(upper), + CrossingKind::LevelCrossing => true, + _ => false, + }; + if !rated { + return None; + } + // The corners of the overlap of the two paved strokes, each on its way's own curve: along the upper + // way by the lower one's half-width over the sine, across it by its own; and the same for the lower. + let (au, al) = (ctx.at_station(c.over), ctx.at_station(c.under)); + let cs = cross(au.tangent, al.tangent); + let sin = cs.abs().max(1e-9); + let (hu, hl) = (ctx.half(upper, au.widen), ctx.half(lower, al.widen)); + let (lu, ll) = ((hl / sin).min(PLACE_M), (hu / sin).min(PLACE_M)); + let mut r = f64::INFINITY; + for (a, b) in [(0.0, 0.0), (1.0, 1.0), (1.0, -1.0), (-1.0, 1.0), (-1.0, -1.0)] { + let (pu, pl) = (ctx.along(&c.over, a * lu), ctx.along(&c.under, b * ll)); + let zu = pu.z + pu.bank * (-b * ll * cs); + let zl = pl.z + pl.bank * (a * lu * cs); + r = r.min(zu - zl); + } + let Rule::Way(su, _) = ctx.rule(upper) else { return None }; + let (full, least) = match ctx.rule(lower) { + Rule::Water(w) => (w.clearance_m + deck_depth(ctx, upper), w.clearance_least_m + su.deck_least_m), + Rule::Way(sl, _) if ctx.tunnel(lower) => (sl.bore_m + ctx.s.cover_m, sl.bore_least_m + sl.roof_least_m), + Rule::Way(sl, _) => (sl.clearance_m + deck_depth(ctx, upper), sl.clearance_least_m + su.deck_least_m), + }; + let snap = if water { su.snap_height_m } else { su.snap_height_m.min(ctx.snap_m(lower)) }; + let step = if c.kind == CrossingKind::LevelCrossing { Step::AtGrade } else { step(r, full, least, snap) }; + let ends = match step { + Step::Closed | Step::Inverted if !water => Some(ends(ctx, c, upper, lower)), + _ => None, + }; + Some(Ladder { upper, lower, room_m: r, full_m: full, least_m: least, step, ends }) +} + +/// The way that ends on step 3: a tunnel way; else the later row of `roads.json`; a tie, the lower +/// way; with no tag and one height, the way whose tile span comes later. +fn ends(ctx: &Ctx, c: &super::Crossing, upper: u32, lower: u32) -> u32 { + let (tu, tl) = (ctx.tunnel(upper), ctx.tunnel(lower)); + if tu != tl { + return if tu { upper } else { lower }; + } + let (cu, cl) = (ctx.g.ways[upper as usize].class, ctx.g.ways[lower as usize].class); + if cu != cl { + return if cu > cl { upper } else { lower }; + } + if ctx.tagged(upper) || ctx.tagged(lower) || ctx.at_station(c.over).z != ctx.at_station(c.under).z { + return lower; + } + let owner = |st: &Station| ctx.g.parts[st.part as usize].spans[st.span as usize].owner; + if owner(&c.over) > owner(&c.under) { + upper + } else { + lower + } +} + +/// A DECK way's A lines (metres along) at its tag ends and the metres between them, read on through +/// deck joints up to `deck_min_m`; None where an A lies past `A_MAX_M`. +type DeckEnds = ([Option; 2], f64); + +fn deck_ends(ctx: &Ctx, w: u32, ground: &[bool]) -> Option { + let len = ctx.lengths[w as usize]; + let deck = |o: u32| ctx.deck_tagged(o) && !ground[o as usize]; + let mut a = [None, None]; + for (i, start) in [(0, true), (1, false)] { + let Some(others) = ctx.others(w, start) else { continue }; + if others.iter().any(|(o, _)| deck(*o)) { + continue; + } + let arms: Vec = others.iter().map(|(o, _)| *o).filter(|&o| !ctx.water(o)).collect(); + a[i] = Some(place_a(ctx, w, start, &arms, len)?); + } + let mut between_m = a[1].unwrap_or(len) - a[0].unwrap_or(0.0); + for (i, start) in [(0, true), (1, false)] { + if a[i].is_none() { + between_m += ctx.onward(w, start, ctx.s.deck_min_m, &deck, 0).min(ctx.s.deck_min_m); + } + } + Some((a, between_m)) +} + +/// The first `m` in [lo, hi] where `ok` turns true, to `PLACE_TO_M`; `ok(lo)` is false, `ok(hi)` true. +fn bisect(mut lo: f64, mut hi: f64, ok: &dyn Fn(f64) -> bool) -> f64 { + while hi - lo > PLACE_TO_M { + let mid = (lo + hi) / 2.0; + if ok(mid) { + hi = mid; + } else { + lo = mid; + } + } + hi +} + +/// An A line: from the tag end inward to the first sample where the deck stroke is clear of every +/// ground arm, then back in steps of `A_STEP_M` and bisected; None past `A_MAX_M`. +fn place_a(ctx: &Ctx, w: u32, start: bool, arms: &[u32], len: f64) -> Option { + let at = |d: f64| if start { d } else { len - d }; + let ok = |d: f64| ctx.clear(w, at(d), arms) > 0.0; + if ok(0.0) { + return Some(at(0.0)); + } + let from = ctx.g.ways[w as usize].from; + let mut ds: Vec = ctx.samples(w).iter().map(|s| between(&ctx.g.parts, &from, &ctx.station(w, s))).collect(); + if !start { + ds = ds.iter().rev().map(|m| len - m).collect(); + } + let hit = ds.iter().copied().filter(|&d| d > 0.0 && d <= A_MAX_M).find(|&d| ok(d))?; + let mut d = ds.iter().copied().filter(|&x| x < hit).fold(0.0, f64::max); + loop { + let next = (d + A_STEP_M).min(hit); + if ok(next) { + return Some(at(bisect(d, next, &ok))); + } + d = next; + } +} + +/// Per way with a state: its samples' metres along, states and tag-end metres, and its A lines. +struct Track { + way: u32, + m: Vec, + state: Vec, + tag: (f64, f64), + a: [Option; 2], +} + +impl Track { + fn tag_m(&self, len: f64, m: f64) -> f64 { + (self.tag.0 + m).min(self.tag.1 + len - m) + } +} + +fn states(ctx: &Ctx, ladders: &[Option]) -> Levels { + let g = ctx.g; + // The step-3 crossings by the way that ends: (crossing, the way that stays). + let mut ended: Vec> = vec![Vec::new(); g.ways.len()]; + let mut culvert = vec![false; g.ways.len()]; + for (i, l) in ladders.iter().enumerate() { + let Some(l) = l.as_ref().filter(|l| matches!(l.step, Step::Closed | Step::Inverted)) else { continue }; + match l.ends { + Some(e) => ended[e as usize].push((i, if e == l.upper { l.lower } else { l.upper })), + None => culvert[l.upper as usize] = true, + } + } + let ways: Vec = (0..g.ways.len() as u32).filter(|&w| ctx.tagged(w) || !ended[w as usize].is_empty()).collect(); + // Deck ways that are ground: over a culvert, or with no room for a deck between their A lines. A + // deck way that turns ground changes the A lines of the deck ways at its ends only. + let mut ground: Vec = (0..g.ways.len() as u32).map(|w| !ctx.deck_tagged(w) || culvert[w as usize]).collect(); + let mut deck_of: Vec> = vec![None; g.ways.len()]; + let mut dirty: Vec = ways.iter().copied().filter(|&w| !ground[w as usize]).collect(); + for _ in 0..4 { + let mut turned = Vec::new(); + for &w in &dirty { + let ends = deck_ends(ctx, w, &ground); + if ends.is_none_or(|e| e.1 < ctx.s.deck_min_m) { + ground[w as usize] = true; + turned.push(w); + } + deck_of[w as usize] = ends; + } + let next = turned.iter().flat_map(|&w| [(w, true), (w, false)]).flat_map(|(w, s)| ctx.others(w, s)).flatten(); + dirty = next.map(|&(o, _)| o).filter(|&o| !ground[o as usize]).collect(); + dirty.sort_unstable(); + dirty.dedup(); + if dirty.is_empty() { + break; + } + } + let mut out = Levels::default(); + for &w in &ways { + let samples = ctx.samples(w); + let from = g.ways[w as usize].from; + let m: Vec = samples.iter().map(|s| between(&g.parts, &from, &ctx.station(w, s))).collect(); + let mut t = Track { way: w, state: vec![State::Open; m.len()], tag: (0.0, 0.0), a: [None, None], m }; + if ctx.tunnel(w) { + t.tag = ctx.tag_ends(w, ctx.s.open_max_m); + for (i, s) in samples.iter().enumerate() { + t.state[i] = + ctx.tunnel_state(w, &ctx.at_station(ctx.station(w, s)), t.tag_m(ctx.lengths[w as usize], t.m[i])); + } + let raw = t.state.clone(); + for i in 0..t.state.len() { + t.state[i] = open_rule(&t, &raw, ctx.lengths[w as usize], i); + } + } else if !ground[w as usize] { + let (a, _) = deck_of[w as usize].expect("each DECK way has its ends"); + let (lo, hi) = (a[0].unwrap_or(0.0), a[1].unwrap_or(ctx.lengths[w as usize])); + for (s, &m) in t.state.iter_mut().zip(&t.m) { + if m >= lo && m <= hi { + *s = State::Deck; + } + } + t.a = a; + } + // Step 3: not drawn over the body of the way that stays; the rest of the way keeps its state. + for &(i, stay) in &ended[w as usize] { + let c = &g.crossings[i]; + let st = if way_of(g, &c.over) == Some(w) { c.over } else { c.under }; + let k0 = t.m.partition_point(|&x| x < between(&g.parts, &from, &st)); + let over = |k: usize| ctx.in_body(stay, ctx.global(&samples[k])); + for k in (k0..samples.len()).take_while(|&k| over(k)) { + t.state[k] = State::Hidden; + } + for k in (0..k0).rev().take_while(|&k| over(k)) { + t.state[k] = State::Hidden; + } + } + runs(ctx, &t, &ended[w as usize], &mut out); + } + merge_a(ctx, &mut out); + out +} + +/// The A lines of one deck group that cross or lie within `edge_band_m` of each other move in together: each A +/// moves in along its way to where its centre line meets the line normal to their mean direction into the decks +/// through the farthest one in, and its ground stretch grows to it; its end line stays square to its own way, so on +/// two ways at an angle the end lines can still cross or leave a wedge. One pass: a moved A is not merged again. A +/// cell merges the A lines that it sees. +fn merge_a(ctx: &Ctx, out: &mut Levels) { + let g = ctx.g; + let mut group = vec![u32::MAX; g.ways.len()]; + for (k, d) in g.decks.iter().enumerate() { + for &w in &d.ways { + group[w as usize] = k as u32; + } + } + let gl = |p: [i32; 2]| [ctx.origin[0] + f64::from(p[0]), ctx.origin[1] + f64::from(p[1])]; + let deck_run = |runs: &[Run], l: &EndLine| { + runs.iter().position(|r| r.way == l.way && r.state == State::Deck && (r.from == l.at || r.to == l.at)) + }; + // The A lines at a deck run, and whether the deck lies ahead of the line along the way. + let lines: Vec<(usize, bool)> = (out.end_lines.iter().enumerate()) + .filter(|(_, l)| l.kind == EndKind::A && group[l.way as usize] != u32::MAX) + .filter_map(|(i, l)| deck_run(&out.runs, l).map(|r| (i, out.runs[r].from == l.at))) + .collect(); + let n = lines.len(); + let mut root: Vec = (0..n).collect(); + fn find(root: &mut [usize], mut i: usize) -> usize { + while root[i] != i { + root[i] = root[root[i]]; + i = root[i]; + } + i + } + for i in 0..n { + for j in i + 1..n { + let (a, b) = (&out.end_lines[lines[i].0], &out.end_lines[lines[j].0]); + if a.way == b.way || group[a.way as usize] != group[b.way as usize] { + continue; + } + let d = segs_dist(gl(a.ends[0]), gl(a.ends[1]), gl(b.ends[0]), gl(b.ends[1])) * ctx.mpu(gl(a.ends[0])); + if d <= ctx.s.edge_band_m { + let (x, y) = (find(&mut root, i), find(&mut root, j)); + root[x.max(y)] = x.min(y); + } + } + } + let mut members: Vec> = vec![Vec::new(); n]; + for i in 0..n { + members[find(&mut root, i)].push(i); + } + for m in members.into_iter().filter(|m| m.len() > 1) { + // Each line's point and the unit direction into its deck. + let into: Vec<([f64; 2], [f64; 2])> = (m.iter()) + .map(|&i| { + let (l, ahead) = lines[i]; + let a = ctx.at_station(out.end_lines[l].at); + let s = if ahead { 1.0 } else { -1.0 }; + (a.p, [s * a.tangent[0], s * a.tangent[1]]) + }) + .collect(); + let mean = into.iter().fold([0.0, 0.0], |s, d| add(s, d.1, 1.0)); + let len = dot(mean, mean).sqrt(); + if len < 1e-9 { + continue; + } + let mean = [mean[0] / len, mean[1] / len]; + let far = into.iter().map(|d| dot(d.0, mean)).fold(f64::NEG_INFINITY, f64::max); + for (k, &i) in m.iter().enumerate() { + let (l, ahead) = lines[i]; + let Some(r) = deck_run(&out.runs, &out.end_lines[l]) else { continue }; + let (p, d) = into[k]; + let gap = (far - dot(p, mean)) / dot(d, mean).max(1e-6); + if gap * ctx.mpu(p) < PLACE_TO_M { + continue; + } + let w = out.end_lines[l].way; + let from = g.ways[w as usize].from; + let at = between(&g.parts, &from, &out.end_lines[l].at); + let moved = if ahead { at + gap * ctx.mpu(p) } else { at - gap * ctx.mpu(p) }; + let deck = (out.runs[r].from, out.runs[r].to); + let (m0, m1) = (between(&g.parts, &from, &deck.0), between(&g.parts, &from, &deck.1)); + // The deck keeps its end lines in order and some length. + if moved <= m0.min(m1) + PLACE_TO_M || moved >= m0.max(m1) - PLACE_TO_M { + continue; + } + let st = ctx.at(w, moved).st; + let old = out.end_lines[l].at; + let ground = Run { way: w, from: old, to: old, state: State::Open }; + if ahead { + out.runs[r].from = st; + match out.runs.iter().position(|x| x.way == w && x.to == old && x.state == State::Open) { + Some(o) => out.runs[o].to = st, + None => out.runs.insert(r, Run { to: st, ..ground }), + } + } else { + out.runs[r].to = st; + match out.runs.iter().position(|x| x.way == w && x.from == old && x.state == State::Open) { + Some(o) => out.runs[o].from = st, + None => out.runs.insert(r + 1, Run { from: st, ..ground }), + } + } + out.end_lines[l] = line_at(ctx, w, st, EndKind::A, State::Deck); + } + } +} + +/// OPEN only between a tag end and the first BORE from that end: the read stays within `open_max_m`. +fn open_rule(t: &Track, raw: &[State], len: f64, i: usize) -> State { + if raw[i] != State::Open { + return raw[i]; + } + let back = t.tag.0 + t.m[i] <= t.tag.1 + len - t.m[i]; + let between = if back { &raw[..i] } else { &raw[i + 1..] }; + if between.contains(&State::Bore) { + State::Hidden + } else { + State::Open + } +} + +/// The runs and end lines of a track: a change between two samples lies where the state that tells +/// the two sides apart begins, bisected; an A lies where `deck_ends` put it. +fn runs(ctx: &Ctx, t: &Track, ended: &[(usize, u32)], out: &mut Levels) { + let g = ctx.g; + let w = t.way; + let len = ctx.lengths[w as usize]; + let tunnel = ctx.tunnel(w); + let stays: Vec = ended.iter().map(|&(_, s)| s).collect(); + let state_at = |m: f64| -> State { + let a = ctx.at(w, m); + if stays.iter().any(|&s| ctx.in_body(s, a.p)) { + State::Hidden + } else if tunnel { + // The OPEN rule at m: no BORE sample between m and its nearer tag end. + let s = ctx.tunnel_state(w, &a, t.tag_m(len, m)); + let back = t.tag.0 + m <= t.tag.1 + len - m; + let bore = t.m.iter().zip(&t.state).any(|(&x, &st)| st == State::Bore && if back { x < m } else { x > m }); + if s == State::Open && bore { + State::Hidden + } else { + s + } + } else { + State::Open + } + }; + let mut from = g.ways[w as usize].from; + let mut first = 0; + for i in 1..=t.state.len() { + if i < t.state.len() && t.state[i] == t.state[i - 1] { + continue; + } + let state = t.state[first]; + let to = if i == t.state.len() { + g.ways[w as usize].to + } else { + let (m0, m1, next) = (t.m[i - 1], t.m[i], t.state[i]); + let a_at = t.a.iter().flatten().copied().find(|&x| x > m0 && x <= m1); + let deck_change = matches!((state, next), (State::Open, State::Deck) | (State::Deck, State::Open)); + let m = match a_at { + Some(x) if deck_change => x, + _ => { + let tell = if state == State::Bore || next == State::Bore { + State::Bore + } else if state == State::Deck || next == State::Deck { + State::Deck + } else { + State::Hidden + }; + let member = |s: State| if tell == State::Deck { s != State::Hidden } else { s == tell }; + let side = member(state); + bisect(m0, m1, &|m| member(state_at(m)) != side) + } + }; + let kind = kind_between(state, next); + let st = ctx.at(w, m).st; + out.end_lines.push(line_at(ctx, w, st, kind, state.min(next))); + st + }; + out.runs.push(Run { way: w, from, to, state }); + from = to; + first = i; + } + // A change at a tag end: the way's end state against the ground way beyond it. + for (start, k) in [(true, 0), (false, t.state.len() - 1)] { + let state = t.state[k]; + let Some(others) = ctx.others(w, start) else { continue }; + let same = |o: u32| if tunnel { ctx.tunnel(o) } else { ctx.deck_tagged(o) }; + if state == State::Open || others.iter().any(|(o, _)| same(*o)) { + continue; + } + let end_m = if start { 0.0 } else { len }; + if state == State::Deck && !t.a[usize::from(!start)].is_some_and(|x| (x - end_m).abs() < 1e-9) { + continue; + } + let kind = match state { + State::Deck => EndKind::A, + State::Bore => EndKind::Portal, + _ => EndKind::Closed, + }; + let st = if start { g.ways[w as usize].from } else { g.ways[w as usize].to }; + out.end_lines.push(line_at(ctx, w, st, kind, state)); + } +} + +/// The end line of one way at a station: across the stroke of the structure side. +fn line_at(ctx: &Ctx, w: u32, st: Station, kind: EndKind, structure: State) -> EndLine { + end_line(ctx.g, ctx.input, ctx.sections, ctx.s.edge_band_m, (w, st, kind, structure)) +} + +/// G7: the runs of a bridge or tunnel way cover it once, in order; OPEN lies within `open_max_m` of a +/// tag end and never between two BORE runs. G8: each BORE sample has its room; a DECK way has +/// `deck_min_m` between its end lines. G9: an A line lies outside the paved stroke of every ground arm. +pub fn check_levels(g: &WayGraph, input: &CellInput, sections: &Sections, s: &Structures) -> Vec { + let ctx = { + let mut c = Ctx::new(g, input, sections, s); + let ladders: Vec> = g.crossings.iter().map(|x| x.ladder.clone()).collect(); + c.grid = grid(&c, &ladders); + c + }; + let mut faults = Vec::new(); + let mut fault = |check: &'static str, what: String| faults.push(Fault { check, what }); + let tolerance = 1e-6; + let k = |st: &Station| (st.span, st.u); + for way in &g.ways { + let w = way.id; + let runs: Vec<&Run> = g.levels.runs.iter().filter(|r| r.way == w).collect(); + if !ctx.tagged(w) && runs.is_empty() { + continue; + } + let joined = runs.windows(2).all(|p| p[0].to == p[1].from); + let ordered = runs.iter().all(|r| k(&r.from) <= k(&r.to)); + if runs.first().map(|r| r.from) != Some(way.from) + || runs.last().map(|r| r.to) != Some(way.to) + || !joined + || !ordered + { + fault("G7", format!("way {w}: its runs do not cover it once in order")); + } + let len = ctx.lengths[w as usize]; + let tunnel = ctx.tunnel(w); + let (back, ahead) = ctx.tag_ends(w, s.open_max_m.max(s.deck_min_m)); + let inside = |r: &Run, st: &Station| k(&r.from) <= k(st) && k(st) <= k(&r.to); + for r in &runs { + let wrong = match r.state { + State::Deck => tunnel, + State::Bore => !tunnel, + State::Open => { + let tag = |st: &Station| { + let m = between(&g.parts, &way.from, st); + (back + m).min(ahead + len - m) + }; + tunnel && tag(&r.from).min(tag(&r.to)) > s.open_max_m + PLACE_TO_M + } + State::Hidden => false, + }; + if wrong { + fault("G7", format!("way {w}: a {:?} run at {:?}", r.state, r.from)); + } + } + let bores: Vec = (0..runs.len()).filter(|&i| runs[i].state == State::Bore).collect(); + if let (Some(&a), Some(&b)) = (bores.first(), bores.last()) { + if runs[a..b].iter().any(|r| r.state == State::Open) { + fault("G7", format!("way {w}: an OPEN run between two BORE runs")); + } + } + for smp in ctx.samples(w) { + let st = ctx.station(w, smp); + if runs.iter().any(|r| r.state == State::Bore && inside(r, &st)) + && ctx.bore(w, &ctx.at_station(st)) < -tolerance + { + fault("G8", format!("way {w}: a BORE station at {st:?} lacks room")); + } + } + let deck: f64 = runs.iter().filter(|r| r.state == State::Deck).map(|r| between(&g.parts, &r.from, &r.to)).sum(); + if deck > 0.0 { + let on = |start: bool| { + let reaches = runs + .iter() + .any(|r| r.state == State::Deck && if start { r.from == way.from } else { r.to == way.to }); + if reaches { + ctx.onward(w, start, s.deck_min_m, &|o| ctx.deck_tagged(o), 0).min(s.deck_min_m) + } else { + 0.0 + } + }; + if deck + on(true) + on(false) < s.deck_min_m - tolerance { + fault("G8", format!("way {w}: a deck of {deck} m between its end lines")); + } + } + } + for line in g.levels.end_lines.iter().filter(|l| l.kind == EndKind::A) { + let w = line.way; + let m = between(&g.parts, &g.ways[w as usize].from, &line.at); + let start = m <= ctx.lengths[w as usize] / 2.0; + let arms: Vec = ctx + .others(w, start) + .into_iter() + .flatten() + .map(|(o, _)| *o) + .filter(|&o| !ctx.water(o) && !ctx.deck_tagged(o)) + .collect(); + if ctx.clear(w, m, &arms) < -PLACE_TO_M { + fault("G9", format!("way {w}: an A line at {:?} lies inside a ground arm", line.at)); + } + } + faults +} diff --git a/host/obc-ground-plan/src/graph/mod.rs b/host/obc-ground-plan/src/graph/mod.rs new file mode 100644 index 0000000000..66b5bbeaaf --- /dev/null +++ b/host/obc-ground-plan/src/graph/mod.rs @@ -0,0 +1,734 @@ +//! The way graph of one cell: every way and waterway as its curve with samples at global parameters, +//! split at the cell lines; the junctions with their hosts, the joints and the ends; snapped ends and +//! their links; a level per way piece; and every crossing with its type. `levels` adds the step of the +//! ladder of each crossing and the states and end lines of the bridge and tunnel ways; the bake runs it, and +//! with the storeys a cell splits its ways at the end lines that the tiles carry (`level_tags::split`). +//! +//! Every decision reads only data within its reach of the element it decides (the rows of +//! `reach_rows`), so two cells give the same graph where both hold complete data. + +mod crossings; +mod curve; +pub mod level_tags; +mod levels; +mod parts; +mod points; +mod snap; +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; + +use crate::frame::{metres_per_unit, CellKey, CELL_UNITS, FRAME_BITS, MARGIN_M}; +use crate::sections::{leading_number, Reach, Sections, WaySection}; +use crate::CellInput; + +pub use crossings::end_on_chord; +pub(crate) use curve::{folds, water_spans, water_tangents}; +pub use curve::{point, s_at, u_at, water_curves, water_grades, water_level, SpanPoint, WaterCurve}; +pub use levels::{check_levels, levels, step, EndKind, EndLine, Ladder, Levels, Run, State, Step, Structures}; + +/// The coarsest sample step: the grid of level l is `BASE_STEP_M / 2^l` along a span. +pub const BASE_STEP_M: f64 = 16.0; +/// The finest step, level 7; a grid point closer than half of it to a break goes. +pub const MIN_STEP_M: f64 = 0.125; +const LEVELS: u32 = 7; +/// Arc knots per span: `s(u)` is linear between them. +pub const KNOTS: usize = 16; +/// An arm's heading points at the curve this far along: the bake's `LOOK_M`. +pub const HEADING_M: f64 = 8.0; +/// GP3's longest read along an arm: a return ramp of 4.5 m at the road grade 0.15. +pub const ROOM_MAX_M: f64 = 30.0; +/// A snap reads this far: `HALF_MAX_M` 15 m, `snap_m` and 4 m of widening. +pub const SNAP_REACH_M: f64 = 20.0; +/// The half-length of a synthetic deck: a deck over water up to 76 m wide at 90°. +pub const DECK_HALF_MAX_M: f64 = 40.0; +/// An unshared vertex where the chords turn by more than this is a spike. +pub const SPIKE_DEG: f64 = 175.0; +/// A joint whose tangents differ by less than this runs on in one stroke. +pub const STROKE_DEG: f64 = 0.5; +/// A synthetic deck reaches this far past the outer edge of what lies under it. +pub const DECK_SIDE_M: f64 = 1.0; +/// A synthetic deck over water also spans this much bank on each side. +pub const WATER_BANK_M: f64 = 1.0; +/// Bisection steps of a cell-line root: 2^-44 of a span after the 16 knots. +pub const ROOT_STEPS: u32 = 40; +/// The side of a bucket of the crossing and snap grid. +const BUCKET_M: f64 = 16.0; +/// A crossing's stations lie where the two curves cross nearest the chords' crossing, within this. +const PLACE_M: f64 = 16.0; +/// Newton steps of a snap's foot on the curve, after the projection on the samples. +const NEWTON_STEPS: u32 = 4; +/// `side` bits of a vertex: the way out back along the part, and on. +pub const SIDE_BACK: u8 = 1; +pub const SIDE_ON: u8 = 2; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Family { + Road, + Path, + Rail, + Water, +} + +/// The families that join at a shared vertex. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Network { + Way, + Rail, + Water, +} + +impl Family { + pub fn network(self) -> Network { + match self { + Family::Road | Family::Path => Network::Way, + Family::Rail => Network::Rail, + Family::Water => Network::Water, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Level { + Ground, + Deck, + Tunnel, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum LinkKind { + EndToEnd, + Carriageway, +} + +/// The index of a feature in the cell's input; a link has the feature of its end. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct FeatureRef(pub u32); + +/// A place on a part's curve: a vertex v is (v, 0), the last vertex (n − 2, 1). +#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] +pub struct Station { + pub part: u32, + pub span: u32, + pub u: f64, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Vertex { + pub pos: [i64; 2], + /// Water in a tunnel with no level has 0 here: no height. + pub z_m: f64, + /// Radians from +x to +y. + pub tangent: f64, + pub grade: f64, + pub bank: f64, + pub widen_m: f64, + pub walk: u8, + pub side: u8, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Span { + pub len_m: f64, + /// Span metres at u = k / 16. + pub knots: [f64; KNOTS + 1], + /// The stroke metres at the start vertex in the tile that owns the span. + pub along0_m: f64, + /// The span is its chord with linear heights: no alignment, or a folded span. + pub chord: bool, + /// The tangent angles at its start and its end: its vertices', or for water `water_spans`'s. + pub ends: [f64; 2], + /// The length of the end tangents as a share of the chord: 1, or less where a water curve would + /// leave its chord too far. + pub handle: f64, + /// The heights are the level of water along the arc between the vertices (`water_level`). + pub water_z: bool, + /// The zoom-13 tile (column, row) that owns the span, and the feature's position in that tile. + pub owner: [u32; 3], +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub feature: FeatureRef, + pub family: Family, + /// The rank: the row of `roads.json`, or of `waterways.json` for water. + pub class: u8, + /// The level of the feature. A way of the part can lie on another: read `Way::level`. + pub level: Level, + pub backward: bool, + pub vertices: Vec, + pub spans: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum SampleKind { + Vertex, + CellLine, + Grid, + Station, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Sample { + /// Frame units from the cell's origin. + pub pos: [i32; 2], + pub span: u32, + pub u: f64, + pub s_m: f64, + pub along_m: f64, + pub z_m: f64, + pub tangent: [f64; 2], + pub grade: f64, + pub bank: f64, + pub widen_m: f64, + pub walk: u8, + pub kind: SampleKind, +} + +/// A piece of a part with one level: its curve is the part's spans from `from` to `to`. Its `level` +/// is the one to read: a synthetic deck is a `Deck` way of a `Ground` part. +#[derive(Clone, Debug, PartialEq)] +pub struct Way { + pub id: u32, + pub part: u32, + pub from: Station, + pub to: Station, + pub family: Family, + pub class: u8, + pub level: Level, + pub deck: Option, + pub link: Option, + pub samples: Range, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum PointRef { + Junction(u32), + Joint(u32), + End(u32), +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Arm { + pub way: u32, + pub at: Station, + /// +1 along the part, −1 back. + pub dir: i8, + pub heading: [f64; 2], + /// `atan2` of the heading: x east, y south. + pub angle: f64, + pub host: bool, + pub level: Level, + pub room_m: f64, + pub next: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum HostRule { + Side, + Fallback, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Junction { + pub pos: [i32; 2], + pub network: Network, + /// Sorted by angle, then by the heading point, then by `dir`. + pub arms: Vec, + pub host_rule: HostRule, + /// Two ways that cross at one height with no shared vertex. + pub implicit: bool, + pub owned: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Joint { + pub pos: [i32; 2], + pub network: Network, + pub arms: [Arm; 2], + /// π less the angle between the headings: 0 straight on. + pub turn_rad: f64, + pub stroke: bool, + pub owned: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct End { + pub pos: [i32; 2], + pub network: Network, + pub arm: Arm, + pub owned: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum CrossingKind { + Deck, + Culvert, + Ford, + PipeInStones, + SteppingStones, + Footbridge, + LevelCrossing, + Stacked, + /// A tunnel way under another way, from their tags. + Bore, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Source { + Tag, + SharedVertex, + Rule, + Fallback, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Crossing { + pub pos: [i32; 2], + pub over: Station, + pub under: Station, + pub kind: CrossingKind, + pub source: Source, + /// From 0 to π/2. + pub angle_rad: f64, + pub deck: Option, + pub owned: bool, + /// The room and the step of the ladder, where one applies. + pub ladder: Option, +} + +/// Deck ways that share a point, or one synthetic stretch. +#[derive(Clone, Debug, PartialEq)] +pub struct Deck { + pub ways: Vec, + pub synthetic: bool, +} + +/// What each stage removed, kept apart or decided. Counts over the work area. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GraphStats { + pub repeated: u32, + pub spikes: u32, + pub folded: u32, + pub no_height: u32, + /// Water spans under the terrain by more than their `underground_m`. + pub underground: u32, + pub shared_runs: u32, + pub end_on_other: u32, + pub water_water: u32, + pub grazing: u32, + pub grazing_water: u32, + pub buried: u32, + pub deck_fallback: u32, + pub deck_cut: u32, + pub links_end: u32, + pub links_carriageway: u32, + pub link_crossed: u32, + pub snap_far: u32, + pub ends: u32, + pub junctions: u32, + pub joints: u32, + pub implicit_junctions: u32, + pub crossings: BTreeMap<(CrossingKind, Source), u32>, + pub samples: u32, +} + +impl GraphStats { + /// Every counter but the crossings by type, by name. + pub fn counters(&self) -> [(&'static str, u32); 23] { + [ + ("repeated", self.repeated), + ("spikes", self.spikes), + ("folded", self.folded), + ("no_height", self.no_height), + ("underground", self.underground), + ("shared_runs", self.shared_runs), + ("end_on_other", self.end_on_other), + ("water_water", self.water_water), + ("grazing", self.grazing), + ("grazing_water", self.grazing_water), + ("buried", self.buried), + ("deck_fallback", self.deck_fallback), + ("deck_cut", self.deck_cut), + ("links_end", self.links_end), + ("links_carriageway", self.links_carriageway), + ("link_crossed", self.link_crossed), + ("snap_far", self.snap_far), + ("ends", self.ends), + ("junctions", self.junctions), + ("joints", self.joints), + ("implicit_junctions", self.implicit_junctions), + ("crossings", self.crossings.values().sum()), + ("samples", self.samples), + ] + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct WayGraph { + pub cell: CellKey, + pub parts: Vec, + pub ways: Vec, + pub samples: Vec, + pub junctions: Vec, + pub joints: Vec, + pub ends: Vec, + pub crossings: Vec, + pub decks: Vec, + /// Empty from `build`: `levels` fills it. + pub levels: Levels, + pub stats: GraphStats, +} + +/// A sample of a walk along a way: its place (cell units) and its way. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WalkPoint { + pub pos: [i32; 2], + pub way: u32, +} + +impl WayGraph { + /// The way whose curve holds a station on the level `level`. + pub fn way_at(&self, st: &Station, level: Level) -> Option { + let key = |s: &Station| (s.span, s.u); + (self.ways.iter()) + .find(|w| w.part == st.part && w.level == level && key(&w.from) <= key(st) && key(st) <= key(&w.to)) + .map(|w| w.id) + } + + /// The sample of a way nearest a point: a crossing's point is a sample of both ways. + pub fn sample_near(&self, way: u32, pos: [i32; 2]) -> u32 { + let r = &self.ways[way as usize].samples; + let d = |k: &u32| { + let p = self.samples[*k as usize].pos; + i64::from(p[0] - pos[0]).pow(2) + i64::from(p[1] - pos[1]).pow(2) + }; + (r.start..r.end).min_by_key(d).unwrap_or(r.start) + } + + /// The walks along a way's network from sample `at` of way `way` in direction `dir` (+1 along its part) + /// for `max_m` metres, the last chord cut there: on through the joints, and with `branches` into each + /// other arm of a junction, a walk of its own after the first. Without, a walk stops at a junction. + /// Every walk starts at `at`. + pub fn walk(&self, way: u32, at: u32, dir: i8, max_m: f64, branches: bool) -> Vec> { + let mpu = |a: [i32; 2], b: [i32; 2]| metres_per_unit(self.cell.origin().y + i64::from(a[1] + b[1]) / 2); + let point = |k: u32| WalkPoint { pos: self.samples[k as usize].pos, way: self.way_of_sample(k) }; + let mut out = Vec::new(); + let network = self.ways[way as usize].family.network(); + let mut todo = vec![(way, at, dir, 0.0, vec![point(at)])]; + while let Some((mut w, mut k, mut d, mut m, mut list)) = todo.pop() { + loop { + let r = &self.ways[w as usize].samples; + let next = i64::from(k) + i64::from(d); + if (i64::from(r.start)..i64::from(r.end)).contains(&next) { + let (a, b) = (self.samples[k as usize].pos, self.samples[next as usize].pos); + let len = libm::hypot(f64::from(b[0] - a[0]), f64::from(b[1] - a[1])) * mpu(a, b); + if m + len >= max_m { + let f = if len > 0.0 { (max_m - m) / len } else { 0.0 }; + let pos = [ + a[0] + libm::round(f * f64::from(b[0] - a[0])) as i32, + a[1] + libm::round(f * f64::from(b[1] - a[1])) as i32, + ]; + list.push(WalkPoint { pos, ..point(next as u32) }); + break; + } + (k, m) = (next as u32, m + len); + list.push(point(k)); + continue; + } + // The way's end: the arms there leave it back along its part. + let end = |a: &Arm| a.way == w && a.dir == -d; + let arms: Vec<&Arm> = match self.joints.iter().find(|j| j.network == network && j.arms.iter().any(end)) + { + Some(j) => j.arms.iter().filter(|a| !end(a)).collect(), + None if branches => (self.junctions.iter()) + .find(|j| j.network == network && j.arms.iter().any(end)) + .map(|j| j.arms.iter().filter(|a| !end(a)).collect()) + .unwrap_or_default(), + None => Vec::new(), + }; + let Some((first, rest)) = arms.split_first() else { break }; + let start = |a: &Arm| { + let r = &self.ways[a.way as usize].samples; + (a.way, if a.dir > 0 { r.start } else { r.end - 1 }, a.dir) + }; + for a in rest { + let (w2, k2, d2) = start(a); + todo.push((w2, k2, d2, m, vec![point(k2)])); + } + (w, k, d) = start(first); + } + out.push(list); + } + out + } + + /// The way of sample k. + fn way_of_sample(&self, k: u32) -> u32 { + self.ways.partition_point(|w| w.samples.end <= k) as u32 + } + + /// The deck depth of bridge way w: its tile's `deck` tag where the way lies on the deck of its own + /// part, else the thinnest deck of its class (`section`). + pub fn deck_depth(&self, input: &CellInput, w: u32, section: &WaySection) -> f64 { + let way = &self.ways[w as usize]; + let part = &self.parts[way.part as usize]; + let tagged = way.level == Level::Deck && part.level == Level::Deck; + let tag = input.features[part.feature.0 as usize].tags.get("deck"); + tag.and_then(|t| leading_number(t)).filter(|_| tagged).unwrap_or(section.deck_least_m) + } +} + +/// A broken invariant of `check`. +#[derive(Clone, Debug, PartialEq)] +pub struct Fault { + pub check: &'static str, + pub what: String, +} + +/// The cell square grown by `MARGIN_M` at its edge nearer the pole: [x0, y0, x1, y1], closed. +pub fn work_area(cell: CellKey) -> [i64; 4] { + let o = cell.origin(); + let pole = if o.y < 1 << (FRAME_BITS - 1) { o.y } else { o.y + CELL_UNITS }; + let m = (MARGIN_M / metres_per_unit(pole)).floor() as i64; + [o.x - m, o.y - m, o.x + CELL_UNITS + m, o.y + CELL_UNITS + m] +} + +fn inside([x0, y0, x1, y1]: [i64; 4], p: [i64; 2]) -> bool { + (x0..=x1).contains(&p[0]) && (y0..=y1).contains(&p[1]) +} + +/// The graph of a cell from its input and the rule tables, in the order of the stages. +pub fn build(cell: CellKey, input: &CellInput, rules: &Sections) -> WayGraph { + build_with(cell, input, rules, None) +} + +/// `build`, with each way split at the end lines that the tiles carry, each stretch on the level of its state +/// (`level_tags::split`), and each junction with arms on the ground and on a deck on the ground +/// (`level_tags::ground_junctions`, with the decks' `edge_band_m`): the graph of the storeys. `levels` reads the graph +/// of `build`, as the bake does. +pub fn build_levelled(cell: CellKey, input: &CellInput, rules: &Sections, band_m: f64) -> WayGraph { + build_with(cell, input, rules, Some(band_m)) +} + +/// `levelled`: the graph of the storeys, with the decks' `edge_band_m`. +fn build_with(cell: CellKey, input: &CellInput, rules: &Sections, levelled: Option) -> WayGraph { + let area = work_area(cell); + let mut stats = GraphStats::default(); + let (mut parts, mut part_rules) = parts::parts(input, rules, &mut stats); + let (mut samples, sampled): (Vec>, Vec>) = + parts.iter().zip(&part_rules).map(|(part, rule)| curve::samples(part, rule, cell, area)).unzip(); + let plan = points::pieces(&parts, &sampled, input, &mut stats); + let plan = crossings::crossings(cell, area, &parts, &part_rules, &mut samples, plan, &mut stats); + let plan = snap::snap(cell, area, &mut parts, &mut part_rules, &mut samples, plan, &mut stats); + let plan = match levelled { + Some(band_m) => { + let plan = level_tags::split(cell, &parts, input, &mut samples, plan); + level_tags::ground_junctions(&parts, input, rules, band_m, &samples, plan) + } + None => plan, + }; + let mut g = points::assemble(cell, area, parts, &part_rules, samples, plan, stats); + open_culverts(&mut g, input, rules); + g +} + +/// The water of a short mapped culvert chain (tunnel water ways that meet end to end, up to its row's +/// `culvert_max_m` in all, as the classifier's, the bake's and develop's rule) under a way on the ground lies on the +/// ground, as the bake lays it: on one straight line over the chain between the levels of the open water at its two +/// ends, or at the one end's level. The faces hide it under a road or a railway only (`faces::culverts`), so the +/// stream runs up to the way's bank, and a path lies across it. A longer chain (a buried stream, `Source::Fallback`) +/// and one with no open water at an end stay in their tunnel. +fn open_culverts(g: &mut WayGraph, input: &CellInput, rules: &Sections) { + let on_ground = |w: u32| g.ways[w as usize].family != Family::Water; + let mut seeds: Vec = (g.crossings.iter()) + .filter(|c| c.kind == CrossingKind::Culvert && c.source != Source::Fallback) + .filter(|c| g.way_at(&c.over, Level::Ground).is_some_and(on_ground)) + .filter_map(|c| g.way_at(&c.under, Level::Tunnel)) + .filter(|&w| g.ways[w as usize].family == Family::Water) + .collect(); + seeds.sort_unstable(); + seeds.dedup(); + let mut done = BTreeSet::new(); + for w in seeds { + if done.contains(&w) { + continue; + } + let (chain, ends) = culvert_chain(g, w); + done.extend(chain.iter().map(|&(x, _)| x)); + let way = &g.ways[w as usize]; + let f = &input.features[g.parts[way.part as usize].feature.0 as usize]; + // Each way's samples in the chain's order, with the metres along the chain at each and the way's direction. + let mut at: Vec<(usize, f64, i8)> = Vec::new(); + let mut len = 0.0; + for &(x, d) in &chain { + let r = g.ways[x as usize].samples.clone(); + let mut k: Vec = (r.start as usize..r.end as usize).collect(); + if d < 0 { + k.reverse(); + } + let first = g.samples[k[0]].along_m; + at.extend(k.iter().map(|&i| (i, len + (g.samples[i].along_m - first).abs(), d))); + len = at.last().map_or(len, |a| a.1); + } + let (z0, z1) = match ends { + [Some(x), Some(y)] => (x, y), + [Some(z), None] | [None, Some(z)] => (z, z), + [None, None] => continue, + }; + if len > rules.water(&f.kind, &f.tags).culvert_max_m { + continue; + } + let len = if len > 1e-6 { len } else { 1.0 }; + for (i, s, d) in at { + g.samples[i].z_m = z0 + (s / len).clamp(0.0, 1.0) * (z1 - z0); + g.samples[i].grade = f64::from(d) * (z1 - z0) / len; + } + for &(x, _) in &chain { + g.ways[x as usize].level = Level::Ground; + } + let arms = (g.joints.iter_mut().flat_map(|j| j.arms.iter_mut())) + .chain(g.junctions.iter_mut().flat_map(|j| j.arms.iter_mut())) + .chain(g.ends.iter_mut().map(|e| &mut e.arm)); + for arm in arms.filter(|x| chain.iter().any(|c| c.0 == x.way)) { + arm.level = Level::Ground; + } + } +} + +/// The culvert chain through tunnel water way w: its tunnel water ways that meet end to end at joints, in order, +/// each with its direction (+1 along its part), and the level of the open water on the ground at each end, none +/// where the chain ends with none. +fn culvert_chain(g: &WayGraph, w: u32) -> (Vec<(u32, i8)>, [Option; 2]) { + let tunnel = |x: u32| g.ways[x as usize].family == Family::Water && g.ways[x as usize].level == Level::Tunnel; + // At the far end of way x walked in direction d: the next tunnel way and its direction, or the open level. + let next = |x: u32, d: i8| -> Result<(u32, i8), Option> { + let end = |a: &Arm| a.way == x && a.dir == -d; + let joint = g.joints.iter().find(|j| j.network == Network::Water && j.arms.iter().any(end)); + let Some(j) = joint else { return Err(None) }; + let other = j.arms.iter().find(|a| !end(a)).ok_or(None)?; + if tunnel(other.way) { + return Ok((other.way, other.dir)); + } + let open = g.ways[other.way as usize].level == Level::Ground; + Err(open.then(|| g.samples[g.sample_near(other.way, j.pos) as usize].z_m)) + }; + let (mut ahead, mut behind, mut ends) = (vec![(w, 1i8)], Vec::new(), [None, None]); + for (k, start) in [(1, 1i8), (0, -1)] { + let (mut x, mut d) = (w, start); + for _ in 0..64 { + match next(x, d) { + Ok((y, e)) if !ahead.iter().chain(&behind).any(|a: &(u32, i8)| a.0 == y) => { + (x, d) = (y, e); + if k == 1 { + ahead.push((y, e)); + } else { + behind.push((y, -e)); + } + } + Ok(_) => break, + Err(z) => { + ends[k] = z; + break; + } + } + } + } + behind.reverse(); + behind.extend(ahead); + (behind, ends) +} + +/// The rows of the graph in the reach table: (R_d, own R_e) of each decision. +pub fn reach_rows(culvert_max_m: f64) -> Vec { + let chain = |name: &str, terms: &[(&str, f64)]| Reach { + name: name.into(), + owner: "graph", + chain: true, + terms: terms.iter().map(|&(what, m)| (what.to_string(), m)).collect(), + }; + let snap_foot = SNAP_REACH_M + SNAP_REACH_M; + vec![ + chain("graph heading", &[("HEADING_M", HEADING_M)]), + chain("graph room", &[("ROOM_MAX_M", ROOM_MAX_M), ("a snap foot there", snap_foot)]), + chain("graph snap", &[("SNAP_REACH_M", SNAP_REACH_M), ("its link", SNAP_REACH_M)]), + chain( + "graph crossing", + &[("HALF_MAX_M", crate::sections::HALF_MAX_M), ("PLACE_M", PLACE_M), ("HEADING_M", HEADING_M)], + ), + chain("graph synthetic deck", &[("DECK_HALF_MAX_M", DECK_HALF_MAX_M), ("its stretch", DECK_HALF_MAX_M)]), + chain("graph culvert chain", &[("culvert_max_m", culvert_max_m)]), + chain("graph shared run", &[("one shared span", 0.0), ("HEADING_M at its ends", HEADING_M)]), + chain("graph spike", &[("a vertex in the grown cell and its two spans", 0.0)]), + ] +} + +/// The invariants G1 to G4 of a graph. +pub fn check(graph: &WayGraph) -> Vec { + let mut faults = Vec::new(); + let mut fault = |check: &'static str, what: String| faults.push(Fault { check, what }); + for way in &graph.ways { + let samples = &graph.samples[way.samples.start as usize..way.samples.end as usize]; + for pair in samples.windows(2) { + if (pair[0].span, pair[0].u) >= (pair[1].span, pair[1].u) { + fault("G1", format!("way {}: samples out of order at span {} u {}", way.id, pair[1].span, pair[1].u)); + } + if pair[0].pos == pair[1].pos { + fault("G1", format!("way {}: two samples at {:?}", way.id, pair[0].pos)); + } + } + if samples.len() < 2 { + fault("G1", format!("way {}: {} samples", way.id, samples.len())); + } + for s in samples { + let values = [s.u, s.s_m, s.along_m, s.z_m, s.tangent[0], s.tangent[1], s.grade, s.bank, s.widen_m]; + if values.iter().any(|v| !v.is_finite()) { + fault("G1", format!("way {}: a value that is not finite at {:?}", way.id, s.pos)); + } + } + } + for j in &graph.junctions { + let hosts = j.arms.iter().filter(|a| a.host).count(); + let group = j.arms.iter().all(|a| graph.ways[a.way as usize].family.network() == j.network); + if j.arms.len() < 3 || !group || !(1..=2).contains(&hosts) { + fault("G2", format!("junction at {:?}: {} arms, {hosts} hosts, one group {group}", j.pos, j.arms.len())); + } + if j.arms.windows(2).any(|a| a[0].angle > a[1].angle) { + fault("G2", format!("junction at {:?}: arms not sorted", j.pos)); + } + } + let area = work_area(graph.cell); + let o = graph.cell.origin(); + let global = |p: [i32; 2]| [o.x + i64::from(p[0]), o.y + i64::from(p[1])]; + // The arms at the ends of ways: (way, direction, station). + let mut arms: BTreeSet<(u32, i8, u32, u64)> = BTreeSet::new(); + let mut at = |arm: &Arm| { + arms.insert((arm.way, arm.dir, arm.at.span, arm.at.u.to_bits())); + }; + graph.junctions.iter().flat_map(|j| &j.arms).for_each(&mut at); + graph.joints.iter().flat_map(|j| &j.arms).for_each(&mut at); + graph.ends.iter().map(|e| &e.arm).for_each(&mut at); + for way in &graph.ways { + let first = &graph.samples[way.samples.start as usize]; + let last = &graph.samples[way.samples.end as usize - 1]; + for (sample, dir, st) in [(first, 1, way.from), (last, -1, way.to)] { + if inside(area, global(sample.pos)) && !arms.contains(&(way.id, dir, st.span, st.u.to_bits())) { + fault("G3", format!("way {}: its end at {:?} is no arm of a point", way.id, sample.pos)); + } + } + if graph.decks.iter().any(|d| d.synthetic && d.ways.contains(&way.id)) { + let inner = + |s: &Station| (s.span, s.u) > (way.from.span, way.from.u) && (s.span, s.u) < (way.to.span, way.to.u); + let holds = (graph.junctions.iter().flat_map(|j| &j.arms)) + .chain(graph.joints.iter().flat_map(|j| &j.arms)) + .chain(graph.ends.iter().map(|e| &e.arm)) + .any(|a| a.way == way.id && inner(&a.at)); + if holds { + fault("G4", format!("synthetic deck way {} holds a point", way.id)); + } + } + } + faults +} diff --git a/host/obc-ground-plan/src/graph/parts.rs b/host/obc-ground-plan/src/graph/parts.rs new file mode 100644 index 0000000000..808ebb0b60 --- /dev/null +++ b/host/obc-ground-plan/src/graph/parts.rs @@ -0,0 +1,557 @@ +//! Stage 1: the parts of a cell. The owned runs of the read tiles join across tile lines, then each +//! part gets its family, class and level, its cleaning, and splits where its heights are unknown or its +//! water lies underground. + +use std::collections::BTreeMap; + +use super::curve::level_at; +use super::{ + folds, water_grades, water_spans, water_tangents, Family, FeatureRef, GraphStats, Level, Part, Span, Vertex, + SPIKE_DEG, +}; +use crate::frame::{metres_per_unit, GlobalPoint}; +use crate::sections::{is_track, Sections, WaterSection, WaySection, WATER_KINDS}; +use crate::tile::{self, Feature, Geometry}; +use crate::CellInput; + +const WAYS: [&str; 6] = ["main-road", "road", "path", "railway", "tunnel", "gallery"]; +/// The classes of the kind `path`. +const PATH_CLASSES: [&str; 7] = ["path", "footway", "cycleway", "bridleway", "steps", "pedestrian", "via_ferrata"]; +/// Spans kept past each span that may meet the work area: the cleaning of a vertex reads its two spans. +const TRIM_SPANS: usize = 2; +/// The step of `underground`'s test points along a span, metres. +const UNDERGROUND_STEP_M: f64 = 2.0; + +/// The rules of a part: the cross-section of its class and whether it fords, or of its water kind. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum Rule<'a> { + Way(WaySection<'a>, bool), + Water(WaterSection), +} + +impl<'a> Rule<'a> { + pub fn way(&self) -> &WaySection<'a> { + match self { + Rule::Way(s, _) => s, + Rule::Water(_) => panic!("a way's rule of water"), + } + } + + pub fn water(&self) -> &WaterSection { + match self { + Rule::Water(w) => w, + Rule::Way(..) => panic!("a water's rule of a way"), + } + } + + pub fn half_m(&self) -> f64 { + match self { + Rule::Way(s, _) => s.half_m, + Rule::Water(w) => w.half_m, + } + } + + pub fn outer_m(&self) -> f64 { + match self { + Rule::Way(s, _) => s.outer_m(), + Rule::Water(w) => w.half_m, + } + } + + /// A way tagged `ford`, or a `low_water_crossing`. + pub fn ford(&self) -> bool { + matches!(self, Rule::Way(_, true)) + } +} + +/// Whether a way of `family` at a ford or at a vertex it shares with open water crosses that water as a ford: a path +/// always, another way only over water wider than `culvert_width_m`. As the bake lays it, a road, a track or a +/// railway otherwise takes the rule of an untagged crossing. +pub(crate) fn fords(family: Family, water: &WaterSection) -> bool { + family == Family::Path || water.width_m > water.culvert_width_m +} + +/// The family, rank, level and rules of a line feature, or None for another kind. +pub(crate) fn classify<'a>(feature: &Feature, sections: &'a Sections) -> Option<(Family, u8, Level, Rule<'a>)> { + let tag = |key: &str| feature.tags.get(key).map(String::as_str); + let kind = feature.kind.as_str(); + if feature.geometry != Geometry::Line { + return None; + } + if WATER_KINDS.contains(&kind) { + let w = sections.water(kind, &feature.tags); + let level = if tag("tunnel").is_some_and(|t| t != "no") { Level::Tunnel } else { Level::Ground }; + return Some((Family::Water, w.rank as u8, level, Rule::Water(w))); + } + if !WAYS.contains(&kind) { + return None; + } + let s = sections.way(kind, &feature.tags, false); + let family = if is_track(&feature.tags) { + Family::Rail + } else if PATH_CLASSES.contains(&s.class) { + Family::Path + } else { + Family::Road + }; + // Tiles of an older bake hold a passage through a building as a tunnel: it is a way, the building stands over it. + let level = if kind == "tunnel" && tag("tunnel") != Some("building_passage") { + Level::Tunnel + } else if tag("deck").is_some() { + Level::Deck + } else { + Level::Ground + }; + let ford = tag("ford").is_some_and(|f| f != "no") || tag("bridge") == Some("low_water_crossing"); + Some((family, s.rank as u8, level, Rule::Way(s, ford))) +} + +/// A vertex before cleaning: its height can be unknown. +#[derive(Clone, Debug)] +struct Raw { + v: Vertex, + z: Option, + /// The spans at this vertex are chords: a spike, or a corner of water. + corner: bool, +} + +/// A water span's shape (`water_spans`): None for its chord, else its end tangents and handle. +type WaterShape = Option<([f64; 2], f64)>; + +/// A joined part before cleaning: its vertices, per span the stroke metres at its start, whether it +/// has no alignment, its owner and its water shape, and the tile's two vertices before and after it with +/// their heights, in the chain's order, where the tile holds them; the tiles of its first and its last run. +struct Chain { + feature: usize, + backward: bool, + tiles: [(u32, u32); 2], + vertices: Vec, + spans: Vec<(f64, bool, [u32; 3], WaterShape)>, + before: Vec<([i64; 2], Option)>, + after: Vec<([i64; 2], Option)>, +} + +/// The vertices of a tile part in the graph's form; a part with no alignment takes its chords. +fn tile_vertices(part: &tile::Part) -> Vec { + let n = part.points.len(); + (0..n) + .map(|i| { + let pos = [part.points[i].x, part.points[i].y]; + let z = part.heights.as_ref().and_then(|h| h[i]); + let v = match &part.plan { + Some(p) => Vertex { + pos, + z_m: 0.0, + tangent: p.tangent[i], + grade: p.grade[i], + bank: p.bank[i], + widen_m: p.widen[i], + walk: p.walk[i], + side: p.side[i], + }, + None => { + let (a, b) = if i + 1 < n { (i, i + 1) } else { (i - 1, i) }; + let (pa, pb) = (part.points[a], part.points[b]); + let tangent = libm::atan2((pb.y - pa.y) as f64, (pb.x - pa.x) as f64); + Vertex { pos, z_m: 0.0, tangent, grade: 0.0, bank: 0.0, widen_m: 0.0, walk: 0, side: 0 } + } + }; + Raw { v, z, corner: false } + }) + .collect() +} + +/// The stroke metres at each vertex of a tile part: from its `along_m`, or from 0 with no alignment. +fn tile_along(part: &tile::Part, vertices: &[Raw]) -> Vec { + let (start, sign) = match &part.plan { + Some(p) => (p.along_m, if p.backward { -1.0 } else { 1.0 }), + None => (0.0, 1.0), + }; + let chord = part.plan.is_none(); + let mut along = vec![start]; + for pair in vertices.windows(2) { + let len = super::curve::length(&pair[0].v, &pair[1].v, chord); + along.push(along.last().unwrap() + sign * len); + } + along +} + +/// An owned run: vertices `from..=to` of part `part` of feature `feature`. +#[derive(Clone, Copy)] +struct Run { + feature: usize, + part: usize, + from: usize, + to: usize, +} + +fn runs(input: &CellInput, line: &[bool]) -> Vec { + let mut out = Vec::new(); + for (f, feature) in input.features.iter().enumerate().filter(|(f, _)| line[*f]) { + for (p, part) in feature.parts.iter().enumerate() { + let mut start = None; + for i in 0..=part.own.len() { + match (start, part.own.get(i).copied().unwrap_or(false)) { + (None, true) => start = Some(i), + (Some(s), false) => { + out.push(Run { feature: f, part: p, from: s, to: i }); + start = None; + } + _ => {} + } + } + } + } + out +} + +fn key(p: GlobalPoint) -> [i64; 2] { + [p.x, p.y] +} + +/// Join the owned runs: a run whose part goes on with an unowned segment takes the run of another +/// tile, of a feature of the same kind and tags, that starts with that segment. +fn chains(input: &CellInput, line: &[bool]) -> Vec { + let runs = runs(input, line); + let part = |r: &Run| &input.features[r.feature].parts[r.part]; + let mut starts: BTreeMap<[[i64; 2]; 2], Vec> = BTreeMap::new(); + for (i, r) in runs.iter().enumerate() { + let points = &part(r).points; + starts.entry([key(points[r.from]), key(points[r.from + 1])]).or_default().push(i); + } + let mut next = vec![None; runs.len()]; + let mut taken = vec![false; runs.len()]; + for (i, r) in runs.iter().enumerate() { + let points = &part(r).points; + if r.to + 1 >= points.len() { + continue; + } + let f = &input.features[r.feature]; + let candidates = starts.get(&[key(points[r.to]), key(points[r.to + 1])]).into_iter().flatten(); + let found = candidates.copied().find(|&j| { + let (g, other) = (&input.features[runs[j].feature], part(&runs[j])); + !taken[j] && other.tile != part(r).tile && g.kind == f.kind && g.tags == f.tags + }); + if let Some(j) = found { + next[i] = Some(j); + taken[j] = true; + } + } + let mut seen = vec![false; runs.len()]; + let mut out = Vec::new(); + let order: Vec = (0..runs.len()).filter(|&i| !taken[i]).chain(0..runs.len()).collect(); + for first in order { + if seen[first] { + continue; + } + let r0 = runs[first]; + let past = |p: &tile::Part, i: usize| (key(p.points[i]), p.heights.as_ref().and_then(|h| h[i])); + let before = (r0.from.saturating_sub(2)..r0.from).map(|i| past(part(&r0), i)).collect(); + let mut chain = Chain { + feature: r0.feature, + backward: false, + tiles: [part(&r0).tile; 2], + vertices: Vec::new(), + spans: Vec::new(), + before, + after: Vec::new(), + }; + let mut at = Some(first); + while let Some(i) = at.filter(|&i| !seen[i]) { + seen[i] = true; + let r = runs[i]; + let p = part(&r); + chain.backward = p.plan.as_ref().is_some_and(|plan| plan.backward); + chain.tiles[1] = p.tile; + let vertices = tile_vertices(p); + let along = tile_along(p, &vertices); + let skip = usize::from(!chain.vertices.is_empty()); + chain.vertices.extend(vertices[r.from + skip..=r.to].iter().cloned()); + let owner = [p.tile.0, p.tile.1, input.features[r.feature].index]; + chain.spans.extend((r.from..r.to).map(|k| (along[k], p.plan.is_none(), owner, None))); + chain.after = (r.to + 1..(r.to + 3).min(p.points.len())).map(|i| past(p, i)).collect(); + at = next[i]; + } + out.push(chain); + } + out +} + +/// The stretches of a chain within `TRIM_SPANS` spans of a span that may meet the square: the box of +/// its chord grown by a third of the chord holds its curve. The rest decides nothing in the cell. +fn trim(chain: Chain, [x0, y0, x1, y1]: [i64; 4]) -> Vec { + let n = chain.spans.len(); + let near: Vec = (0..n) + .map(|k| { + let (a, b) = (chain.vertices[k].v.pos, chain.vertices[k + 1].v.pos); + let d = [(b[0] - a[0]) as f64, (b[1] - a[1]) as f64]; + let grow = ((d[0] * d[0] + d[1] * d[1]).sqrt() / 3.0).ceil() as i64 + 1; + a[0].max(b[0]) + grow >= x0 + && a[0].min(b[0]) - grow <= x1 + && a[1].max(b[1]) + grow >= y0 + && a[1].min(b[1]) - grow <= y1 + }) + .collect(); + let keep: Vec = + (0..n).map(|k| near[k.saturating_sub(TRIM_SPANS)..(k + TRIM_SPANS + 1).min(n)].iter().any(|&m| m)).collect(); + let mut out = Vec::new(); + let mut k = 0; + while k < n { + if !keep[k] { + k += 1; + continue; + } + let start = k; + while k < n && keep[k] { + k += 1; + } + let before: Vec<([i64; 2], Option)> = + chain.before.iter().copied().chain(chain.vertices[..start].iter().map(|r| (r.v.pos, r.z))).collect(); + out.push(Chain { + feature: chain.feature, + backward: chain.backward, + tiles: chain.tiles, + vertices: chain.vertices[start..=k].to_vec(), + spans: chain.spans[start..k].to_vec(), + before: before[before.len().saturating_sub(2)..].to_vec(), + after: chain.vertices[k + 1..] + .iter() + .map(|r| (r.v.pos, r.z)) + .chain(chain.after.iter().copied()) + .take(2) + .collect(), + }); + } + out +} + +/// The turn in degrees of the chords from a through b to c. +fn turn_deg(a: [i64; 2], b: [i64; 2], c: [i64; 2]) -> f64 { + let (u, v) = ([(b[0] - a[0]) as f64, (b[1] - a[1]) as f64], [(c[0] - b[0]) as f64, (c[1] - b[1]) as f64]); + libm::atan2((u[0] * v[1] - u[1] * v[0]).abs(), u[0] * v[0] + u[1] * v[1]).to_degrees() +} + +/// The neighbours of vertex i on its chain: the tile's vertices past the chain's ends included. +fn neighbours(chain: &Chain, i: usize) -> (Option<[i64; 2]>, Option<[i64; 2]>) { + let (n, here) = (chain.vertices.len(), chain.vertices[i].v.pos); + let prev = if i > 0 { Some(chain.vertices[i - 1].v.pos) } else { chain.before.last().map(|p| p.0) }; + let next = if i + 1 < n { Some(chain.vertices[i + 1].v.pos) } else { chain.after.first().map(|p| p.0) }; + (prev.filter(|&q| q != here), next.filter(|&q| q != here)) +} + +/// The tile's two vertices past an end of a water chain on the one other water line that ends there, in +/// the chain's order (`at_start`: before its first vertex, else after its last): where the map splits a +/// stream into two ways, the curve and the grades read on through the shared vertex. None where no other +/// line or more than one ends there (a confluence). Only the tile of the chain's end run counts, so every +/// cell decides alike. +fn through(input: &CellInput, water: &[bool], chain: &Chain, at_start: bool) -> Option)>> { + let n = chain.vertices.len(); + let tile = chain.tiles[usize::from(!at_start)]; + let (end, own) = if at_start { + (chain.vertices[0].v.pos, chain.vertices.get(1).map(|r| r.v.pos)) + } else { + (chain.vertices[n - 1].v.pos, n.checked_sub(2).map(|i| chain.vertices[i].v.pos)) + }; + let mut found: Vec)>> = Vec::new(); + let parts = (input.features.iter().enumerate()).filter(|(f, _)| water[*f]).flat_map(|(_, f)| &f.parts); + let parts = parts.filter(|p| p.tile == tile); + for part in parts { + let m = part.points.len(); + let at = |i: usize| (key(part.points[i]), part.heights.as_ref().and_then(|h| h[i])); + let away: Vec = if m >= 2 && key(part.points[0]) == end { + (1..m.min(3)).collect() + } else if m >= 2 && key(part.points[m - 1]) == end { + (m.saturating_sub(3)..m - 1).rev().collect() + } else { + continue; + }; + let next: Vec<_> = away.into_iter().map(at).collect(); + // A copy of the chain's own line, or a second copy of a line already found. + if Some(next[0].0) == own || found.iter().any(|f| f[0].0 == next[0].0) { + continue; + } + found.push(next); + } + let mut next = found.pop().filter(|_| found.is_empty())?; + if at_start { + next.reverse(); + } + Some(next) +} + +/// The tangents, corners, span shapes and grades of water (`water_tangents`, `water_spans`, +/// `water_grades`). A chain end that is no end of the way reads the tile's two vertices past it, so every +/// cell that samples a span gives it one curve and one profile: a span reads the spans beside it. +fn curve_water(chain: &mut Chain, turn_max_deg: f64, off_max_m: f64) { + let all: Vec<([i64; 2], Option)> = (chain.before.iter().copied()) + .chain(chain.vertices.iter().map(|r| (r.v.pos, r.z))) + .chain(chain.after.iter().copied()) + .collect(); + let points: Vec<[f64; 2]> = all.iter().map(|p| p.0.map(|c| c as f64)).collect(); + let skip = chain.before.len(); + let mut tangents = water_tangents(&points, turn_max_deg); + for (r, (tangent, corner)) in chain.vertices.iter_mut().zip(&mut tangents[skip..]) { + r.v.tangent = *tangent; + r.corner |= *corner; + *corner = r.corner; + } + let metres = |a: [f64; 2], b: [f64; 2]| metres_per_unit(((a[1] + b[1]) / 2.0).floor() as i64); + let shapes = water_spans(&points, &tangents, metres, off_max_m); + for (span, shape) in chain.spans.iter_mut().zip(&shapes[skip..]) { + span.3 = *shape; + } + let z: Vec> = all.iter().map(|p| p.1).collect(); + for (r, grade) in chain.vertices.iter_mut().zip(&water_grades(&points, &z, metres)[skip..]) { + r.v.grade = *grade; + } +} + +/// A span of water: its chord, or its curve with the end tangents and handle of `water_spans`. +fn water_span(a: &Vertex, b: &Vertex, along0_m: f64, owner: [u32; 3], shape: WaterShape) -> Span { + let span = match shape { + Some((ends, handle)) => Span::shaped(a, b, false, ends, handle, along0_m), + None => Span::new(a, b, true, along0_m), + }; + Span { water_z: true, owner, ..span } +} + +/// Whether water lies underground on a span: at a point of it in the cell's grown square, every +/// `UNDERGROUND_STEP_M` along it, its level lies more than `depth_m` under the terrain. The grown square +/// holds the finest terrain of every cell that reads the point, so every cell decides alike where a cell +/// draws the span. Such a span is no part: the water ends at its vertices. +fn underground(input: &CellInput, a: &Vertex, b: &Vertex, span: &Span, depth_m: f64) -> bool { + let [x0, y0, x1, y1] = input.key.grown(); + let n = (span.len_m / UNDERGROUND_STEP_M).ceil().max(1.0) as u32; + (0..=n).any(|k| { + let (p, z) = level_at(a, b, span, f64::from(k) / f64::from(n)); + let inside = (x0..=x1).contains(&p[0]) && (y0..=y1).contains(&p[1]); + inside && input.terrain.height(GlobalPoint { x: p[0], y: p[1] }).is_some_and(|t| t - z > depth_m) + }) +} + +/// Remove repeated vertices: the later one goes, its `side` joins the one that stays. +fn repeated(chain: &mut Chain, stats: &mut GraphStats) -> bool { + let mut changed = false; + let mut i = 1; + while i < chain.vertices.len() { + if chain.vertices[i].v.pos == chain.vertices[i - 1].v.pos { + let side = chain.vertices[i].v.side; + chain.vertices[i - 1].v.side |= side; + chain.vertices.remove(i); + // The zero-length span goes; the span after it starts at the vertex that stays. + chain.spans.remove(i - 1); + stats.repeated += 1; + changed = true; + } else { + i += 1; + } + } + changed +} + +/// The parts of a cell and their rules, ordered by their vertex positions. +pub(crate) fn parts<'a>( + input: &CellInput, + sections: &'a Sections, + stats: &mut GraphStats, +) -> (Vec, Vec>) { + let classes: Vec<_> = input.features.iter().map(|f| classify(f, sections)).collect(); + let line: Vec = classes.iter().map(Option::is_some).collect(); + let water: Vec = classes.iter().map(|c| matches!(c, Some((Family::Water, _, Level::Ground, _)))).collect(); + let mut chains = chains(input, &line); + for chain in &mut chains { + repeated(chain, stats); + if water[chain.feature] { + if chain.before.is_empty() { + chain.before = through(input, &water, chain, true).unwrap_or_default(); + } + if chain.after.is_empty() { + chain.after = through(input, &water, chain, false).unwrap_or_default(); + } + } + // A spike stays, and its two spans are chords: the test reads only the part. + for i in 0..chain.vertices.len() { + let (prev, next) = neighbours(chain, i); + let spike = prev.zip(next).is_some_and(|(a, c)| turn_deg(a, chain.vertices[i].v.pos, c) > SPIKE_DEG); + if spike { + chain.vertices[i].corner = true; + stats.spikes += 1; + } + } + if let Some((_, _, _, Rule::Water(w))) = classes[chain.feature] { + curve_water(chain, w.curve_turn_max_deg, w.curve_off_max_m); + } + } + let chains: Vec = chains.into_iter().flat_map(|c| trim(c, input.key.grown())).collect(); + let mut out: Vec<(Part, Rule<'a>)> = Vec::new(); + for chain in chains { + let (family, class, level, rule) = classes[chain.feature].expect("a chain of a line feature"); + let keep_unknown = family == Family::Water && level == Level::Tunnel; + let mut piece: Vec = Vec::new(); + let mut spans: Vec<(f64, bool, [u32; 3], WaterShape)> = Vec::new(); + let mut flush = |piece: &mut Vec, + spans: &mut Vec<(f64, bool, [u32; 3], WaterShape)>, + stats: &mut GraphStats| { + if piece.len() >= 2 { + // Water in a tunnel has no level: 0 marks it, it is no height. + let vertices: Vec = + piece.iter().map(|r| Vertex { z_m: r.z.unwrap_or(0.0), ..r.v.clone() }).collect(); + let corner: Vec = piece.iter().map(|r| r.corner).collect(); + let spans = vertices + .windows(2) + .zip(spans.iter()) + .enumerate() + .map(|(k, (pair, &(along0, chord, owner, shape)))| { + if let Rule::Water(_) = rule { + return water_span(&pair[0], &pair[1], along0, owner, shape); + } + let d = [(pair[1].pos[0] - pair[0].pos[0]) as f64, (pair[1].pos[1] - pair[0].pos[1]) as f64]; + let chord = corner[k] || corner[k + 1] || chord; + let folded = !chord && folds(d, pair[0].tangent, pair[1].tangent); + stats.folded += u32::from(folded); + Span { owner, ..Span::new(&pair[0], &pair[1], chord || folded, along0) } + }) + .collect(); + let part = Part { + feature: FeatureRef(chain.feature as u32), + family, + class, + level, + backward: chain.backward, + vertices, + spans, + }; + out.push((part, rule)); + } + piece.clear(); + spans.clear(); + }; + for (k, &span) in chain.spans.iter().enumerate() { + let (a, b) = (&chain.vertices[k], &chain.vertices[k + 1]); + let deep = match (rule, a.z.zip(b.z)) { + (Rule::Water(w), Some((za, zb))) if level == Level::Ground => { + let (va, vb) = (Vertex { z_m: za, ..a.v.clone() }, Vertex { z_m: zb, ..b.v.clone() }); + underground(input, &va, &vb, &water_span(&va, &vb, span.0, span.2, span.3), w.underground_m) + } + _ => false, + }; + stats.underground += u32::from(deep); + if keep_unknown || (a.z.is_some() && b.z.is_some() && !deep) { + if piece.is_empty() { + piece.push(a.clone()); + } + piece.push(b.clone()); + spans.push(span); + } else { + stats.no_height += 1; + flush(&mut piece, &mut spans, stats); + } + } + flush(&mut piece, &mut spans, stats); + } + out.sort_by(|(p, _), (q, _)| { + let (a, b) = (p.vertices.iter().map(|v| v.pos), q.vertices.iter().map(|v| v.pos)); + a.cmp(b).then((p.family, p.class).cmp(&(q.family, q.class))) + }); + out.into_iter().unzip() +} diff --git a/host/obc-ground-plan/src/graph/points.rs b/host/obc-ground-plan/src/graph/points.rs new file mode 100644 index 0000000000..a544d45ca5 --- /dev/null +++ b/host/obc-ground-plan/src/graph/points.rs @@ -0,0 +1,693 @@ +//! Shared runs, way pieces, and the points of a set of pieces: junctions with their hosts, joints +//! and ends at every position where pieces meet, and the final assembly of the graph. + +use std::cmp::Ordering; +use std::collections::BTreeMap; + +use core::f64::consts::PI; + +use super::curve::{geo_of, point}; +use super::parts::{fords, Rule}; +use super::{ + inside, Arm, Crossing, CrossingKind, Deck, End, Family, GraphStats, HostRule, Joint, Junction, Level, LinkKind, + Network, Part, PointRef, Sample, Source, Station, Way, WayGraph, HEADING_M, ROOM_MAX_M, SIDE_BACK, SIDE_ON, + STROKE_DEG, +}; +use crate::frame::CellKey; +use crate::sections::GRAZE_DEG; +use crate::CellInput; + +/// A stretch of one part with one level, before ids. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Piece { + pub part: usize, + pub from: Station, + pub to: Station, + pub level: Level, + pub link: Option, + pub synthetic: bool, +} + +/// A station on a piece that is a point of its own: an implicit junction or a snap foot. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Anchor { + pub pos: [i64; 2], + pub at: Station, + pub implicit: bool, +} + +/// What the stages hand on: the pieces, the anchors, the crossings without a shared vertex, and the +/// carriageway links (their foot ends are guests). +#[derive(Clone, Debug, Default)] +pub(crate) struct Plan { + pub pieces: Vec, + pub anchors: Vec, + pub crossings: Vec, +} + +/// The station of a vertex: (v, 0), or (n − 2, 1) for the last. +pub(crate) fn vertex_station(part: &Part, index: usize, v: usize) -> Station { + let n = part.spans.len(); + let (span, u) = if v < n { (v, 0.0) } else { (n - 1, 1.0) }; + Station { part: index as u32, span: span as u32, u } +} + +/// A station in its one form: the end of a span is the next span's u = 0, but at the last vertex. +pub(crate) fn norm(part: &Part, st: Station) -> Station { + if st.u >= 1.0 && (st.span as usize) + 1 < part.spans.len() { + Station { span: st.span + 1, u: 0.0, ..st } + } else { + st + } +} + +pub(crate) fn key(st: &Station) -> (u32, f64) { + (st.span, st.u) +} + +pub(crate) fn before(a: &Station, b: &Station) -> bool { + key(a) < key(b) +} + +/// Metres along a piece from its start to a station on it. +pub(crate) fn metres(parts: &[Part], piece: &Piece, st: &Station) -> f64 { + let part = &parts[piece.part]; + let s = |st: &Station| super::s_at(&part.spans[st.span as usize], st.u); + let whole: f64 = (piece.from.span..st.span).map(|k| part.spans[k as usize].len_m).sum(); + whole + s(st) - s(&piece.from) +} + +/// The station `delta` metres along a piece from a station on it, at most to the piece's ends. It +/// reads only the spans between, so every cell gives one station. +pub(crate) fn advance(parts: &[Part], piece: &Piece, st: &Station, delta: f64) -> Station { + let part = &parts[piece.part]; + let s_of = |st: &Station| super::s_at(&part.spans[st.span as usize], st.u); + let (mut span, mut s, mut left) = (st.span, s_of(st), delta.abs()); + loop { + let len = part.spans[span as usize].len_m; + if delta >= 0.0 { + if span == piece.to.span { + s = (s + left).min(s_of(&piece.to)); + break; + } + if s + left <= len { + s += left; + break; + } + left -= len - s; + (span, s) = (span + 1, 0.0); + } else { + if span == piece.from.span { + s = (s - left).max(s_of(&piece.from)); + break; + } + if s - left >= 0.0 { + s -= left; + break; + } + left -= s; + span -= 1; + s = part.spans[span as usize].len_m; + } + } + norm(part, Station { span, u: super::u_at(&part.spans[span as usize], s), ..*st }) +} + +/// The metres along a part between two stations on it, summed from the lower one. +pub(crate) fn between(parts: &[Part], a: &Station, b: &Station) -> f64 { + let (a, b) = if before(b, a) { (b, a) } else { (a, b) }; + let part = &parts[a.part as usize]; + let s = |st: &Station| super::s_at(&part.spans[st.span as usize], st.u); + if a.span == b.span { + return s(b) - s(a); + } + let mut sum = part.spans[a.span as usize].len_m - s(a); + for k in a.span + 1..b.span { + sum += part.spans[k as usize].len_m; + } + sum + s(b) +} + +/// The global position of a station, rounded as a sample is. +pub(crate) fn position(parts: &[Part], st: &Station) -> [i64; 2] { + let part = &parts[st.part as usize]; + let span = st.span as usize; + let g = geo_of(&part.vertices[span], &part.vertices[span + 1], &part.spans[span]); + super::curve::round(&g, g.eval(st.u)[0]) +} + +/// The global position of a station in frame units, unrounded. +pub(crate) fn exact(parts: &[Part], st: &Station) -> [f64; 2] { + let part = &parts[st.part as usize]; + let p = point(part, st.span as usize, st.u); + let p0 = part.vertices[st.span as usize].pos; + [p0[0] as f64 + p.d[0], p0[1] as f64 + p.d[1]] +} + +/// Pieces of every part: its runs of sampled spans that no shared run takes. +pub(crate) fn pieces(parts: &[Part], sampled: &[Vec], input: &CellInput, stats: &mut GraphStats) -> Plan { + let lost = shared_runs(parts, sampled, input, stats); + let mut plan = Plan::default(); + for (index, part) in parts.iter().enumerate() { + let mut start = None; + for span in 0..=part.spans.len() { + let keep = span < part.spans.len() && sampled[index][span] && !lost[index][span]; + match (start, keep) { + (None, true) => start = Some(span), + (Some(a), false) => { + plan.pieces.push(Piece { + part: index, + from: vertex_station(part, index, a), + to: vertex_station(part, index, span), + level: part.level, + link: None, + synthetic: false, + }); + start = None; + } + _ => {} + } + } + } + plan +} + +/// The order of the parts that hold one segment, read from that segment and the vertex past each of +/// its ends: class, kind, tags; the part's direction, the lower position first first; a chord last; +/// the data of its two vertices, the lower position first, as seen in that direction; then the +/// positions of the vertices past its lower and its higher end (none first). +struct SegmentOrder { + head: (u8, String, crate::tile::Tags, bool, bool), + data: Vec, + past: (Option<[i64; 2]>, Option<[i64; 2]>), +} + +impl SegmentOrder { + fn new(part: &Part, k: usize, input: &CellInput) -> SegmentOrder { + let (a, b) = (&part.vertices[k], &part.vertices[k + 1]); + let forward = a.pos <= b.pos; + let sign = if forward { 1.0 } else { -1.0 }; + let swap = |bits: u8| if forward { bits } else { (bits & 1) << 1 | (bits >> 1) & 1 }; + let turn = |t: f64| if forward { t } else { (t + PI).rem_euclid(core::f64::consts::TAU) }; + let (lo, hi) = if forward { (a, b) } else { (b, a) }; + let mut data = Vec::with_capacity(13); + for v in [lo, hi] { + data.extend([turn(v.tangent), v.z_m, sign * v.grade, sign * v.bank, v.widen_m, f64::from(swap(v.side))]); + } + data.push(f64::from(swap(a.walk))); + let at = |i: Option| i.and_then(|i| part.vertices.get(i)).map(|v| v.pos); + let (before, after) = (at(k.checked_sub(1)), at(Some(k + 2))); + let past = if forward { (before, after) } else { (after, before) }; + let f = &input.features[part.feature.0 as usize]; + SegmentOrder { head: (part.class, f.kind.clone(), f.tags.clone(), !forward, part.spans[k].chord), data, past } + } + + fn cmp(&self, other: &SegmentOrder) -> Ordering { + let data = || { + let pairs = self.data.iter().zip(&other.data); + pairs.map(|(u, v)| u.total_cmp(v)).find(|o| o.is_ne()).unwrap_or(Ordering::Equal) + }; + self.head.cmp(&other.head).then_with(data).then_with(|| self.past.cmp(&other.past)) + } +} + +/// Where parts of one network hold one segment, every part but the first in `SegmentOrder` loses +/// that span: the decision reads only the segment and its neighbours, so every cell that holds it +/// agrees. A run whose order changes along it hands over at a vertex, a joint. Of parts that tie +/// exactly, the one whose span has the lowest owner (tile, then position in it) keeps it. +fn shared_runs(parts: &[Part], sampled: &[Vec], input: &CellInput, stats: &mut GraphStats) -> Vec> { + let mut lost: Vec> = parts.iter().map(|p| vec![false; p.spans.len()]).collect(); + let mut segments: BTreeMap<[[i64; 2]; 2], Vec<(usize, usize)>> = BTreeMap::new(); + for (i, part) in parts.iter().enumerate() { + for k in (0..part.spans.len()).filter(|&k| sampled[i][k]) { + let (a, b) = (part.vertices[k].pos, part.vertices[k + 1].pos); + segments.entry([a.min(b), a.max(b)]).or_default().push((i, k)); + } + } + for holders in segments.values().filter(|h| h.len() > 1) { + let network = |&(i, _): &(usize, usize)| parts[i].family.network(); + for net in [Network::Way, Network::Rail, Network::Water] { + let mine: Vec<(usize, usize)> = holders.iter().copied().filter(|h| network(h) == net).collect(); + if mine.len() < 2 { + continue; + } + let orders: Vec = mine.iter().map(|&(i, k)| SegmentOrder::new(&parts[i], k, input)).collect(); + let owner = |n: usize| parts[mine[n].0].spans[mine[n].1].owner; + let best = + (0..mine.len()).min_by(|&x, &y| orders[x].cmp(&orders[y]).then(owner(x).cmp(&owner(y)))).unwrap(); + for (n, &(i, k)) in mine.iter().enumerate() { + lost[i][k] |= n != best; + } + } + } + for spans in &lost { + stats.shared_runs += + spans.windows(2).filter(|w| w[1] && !w[0]).count() as u32 + u32::from(spans.first() == Some(&true)); + } + lost +} + +/// An arm before ids: a piece, a station, the metres along the piece, a direction. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct RawArm { + pub piece: usize, + pub at: Station, + pub m: f64, + pub dir: i8, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum NodeKind { + Junction, + Joint, + End, +} + +/// A point of one group at one position. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Node { + pub pos: [i64; 2], + pub network: Network, + pub kind: NodeKind, + pub arms: Vec, + pub implicit: bool, +} + +/// A shared vertex of two networks with two or more arms each: the position, and each network with its arms. +pub(crate) type Shared = ([i64; 2], (Network, Vec), (Network, Vec)); + +/// The points of the pieces in the area, and the crossings at shared vertices. +pub(crate) struct Nodes { + pub nodes: Vec, + pub shared: Vec, + /// The pieces at each position where two or more occurrences meet. + pub meets: BTreeMap<[i64; 2], Vec>, +} + +pub(crate) fn nodes(parts: &[Part], plan: &Plan, area: [i64; 4], stats: Option<&mut GraphStats>) -> Nodes { + // (position, piece, station, an arm back, an arm on, implicit) of each occurrence. + let mut at: Vec<([i64; 2], usize, Station, bool, bool, bool)> = Vec::new(); + for (index, piece) in plan.pieces.iter().enumerate() { + let part = &parts[piece.part]; + let mut add = |pos: [i64; 2], st: Station, implicit: bool| { + at.push((pos, index, st, before(&piece.from, &st), before(&st, &piece.to), implicit)); + }; + add(position(parts, &piece.from), piece.from, false); + for v in piece.from.span as usize + 1..=piece.to.span as usize { + let st = vertex_station(part, piece.part, v); + if before(&st, &piece.to) { + add(part.vertices[v].pos, st, false); + } + } + add(position(parts, &piece.to), piece.to, false); + for a in plan.anchors.iter().filter(|a| a.at.part as usize == piece.part) { + if before(&piece.from, &a.at) && before(&a.at, &piece.to) { + add(a.pos, a.at, a.implicit); + } + } + } + // An anchor at a vertex is that vertex's occurrence. + at.sort_by(|a, b| (a.0, a.1, key(&a.2)).partial_cmp(&(b.0, b.1, key(&b.2))).unwrap()); + at.dedup_by(|b, a| { + let same = (a.0, a.1, key(&a.2)) == (b.0, b.1, key(&b.2)); + a.5 |= same && b.5; + same + }); + let mut out = Nodes { nodes: Vec::new(), shared: Vec::new(), meets: BTreeMap::new() }; + let mut end_on_other = 0; + for occurrences in at.chunk_by(|a, b| a.0 == b.0) { + let pos = occurrences[0].0; + if occurrences.len() < 2 && occurrences.iter().all(|o| o.3 && o.4) { + continue; + } + out.meets.insert(pos, occurrences.iter().map(|o| o.1).collect()); + if !inside(area, pos) { + continue; + } + let implicit = occurrences.iter().any(|o| o.5); + let mut groups: BTreeMap, usize)> = BTreeMap::new(); + for &(_, piece, st, back, on, _) in occurrences { + let entry = groups.entry(parts[plan.pieces[piece].part].family.network()).or_default(); + entry.1 += 1; + let m = metres(parts, &plan.pieces[piece], &st); + let dirs = [(back, -1), (on, 1)]; + entry.0.extend(dirs.iter().filter(|d| d.0).map(|&(_, dir)| RawArm { piece, at: st, m, dir })); + } + let wide: Vec = groups.iter().filter(|(_, (arms, _))| arms.len() >= 2).map(|(&g, _)| g).collect(); + for (i, &g) in wide.iter().enumerate() { + for &h in &wide[i + 1..] { + out.shared.push((pos, (g, groups[&g].0.clone()), (h, groups[&h].0.clone()))); + } + } + for (group, (arms, count)) in groups { + let kind = match arms.len() { + 0 => continue, + 1 => { + end_on_other += usize::from(!wide.is_empty()); + NodeKind::End + } + 2 if count == 1 => continue, + 2 => NodeKind::Joint, + _ => NodeKind::Junction, + }; + out.nodes.push(Node { pos, network: group, kind, arms, implicit }); + } + } + if let Some(stats) = stats { + stats.end_on_other += end_on_other as u32; + } + out +} + +/// The heading of an arm: the unit vector from the point to the curve `HEADING_M` along its piece, +/// and that curve point. +fn heading(parts: &[Part], piece: &Piece, arm: &RawArm, pos: [i64; 2]) -> ([f64; 2], [i64; 2]) { + let st = advance(parts, piece, &arm.at, f64::from(arm.dir) * HEADING_M); + let p = exact(parts, &st); + let v = [p[0] - pos[0] as f64, p[1] - pos[1] as f64]; + let length = (v[0] * v[0] + v[1] * v[1]).sqrt(); + if length > 0.0 { + return ([v[0] / length, v[1] / length], position(parts, &st)); + } + let t = point(&parts[arm.at.part as usize], arm.at.span as usize, arm.at.u).tangent; + let dir = f64::from(arm.dir); + ([dir * t[0], dir * t[1]], position(parts, &st)) +} + +/// The `side` bit of an arm at a vertex. +fn side_bit(parts: &[Part], arm: &RawArm) -> bool { + let part = &parts[arm.at.part as usize]; + let v = if arm.at.u == 0.0 { + arm.at.span as usize + } else if arm.at.u == 1.0 { + arm.at.span as usize + 1 + } else { + return false; + }; + part.vertices[v].side & if arm.dir < 0 { SIDE_BACK } else { SIDE_ON } != 0 +} + +fn dot(a: [f64; 2], b: [f64; 2]) -> f64 { + a[0] * b[0] + a[1] * b[1] +} + +/// The angle between two unit vectors. +fn angle_of(a: [f64; 2], b: [f64; 2]) -> f64 { + libm::atan2((a[0] * b[1] - a[1] * b[0]).abs(), dot(a, b)) +} + +/// The hosts of a junction's arms, which are sorted. A link's foot is a guest and is not a candidate. +fn hosts(parts: &[Part], plan: &Plan, node: &Node, headings: &[[f64; 2]]) -> (Vec, HostRule) { + let n = node.arms.len(); + let piece = |a: &RawArm| &plan.pieces[a.piece]; + let family = |a: &RawArm| parts[piece(a).part].family; + let foot = |a: &RawArm| piece(a).link == Some(LinkKind::Carriageway) && a.dir < 0; + let mut host = vec![false; n]; + let open: Vec = (0..n).filter(|&i| !foot(&node.arms[i])).collect(); + let roads: Vec = open.iter().copied().filter(|&i| family(&node.arms[i]) != Family::Path).collect(); + if !node.implicit && node.network != Network::Water { + let unmarked: Vec = roads.iter().copied().filter(|&i| !side_bit(parts, &node.arms[i])).collect(); + if unmarked.len() == 2 { + unmarked.iter().for_each(|&i| host[i] = true); + return (host, HostRule::Side); + } + } + let candidates = if roads.is_empty() { open } else { roads }; + if candidates.len() == 1 { + host[candidates[0]] = true; + return (host, HostRule::Fallback); + } + // The pair whose worse class is best, then the most nearly straight, then the better class: a + // stub of a better class does not break a through pair. + let rank = |i: usize| parts[piece(&node.arms[i]).part].class; + let mut best: Option<((u8, f64, u8), usize, usize)> = None; + for (x, &i) in candidates.iter().enumerate() { + for &j in &candidates[x + 1..] { + let k = (rank(i).max(rank(j)), dot(headings[i], headings[j]), rank(i).min(rank(j))); + if best.as_ref().is_none_or(|(b, ..)| k.partial_cmp(b) == Some(Ordering::Less)) { + best = Some((k, i, j)); + } + } + } + if let Some((_, i, j)) = best { + host[i] = true; + host[j] = true; + } + (host, HostRule::Fallback) +} + +/// The graph from the final pieces: ways, samples, points, crossings, decks and stats. +pub(crate) fn assemble( + cell: CellKey, + area: [i64; 4], + parts: Vec, + rules: &[Rule<'_>], + samples: Vec>, + mut plan: Plan, + mut stats: GraphStats, +) -> WayGraph { + plan.pieces.sort_by(|a, b| (a.part, key(&a.from)).partial_cmp(&(b.part, key(&b.from))).unwrap()); + let mut out = WayGraph { + cell, + parts: Vec::new(), + ways: Vec::new(), + samples: Vec::new(), + junctions: Vec::new(), + joints: Vec::new(), + ends: Vec::new(), + crossings: Vec::new(), + decks: Vec::new(), + levels: Default::default(), + stats: GraphStats::default(), + }; + for (id, piece) in plan.pieces.iter().enumerate() { + let part = &parts[piece.part]; + let start = out.samples.len() as u32; + let within = |s: &&Sample| { + let k = (s.span, s.u); + k >= key(&piece.from) && k <= key(&piece.to) + }; + out.samples.extend(samples[piece.part].iter().filter(within).cloned()); + out.ways.push(Way { + id: id as u32, + part: piece.part as u32, + from: piece.from, + to: piece.to, + family: part.family, + class: part.class, + level: piece.level, + deck: None, + link: piece.link, + samples: start..out.samples.len() as u32, + }); + } + stats.samples = out.samples.len() as u32; + let found = nodes(&parts, &plan, area, Some(&mut stats)); + let o = cell.origin(); + let local = |p: [i64; 2]| [(p[0] - o.x) as i32, (p[1] - o.y) as i32]; + let owned = |p: [i64; 2]| cell.contains(crate::frame::GlobalPoint { x: p[0], y: p[1] }); + // The points on each piece by metres, for `room_m` and `next`. + let mut refs: Vec = Vec::new(); + let mut counts = [0u32; 3]; + for node in &found.nodes { + let i = node.kind as usize; + refs.push(match node.kind { + NodeKind::Junction => PointRef::Junction(counts[i]), + NodeKind::Joint => PointRef::Joint(counts[i]), + NodeKind::End => PointRef::End(counts[i]), + }); + counts[i] += 1; + } + let mut on_piece: Vec> = vec![Vec::new(); plan.pieces.len()]; + for (node, &r) in found.nodes.iter().zip(&refs) { + for arm in &node.arms { + if !on_piece[arm.piece].iter().any(|&(m, q, _)| q == r && m == arm.m) { + on_piece[arm.piece].push((arm.m, r, arm.at)); + } + } + } + for list in &mut on_piece { + list.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + } + for (node, &r) in found.nodes.iter().zip(&refs) { + let mut arms: Vec<(Arm, [i64; 2])> = node + .arms + .iter() + .map(|raw| { + let piece = &plan.pieces[raw.piece]; + let (h, point) = heading(&parts, piece, raw, node.pos); + let ahead = on_piece[raw.piece].iter().filter(|&&(m, q, _)| q != r || m != raw.m); + let next = if raw.dir > 0 { + ahead.filter(|(m, ..)| *m > raw.m).min_by(|a, b| a.0.total_cmp(&b.0)) + } else { + ahead.filter(|(m, ..)| *m < raw.m).max_by(|a, b| a.0.total_cmp(&b.0)) + }; + let end = if raw.dir > 0 { piece.to } else { piece.from }; + let room = between(&parts, &raw.at, &next.map_or(end, |n| n.2)).min(ROOM_MAX_M); + let arm = Arm { + way: raw.piece as u32, + at: raw.at, + dir: raw.dir, + heading: h, + angle: libm::atan2(h[1], h[0]), + host: false, + level: piece.level, + room_m: room, + next: next.map(|&(_, q, _)| q), + }; + (arm, point) + }) + .collect(); + let mut order: Vec = (0..arms.len()).collect(); + order.sort_by(|&a, &b| { + let (x, y) = (&arms[a], &arms[b]); + x.0.angle.total_cmp(&y.0.angle).then(x.1.cmp(&y.1)).then(x.0.dir.cmp(&y.0.dir)) + }); + let raws: Vec = order.iter().map(|&i| node.arms[i].clone()).collect(); + arms = order.into_iter().map(|i| arms[i].clone()).collect(); + let sorted = Node { arms: raws, ..node.clone() }; + let pos = local(node.pos); + match node.kind { + NodeKind::Junction => { + let headings: Vec<[f64; 2]> = arms.iter().map(|a| a.0.heading).collect(); + let (host, host_rule) = hosts(&parts, &plan, &sorted, &headings); + let arms = arms.into_iter().zip(host).map(|((arm, _), host)| Arm { host, ..arm }).collect(); + stats.implicit_junctions += u32::from(node.implicit); + out.junctions.push(Junction { + pos, + network: node.network, + arms, + host_rule, + implicit: node.implicit, + owned: owned(node.pos), + }); + } + NodeKind::Joint => { + let [a, b]: [Arm; 2] = [arms[0].0.clone(), arms[1].0.clone()]; + let tangent = |arm: &Arm| { + let t = point(&parts[arm.at.part as usize], arm.at.span as usize, arm.at.u).tangent; + [f64::from(arm.dir) * t[0], f64::from(arm.dir) * t[1]] + }; + let (ta, tb) = (tangent(&a), tangent(&b)); + let stroke = angle_of([-ta[0], -ta[1]], tb).to_degrees() < STROKE_DEG; + let turn_rad = PI - angle_of(a.heading, b.heading); + out.joints.push(Joint { + pos, + network: node.network, + arms: [a, b], + turn_rad, + stroke, + owned: owned(node.pos), + }); + } + NodeKind::End => { + let arm = arms.into_iter().next().unwrap().0; + out.ends.push(End { pos, network: node.network, arm, owned: owned(node.pos) }); + } + } + } + stats.junctions = out.junctions.len() as u32; + stats.joints = out.joints.len() as u32; + stats.ends = out.ends.len() as u32; + // Crossings at shared vertices, then those of the stages after. Each network's arm is the first by + // (rank, heading point, direction), which reads only the vertex's neighbourhood. + for (pos, (ga, arms_a), (gb, arms_b)) in &found.shared { + let pick = |arms: &[RawArm]| { + arms.iter() + .min_by_key(|a| { + let piece = &plan.pieces[a.piece]; + (parts[piece.part].class, heading(&parts, piece, a, *pos).1, a.dir) + }) + .unwrap() + .clone() + }; + let (a, b) = (pick(arms_a), pick(arms_b)); + let ta = point(&parts[a.at.part as usize], a.at.span as usize, a.at.u).tangent; + let tb = point(&parts[b.at.part as usize], b.at.span as usize, b.at.u).tangent; + let angle = libm::atan2((ta[0] * tb[1] - ta[1] * tb[0]).abs(), dot(ta, tb).abs()); + let tunnel = arms_b.iter().any(|x| plan.pieces[x.piece].level == Level::Tunnel); + let water = || rules[plan.pieces[b.piece].part].water(); + let ford = || fords(parts[plan.pieces[a.piece].part].family, water()); + // A way that does not ford the water takes the untagged rule, as at a crossing without a shared vertex. + let (kind, source) = match (ga, gb) { + (Network::Way, Network::Rail) => (CrossingKind::LevelCrossing, Source::SharedVertex), + (Network::Way, Network::Water) if tunnel => (CrossingKind::Culvert, Source::SharedVertex), + (Network::Way, Network::Water) if ford() => (CrossingKind::Ford, Source::SharedVertex), + _ if angle >= GRAZE_DEG.to_radians() && water().width_m <= water().culvert_width_m => { + (CrossingKind::Culvert, Source::Rule) + } + _ => (CrossingKind::Stacked, Source::Fallback), + }; + plan.crossings.push(Crossing { + pos: local(*pos), + over: a.at, + under: b.at, + kind, + source, + angle_rad: angle, + deck: None, + owned: false, + ladder: None, + }); + } + // Decks: deck pieces that share a point, and each synthetic stretch. + let mut root: Vec = (0..plan.pieces.len()).collect(); + fn find(root: &mut [usize], i: usize) -> usize { + let mut i = i; + while root[i] != i { + root[i] = root[root[i]]; + i = root[i]; + } + i + } + for node in &found.nodes { + let decks: Vec = (node.arms.iter()) + .map(|a| a.piece) + .filter(|&p| plan.pieces[p].level == Level::Deck && !plan.pieces[p].synthetic) + .collect(); + for w in decks.windows(2) { + let (a, b) = (find(&mut root, w[0]), find(&mut root, w[1])); + root[a.max(b)] = a.min(b); + } + } + let mut groups: BTreeMap> = BTreeMap::new(); + for (i, piece) in plan.pieces.iter().enumerate().filter(|(_, p)| p.level == Level::Deck) { + let r = if piece.synthetic { i } else { find(&mut root, i) }; + groups.entry(r).or_default().push(i as u32); + } + let lowest = |ways: &[u32]| { + ways.iter() + .flat_map(|&w| { + let r = &out.ways[w as usize].samples; + out.samples[r.start as usize..r.end as usize].iter().map(|s| s.pos) + }) + .min() + }; + let mut decks: Vec = + groups.into_values().map(|ways| Deck { synthetic: plan.pieces[ways[0] as usize].synthetic, ways }).collect(); + decks.sort_by_key(|d| lowest(&d.ways)); + for (id, deck) in decks.iter().enumerate() { + for &w in &deck.ways { + out.ways[w as usize].deck = Some(id as u32); + } + } + out.decks = decks; + let deck_at = |st: &Station| { + out.ways + .iter() + .find(|w| w.part == st.part && w.level == Level::Deck && key(&w.from) <= key(st) && key(st) <= key(&w.to)) + .and_then(|w| w.deck) + }; + for c in &mut plan.crossings { + c.owned = owned([o.x + i64::from(c.pos[0]), o.y + i64::from(c.pos[1])]); + if matches!(c.kind, CrossingKind::Deck | CrossingKind::Footbridge) { + c.deck = deck_at(&c.over); + } + *stats.crossings.entry((c.kind, c.source)).or_default() += 1; + } + plan.crossings.sort_by_key(|c| (c.pos, c.kind, c.source)); + out.crossings = plan.crossings; + out.parts = parts; + out.stats = stats; + out +} diff --git a/host/obc-ground-plan/src/graph/snap.rs b/host/obc-ground-plan/src/graph/snap.rs new file mode 100644 index 0000000000..5de73e83bc --- /dev/null +++ b/host/obc-ground-plan/src/graph/snap.rs @@ -0,0 +1,276 @@ +//! Stage 5: snapped ends. Two ends close to each other join by a link; an end close to a carriageway +//! edge at its height joins that way at its foot, by a link. A link that crosses another way goes. + +use std::collections::{BTreeMap, BTreeSet}; + +use super::crossings::{cross, Grid}; +use super::curve::{geo_of, insert, point, samples as span_samples, station_sample}; +use super::parts::Rule; +use super::points::{metres, nodes, position, Anchor, NodeKind, Nodes, Piece, Plan}; +use super::{ + Family, GraphStats, Level, LinkKind, Network, Part, Sample, Span, Station, Vertex, NEWTON_STEPS, SNAP_REACH_M, +}; +use crate::frame::{metres_per_unit, CellKey}; + +/// The order of snap targets: the nearest edge, the better rank, the lower foot. +type Order = (f64, u8, [i64; 2]); + +/// An end that may snap. +#[derive(Clone, Debug)] +struct End<'a> { + pos: [i64; 2], + piece: usize, + st: Station, + z: f64, + rank: u8, + level: Level, + rule: Rule<'a>, +} + +fn distance(a: [i64; 2], b: [i64; 2]) -> f64 { + let d = [(b[0] - a[0]) as f64, (b[1] - a[1]) as f64]; + (d[0] * d[0] + d[1] * d[1]).sqrt() +} + +/// The pieces that an end reaches along the graph within `budget` metres. +fn reached(nodes: &Nodes, on_piece: &[Vec<(f64, usize)>], piece: usize, m: f64, budget: f64) -> BTreeSet { + let mut out = BTreeSet::from([piece]); + let mut best: BTreeMap = BTreeMap::new(); + let mut queue = vec![(piece, m, budget)]; + while let Some((piece, m, left)) = queue.pop() { + for &(m2, node) in &on_piece[piece] { + let rest = left - (m2 - m).abs(); + if rest < 0.0 || best.get(&node).is_some_and(|&b| b >= rest) { + continue; + } + best.insert(node, rest); + for arm in &nodes.nodes[node].arms { + out.insert(arm.piece); + queue.push((arm.piece, arm.m, rest)); + } + } + } + out +} + +/// The u on a span nearest to a point, from a first u: Newton steps on the squared distance. +pub(super) fn foot(part: &Part, span: usize, mut u: f64, e: [i64; 2]) -> f64 { + let g = geo_of(&part.vertices[span], &part.vertices[span + 1], &part.spans[span]); + let rel = [(e[0] - g.p0[0]) as f64, (e[1] - g.p0[1]) as f64]; + for _ in 0..NEWTON_STEPS { + let [p, d, dd] = g.eval(u); + let v = [p[0] - rel[0], p[1] - rel[1]]; + let f = v[0] * d[0] + v[1] * d[1]; + let df = d[0] * d[0] + d[1] * d[1] + v[0] * dd[0] + v[1] * dd[1]; + if df <= 0.0 { + break; + } + u = (u - f / df).clamp(0.0, 1.0); + } + u +} + +/// Whether a link from a to b crosses a sample segment of a piece other than `skip`. +fn crossed(grid: &Grid, a: [i64; 2], b: [i64; 2], skip: &[usize]) -> bool { + grid.near(a, b, 0).iter().any(|&id| { + let s = &grid.segs[id as usize]; + !skip.contains(&s.piece) && cross(a, b, s.a, s.b).is_some_and(|(t, _)| t > 0.0 && t < 1.0) + }) +} + +/// A link part of one chord span from an end to a point, with the end's class and level. +#[allow(clippy::too_many_arguments)] +fn link<'a>( + cell: CellKey, + area: [i64; 4], + parts: &mut Vec, + rules: &mut Vec>, + samples: &mut Vec>, + plan: &mut Plan, + from: (&End<'a>, [i64; 2], f64), + to: ([i64; 2], f64), + kind: LinkKind, +) { + let (e, a, za) = from; + let (b, zb) = to; + let source = &parts[e.st.part as usize]; + let along = station_sample(source, e.st.span as usize, e.st.u, cell).along_m; + let tangent = libm::atan2((b[1] - a[1]) as f64, (b[0] - a[0]) as f64); + let vertex = + |pos: [i64; 2], z_m: f64| Vertex { pos, z_m, tangent, grade: 0.0, bank: 0.0, widen_m: 0.0, walk: 0, side: 0 }; + let (mut va, mut vb) = (vertex(a, za), vertex(b, zb)); + let span = Span::new(&va, &vb, true, along); + let grade = (zb - za) / span.len_m; + (va.grade, vb.grade) = (grade, grade); + let part = Part { + feature: source.feature, + family: source.family, + class: source.class, + level: e.level, + backward: false, + vertices: vec![va, vb], + spans: vec![span], + }; + let index = parts.len(); + samples.push(span_samples(&part, &e.rule, cell, area).0); + plan.pieces.push(Piece { + part: index, + from: Station { part: index as u32, span: 0, u: 0.0 }, + to: Station { part: index as u32, span: 0, u: 1.0 }, + level: e.level, + link: Some(kind), + synthetic: false, + }); + parts.push(part); + rules.push(e.rule); +} + +pub(crate) fn snap<'a>( + cell: CellKey, + area: [i64; 4], + parts: &mut Vec, + rules: &mut Vec>, + samples: &mut Vec>, + mut plan: Plan, + stats: &mut GraphStats, +) -> Plan { + let prelim = nodes(parts, &plan, area, None); + let grid = Grid::new(cell, samples, &plan.pieces); + let mut on_piece: Vec> = vec![Vec::new(); plan.pieces.len()]; + for (n, node) in prelim.nodes.iter().enumerate() { + for arm in &node.arms { + on_piece[arm.piece].push((arm.m, n)); + } + } + let ends: Vec = (prelim.nodes.iter()) + .filter(|n| n.kind == NodeKind::End && n.network == Network::Way) + .filter_map(|n| { + let arm = &n.arms[0]; + let piece = &plan.pieces[arm.piece]; + let part = &parts[piece.part]; + (piece.level != Level::Tunnel && matches!(part.family, Family::Road | Family::Path)).then(|| End { + pos: n.pos, + piece: arm.piece, + st: arm.at, + z: point(part, arm.at.span as usize, arm.at.u).z_m, + rank: part.class, + level: piece.level, + rule: rules[piece.part], + }) + }) + .collect(); + let mpu = |p: [i64; 2]| metres_per_unit(p[1]); + // End to end: each the other's nearest candidate. + let nearest = |i: usize| { + let e = &ends[i]; + (0..ends.len()) + .filter(|&j| j != i && ends[j].level == e.level) + .map(|j| (distance(e.pos, ends[j].pos) * mpu(e.pos), ends[j].pos, j)) + .filter(|&(d, _, j)| { + d <= e.rule.way().snap_m.min(ends[j].rule.way().snap_m) + && (e.z - ends[j].z).abs() <= e.rule.way().snap_height_m.min(ends[j].rule.way().snap_height_m) + }) + .min_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))) + .map(|(.., j)| j) + }; + let mut done = vec![false; ends.len()]; + for i in 0..ends.len() { + let Some(j) = nearest(i).filter(|&j| j > i && nearest(j) == Some(i)) else { continue }; + done[i] = true; + done[j] = true; + let (a, b) = if (ends[i].rank, ends[i].pos) <= (ends[j].rank, ends[j].pos) { (i, j) } else { (j, i) }; + if crossed(&grid, ends[a].pos, ends[b].pos, &[ends[a].piece, ends[b].piece]) { + stats.link_crossed += 1; + continue; + } + let (ea, eb) = (&ends[a], &ends[b]); + link(cell, area, parts, rules, samples, &mut plan, (ea, ea.pos, ea.z), (eb.pos, eb.z), LinkKind::EndToEnd); + stats.links_end += 1; + } + // To a carriageway: the nearest edge, then the better rank, then the lower foot. + let pieces = plan.pieces.clone(); + for (_, e) in ends.iter().enumerate().filter(|(i, _)| !done[*i]) { + let scale = mpu(e.pos); + let reach = (SNAP_REACH_M / scale).ceil() as i64; + let near = reached(&prelim, &on_piece, e.piece, metres(parts, &pieces[e.piece], &e.st), SNAP_REACH_M); + // The nearest sample segment of each target piece. + let mut by_piece: BTreeMap = BTreeMap::new(); + for id in grid.near(e.pos, e.pos, reach) { + let s = &grid.segs[id as usize]; + let t = &pieces[s.piece]; + let tp = &parts[t.part]; + let level = t.level == e.level || (e.level == Level::Deck && t.level == Level::Ground); + if near.contains(&s.piece) + || !level + || tp.class > e.rank + || !matches!(tp.family, Family::Road | Family::Path) + { + continue; + } + let r = [(s.b[0] - s.a[0]) as f64, (s.b[1] - s.a[1]) as f64]; + let q = [(e.pos[0] - s.a[0]) as f64, (e.pos[1] - s.a[1]) as f64]; + let length2 = r[0] * r[0] + r[1] * r[1]; + let f = if length2 > 0.0 { ((q[0] * r[0] + q[1] * r[1]) / length2).clamp(0.0, 1.0) } else { 0.0 }; + let x = [q[0] - f * r[0], q[1] - f * r[1]]; + let d = (x[0] * x[0] + x[1] * x[1]).sqrt(); + if by_piece.get(&s.piece).is_none_or(|&(best, _)| d < best) { + by_piece.insert(s.piece, (d, s.at(f))); + } + } + // ((edge, rank, foot), target, station, height). + let mut best: Option<(Order, usize, Station, f64)> = None; + for (&target, &(_, st)) in &by_piece { + let tp = &parts[pieces[target].part]; + let u = foot(tp, st.span as usize, st.u, e.pos); + let st = Station { u, ..st }; + let p = point(tp, st.span as usize, u); + let p0 = tp.vertices[st.span as usize].pos; + let v = [(e.pos[0] - p0[0]) as f64 - p.d[0], (e.pos[1] - p0[1]) as f64 - p.d[1]]; + let dist = (v[0] * v[0] + v[1] * v[1]).sqrt() * scale; + let half = rules[pieces[target].part].half_m(); + let edge = dist - (half + p.widen_m); + if dist > SNAP_REACH_M { + stats.snap_far += u32::from(edge <= e.rule.way().snap_m); + continue; + } + let offset = ((v[0] * p.tangent[1] - v[1] * p.tangent[0]) * scale).clamp(-half, half); + if edge > e.rule.way().snap_m || (e.z - (p.z_m + p.bank * offset)).abs() > e.rule.way().snap_height_m { + continue; + } + let k = (edge, tp.class, position(parts, &st)); + if best.as_ref().is_none_or(|(b, ..)| k.partial_cmp(b) == Some(std::cmp::Ordering::Less)) { + best = Some((k, target, st, p.z_m)); + } + } + let Some((_, target, st, z)) = best else { continue }; + let t = &pieces[target]; + let m = metres(parts, t, &st); + // A point of the target within `snap_m` along it takes the link. + let close = (on_piece[target].iter()).filter(|(m2, _)| (m2 - m).abs() <= e.rule.way().snap_m).min_by(|a, b| { + (a.0 - m).abs().total_cmp(&(b.0 - m).abs()).then(prelim.nodes[a.1].pos.cmp(&prelim.nodes[b.1].pos)) + }); + let (to, z) = match close { + Some(&(_, n)) => { + let at = prelim.nodes[n].arms.iter().find(|a| a.piece == target).map_or(st, |a| a.at); + (prelim.nodes[n].pos, point(&parts[at.part as usize], at.span as usize, at.u).z_m) + } + None => (position(parts, &st), z), + }; + if crossed(&grid, e.pos, to, &[e.piece, target]) { + stats.link_crossed += 1; + continue; + } + let (to, z) = if close.is_none() { + let part = t.part; + let taken = insert(&parts[part], &mut samples[part], st, cell); + let pos = position(parts, &taken); + plan.anchors.push(Anchor { pos, at: taken, implicit: false }); + (pos, point(&parts[part], taken.span as usize, taken.u).z_m) + } else { + (to, z) + }; + link(cell, area, parts, rules, samples, &mut plan, (e, e.pos, e.z), (to, z), LinkKind::Carriageway); + stats.links_carriageway += 1; + } + plan +} diff --git a/host/obc-ground-plan/src/graph/tests.rs b/host/obc-ground-plan/src/graph/tests.rs new file mode 100644 index 0000000000..44d9c71aed --- /dev/null +++ b/host/obc-ground-plan/src/graph/tests.rs @@ -0,0 +1,1011 @@ +use super::*; +use crate::frame::{from_lon_lat, GlobalPoint}; +use crate::terrain::Terrain; +use crate::tile::{self, Alignment, Feature, Geometry, Tags}; + +fn cell() -> CellKey { + CellKey::of(from_lon_lat(8.40, 46.82)) +} + +fn mpu() -> f64 { + metres_per_unit(cell().origin().y + CELL_UNITS / 2) +} + +/// A point at metres east and south of the cell's centre. +fn at([x, y]: [f64; 2]) -> GlobalPoint { + let o = cell().origin(); + let half = CELL_UNITS / 2; + GlobalPoint { x: o.x + half + libm::round(x / mpu()) as i64, y: o.y + half + libm::round(y / mpu()) as i64 } +} + +/// A line feature through points in metres about the centre, at heights z (None: unknown). +#[derive(Clone)] +struct Line { + kind: &'static str, + tags: Vec<(&'static str, &'static str)>, + points: Vec<[f64; 2]>, + z: Vec>, + side: Vec, + tangents: Option>, +} + +fn line(kind: &'static str, tags: &[(&'static str, &'static str)], points: &[[f64; 2]], z: f64) -> Line { + Line { + kind, + tags: tags.to_vec(), + points: points.to_vec(), + z: vec![Some(z); points.len()], + side: vec![0; points.len()], + tangents: None, + } +} + +fn road(points: &[[f64; 2]], z: f64) -> Line { + line("road", &[("highway", "residential")], points, z) +} + +fn footway(points: &[[f64; 2]], z: f64) -> Line { + line("path", &[("highway", "footway")], points, z) +} + +fn stream(tags: &[(&'static str, &'static str)], points: &[[f64; 2]], z: f64) -> Line { + let mut all = vec![("waterway", "stream")]; + all.extend_from_slice(tags); + line("stream", &all, points, z) +} + +fn feature(l: &Line, tile: (u32, u32), index: u32) -> Feature { + let points: Vec = l.points.iter().map(|&p| at(p)).collect(); + let n = points.len(); + let chord = |i: usize, j: usize| { + libm::atan2((points[j].y - points[i].y) as f64, (points[j].x - points[i].x) as f64) + .rem_euclid(core::f64::consts::TAU) + }; + let tangent: Vec = l.tangents.clone().unwrap_or_else(|| { + (0..n) + .map(|i| { + if i == 0 { + chord(0, 1) + } else if i == n - 1 { + chord(n - 2, n - 1) + } else { + chord(i - 1, i + 1) + } + }) + .collect() + }); + let water = matches!(l.kind, "river" | "stream"); + let plan = (!water).then(|| Alignment { + along_m: 0.0, + backward: false, + tangent, + grade: vec![0.0; n], + bank: vec![0.0; n], + widen: vec![0.0; n], + side: l.side.clone(), + walk: vec![0; n], + }); + let tags: Tags = l.tags.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let part = tile::Part { outer: false, tile, own: vec![true; n - 1], points, heights: Some(l.z.clone()), plan }; + Feature { index, kind: l.kind.into(), tags, geometry: Geometry::Line, parts: vec![part] } +} + +/// The input of a cell: the lines from one tile, all owned. +fn input_of(key: CellKey, lines: &[Line]) -> CellInput { + let tile = cell().feature_tiles()[0]; + CellInput { + key, + features: lines.iter().zip(0..).map(|(l, index)| feature(l, tile, index)).collect(), + terrain: Terrain::new(key, Vec::new()), + } +} + +fn graph(lines: &[Line]) -> WayGraph { + graph_of(cell(), lines) +} + +fn graph_of(key: CellKey, lines: &[Line]) -> WayGraph { + graph_with(input_of(key, lines)) +} + +/// The graph of lines on terrain z of metres east and south of the cell's centre. +fn graph_on(lines: &[Line], z: &dyn Fn(f64, f64) -> f64) -> WayGraph { + let mut input = input_of(cell(), lines); + input.terrain = crate::faces::tests::plane(cell(), z); + graph_with(input) +} + +fn graph_with(input: CellInput) -> WayGraph { + let key = input.key; + let mut g = build(key, &input, Sections::embedded()); + assert_eq!(check(&g), Vec::new()); + let structures = &crate::faces::Rules::embedded().structures; + levels(&mut g, &input, Sections::embedded(), structures); + assert_eq!(check_levels(&g, &input, Sections::embedded(), structures), Vec::new()); + g +} + +fn class(g: &WayGraph, arm: &Arm) -> String { + let w = &g.ways[arm.way as usize]; + Sections::embedded().rank_name(w.family == Family::Water, w.class as usize).to_string() +} + +fn hosts(g: &WayGraph) -> Vec<(String, bool)> { + let mut out: Vec<(String, bool)> = g.junctions[0].arms.iter().map(|a| (class(g, a), a.host)).collect(); + out.sort(); + out +} + +/// The span metres of the bake: one 5-point Simpson with the chord in metres. +fn bake_arc(chord: [f64; 2], t0: [f64; 2], t1: [f64; 2]) -> f64 { + let c = (chord[0] * chord[0] + chord[1] * chord[1]).sqrt(); + let speed = |u: f64| { + let (d0, d1, d2) = (3.0 * u * u - 4.0 * u + 1.0, 6.0 * u - 6.0 * u * u, 3.0 * u * u - 2.0 * u); + let v = [d1 * chord[0] + c * (d0 * t0[0] + d2 * t1[0]), d1 * chord[1] + c * (d0 * t0[1] + d2 * t1[1])]; + (v[0] * v[0] + v[1] * v[1]).sqrt() + }; + (speed(0.0) + 4.0 * speed(0.25) + 2.0 * speed(0.5) + 4.0 * speed(0.75) + speed(1.0)) / 12.0 +} + +#[test] +fn a_span_measures_as_the_bake_and_its_metres_invert() { + let mut l = road(&[[0.0, 0.0], [40.0, 10.0]], 0.0); + l.tangents = Some(vec![-0.3, 0.6]); + let g = graph(&[l]); + let (part, span) = (&g.parts[0], &g.parts[0].spans[0]); + let (a, b) = (&part.vertices[0], &part.vertices[1]); + let scale = metres_per_unit((a.pos[1] + b.pos[1]).div_euclid(2)); + let chord = [(b.pos[0] - a.pos[0]) as f64 * scale, (b.pos[1] - a.pos[1]) as f64 * scale]; + let unit = |t: f64| [libm::cos(t), libm::sin(t)]; + let bake = bake_arc(chord, unit(a.tangent), unit(b.tangent)); + assert!((span.knots[KNOTS] - bake).abs() < 1e-9 * bake, "{} {bake}", span.knots[KNOTS]); + assert!(span.knots.windows(2).all(|k| k[0] < k[1])); + for u in [0.0, 0.013, 0.31, 0.5, 0.97, 1.0] { + assert!((u_at(span, s_at(span, u)) - u).abs() < 1e-12, "{u}"); + } +} + +#[test] +fn samples_break_at_cell_lines_and_a_grid_point_near_a_break_goes() { + let o = cell().origin(); + // A road whose crossing with the cell's east line lies 16.03 m from its start. + let east_m = (CELL_UNITS / 2) as f64 * mpu(); + let g = graph(&[road(&[[east_m - 16.03, 3.0], [east_m + 30.0, 3.0]], 0.0)]); + let samples = &g.samples; + let lines: Vec<&Sample> = samples.iter().filter(|s| s.kind == SampleKind::CellLine).collect(); + assert_eq!(lines.len(), 1); + assert_eq!(i64::from(lines[0].pos[0]) + o.x, o.x + CELL_UNITS, "exactly on the line"); + assert!(samples.iter().all(|s| s.kind != SampleKind::Grid || (s.s_m - lines[0].s_m).abs() >= MIN_STEP_M / 2.0)); + // A straight road through a cell corner gives one sample there. + let corner = [east_m, east_m]; + let g = graph(&[road(&[[corner[0] - 20.0, corner[1] - 20.0], [corner[0] + 20.0, corner[1] + 20.0]], 0.0)]); + let corners: Vec<&Sample> = g.samples.iter().filter(|s| s.kind == SampleKind::CellLine).collect(); + assert_eq!(corners.len(), 1, "{corners:?}"); + assert_eq!(corners[0].pos, [CELL_UNITS as i32, CELL_UNITS as i32]); +} + +#[test] +fn a_stream_is_a_curve_through_its_vertices_with_its_levels_smooth_and_falling_along_it() { + // Chords of 30 m and 60 m: the tangent bisects their directions and does not lean to the longer. + let g = graph(&[Line { + z: vec![Some(10.0), Some(8.0), Some(7.0)], + ..stream(&[], &[[-30.0, 0.0], [0.0, 5.0], [60.0, 0.0]], 0.0) + }]); + let part = &g.parts[0]; + let (v, s) = (&part.vertices, &part.spans); + assert!(s.iter().all(|s| !s.chord && s.water_z)); + let direction = |a: [i64; 2], b: [i64; 2]| libm::atan2((b[1] - a[1]) as f64, (b[0] - a[0]) as f64); + let half = (direction(v[0].pos, v[1].pos) + direction(v[1].pos, v[2].pos)) / 2.0; + assert!((v[1].tangent - half).abs() < 1e-12, "the bisector of its chords"); + assert!((v[0].tangent - direction(v[0].pos, v[1].pos)).abs() < 1e-12, "an end takes its one chord"); + for (span, u, vertex) in [(0, 0.0, 0), (0, 1.0, 1), (1, 0.0, 1), (1, 1.0, 2)] { + let p = point(part, span, u); + let at = [v[span].pos[0] as f64 + p.d[0], v[span].pos[1] as f64 + p.d[1]]; + assert!((at[0] - v[vertex].pos[0] as f64).abs() < 1e-6 && (at[1] - v[vertex].pos[1] as f64).abs() < 1e-6); + let t = [libm::cos(v[vertex].tangent), libm::sin(v[vertex].tangent)]; + assert!((p.tangent[0] - t[0]).abs() < 1e-9 && (p.tangent[1] - t[1]).abs() < 1e-9, "{span} {u}"); + assert!((p.z_m - v[vertex].z_m).abs() < 1e-9); + } + // The level falls all along, and its grade has no break at the middle vertex. + let z: Vec = (0..=40).map(|j| point(part, j / 21, (j % 21) as f64 / 20.0).z_m).collect(); + assert!(z.windows(2).all(|w| w[1] <= w[0] + 1e-12), "{z:?}"); + assert!((point(part, 0, 1.0).grade - point(part, 1, 0.0).grade).abs() < 1e-9); + assert!(point(part, 1, 0.0).grade < 0.0, "a vertex between two falls keeps falling"); + assert!(g.samples.iter().any(|s| s.kind == SampleKind::Grid), "the sag rule refines it"); + // A turn over `curve_turn_max_deg` (60°) is a corner: both its spans are chords, the next one not, and + // that curve leaves vertex 2 along the chord before it, so the line does not kink there. + let g = graph(&[stream(&[], &[[-30.0, 0.0], [0.0, 0.0], [-20.0, 25.0], [-25.0, 60.0]], 0.0)]); + let (v, s) = (&g.parts[0].vertices, &g.parts[0].spans); + assert_eq!(s.iter().map(|s| s.chord).collect::>(), [true, true, false]); + let t = point(&g.parts[0], 2, 0.0).tangent; + let chord = direction(v[1].pos, v[2].pos); + assert!((t[0] - libm::cos(chord)).abs() < 1e-9 && (t[1] - libm::sin(chord)).abs() < 1e-9); + // Spans of 300 m whose curves would leave their chords by more than `curve_off_max_m` (2 m). + let g = graph(&[stream(&[], &[[-300.0, -60.0], [0.0, 0.0], [300.0, -60.0]], 0.0)]); + assert!(g.parts[0].spans.iter().all(|s| s.chord)); +} + +#[test] +fn a_waters_end_at_a_tile_line_reads_the_tiles_next_vertex() { + // A stream across a zoom-13 tile line, 150 m spans. The cell two west of the line reads only the + // west tile; the cell on the line reads both. + let line_x = cell().feature_tiles().iter().map(|t| tile::tile_square(*t)[2]).min().unwrap(); + let both = CellKey::of(GlobalPoint { x: line_x, y: cell().origin().y }); + let west = CellKey { x: both.x - 2, y: both.y }; + let unit = (150.0 / metres_per_unit(both.origin().y)) as i64; + let p = |k: i64| GlobalPoint { x: line_x + k * unit + 7, y: both.origin().y + 1000 + (k & 1) * unit / 8 }; + let tags: Tags = [("waterway".to_string(), "stream".to_string())].into(); + let copy = |tiles: &[(u32, u32)], tile: (u32, u32), ks: std::ops::RangeInclusive| { + let points: Vec = ks.clone().map(p).collect(); + let at = tiles.iter().position(|&t| t == tile).unwrap(); + let own = tile::own(Geometry::Line, &points, tiles, at); + let heights = Some(ks.map(|k| Some(100.0 - k as f64)).collect()); + let part = tile::Part { outer: false, tile, own, points, heights, plan: None }; + Feature { index: 0, kind: "stream".into(), tags: tags.clone(), geometry: Geometry::Line, parts: vec![part] } + }; + let holding = |tiles: &[(u32, u32)], q: GlobalPoint| { + *tiles.iter().find(|&&t| tile::tile_square(t)[0] <= q.x && q.x < tile::tile_square(t)[2]).unwrap() + }; + let tangent_at = |key: CellKey| { + let tiles = key.feature_tiles(); + let (w, e) = (holding(&tiles, p(-1)), tiles.iter().copied().find(|t| tile::tile_square(*t)[0] == line_x)); + let mut features = vec![copy(&tiles, w, -6..=2)]; + if let Some(e) = e { + features.push(copy(&tiles, e, -2..=3)); + } + let g = build(key, &CellInput { key, features, terrain: Terrain::new(key, Vec::new()) }, Sections::embedded()); + let v = g.parts.iter().flat_map(|part| &part.vertices).find(|v| v.pos == [p(0).x, p(0).y]).unwrap(); + v.tangent + }; + assert_eq!(tangent_at(west), tangent_at(both)); +} + +#[test] +fn water_reads_on_through_a_vertex_where_the_map_splits_it_into_two_ways_but_not_at_a_confluence() { + // A stream mapped as two ways that meet at (0, 0): the curve and the grade at the shared vertex are + // those of one line, so the water turns and falls smoothly there. + let up = Line { z: vec![Some(12.0), Some(10.0)], ..stream(&[], &[[-40.0, -10.0], [0.0, 0.0]], 0.0) }; + let down = Line { z: vec![Some(10.0), Some(9.0)], ..stream(&[("name", "Bach")], &[[0.0, 0.0], [50.0, -5.0]], 0.0) }; + let joint = |g: &WayGraph| -> Vec<(f64, f64)> { + let o = at([0.0, 0.0]); + (g.parts.iter().flat_map(|p| &p.vertices)) + .filter(|v| v.pos == [o.x, o.y]) + .map(|v| (v.tangent, v.grade)) + .collect() + }; + let one = joint(&graph(&[up.clone(), down.clone()])); + assert_eq!(one.len(), 2); + assert!((one[0].0 - one[1].0).abs() < 1e-12 && (one[0].1 - one[1].1).abs() < 1e-12, "{one:?}"); + let whole = joint(&graph(&[Line { + z: vec![Some(12.0), Some(10.0), Some(9.0)], + ..stream(&[], &[[-40.0, -10.0], [0.0, 0.0], [50.0, -5.0]], 0.0) + }])); + assert!((one[0].0 - whole[0].0).abs() < 1e-12 && (one[0].1 - whole[0].1).abs() < 1e-12); + // A third line that ends there makes a confluence: each line keeps its own chord. + let side = stream(&[], &[[0.0, 0.0], [10.0, 40.0]], 0.0); + let three = joint(&graph(&[up, down, side])); + assert!(three.iter().all(|t| (t.0 - one[0].0).abs() > 1e-3), "{three:?}"); +} + +#[test] +fn cleaning_flattens_spikes_and_folded_spans_and_removes_repeated_vertices() { + // A spike stays a vertex; its two spans are chords. + let g = graph(&[road(&[[-30.0, 0.0], [20.0, 0.0], [-10.0, 0.3], [-10.0, 30.0]], 0.0)]); + let chords: Vec = g.parts[0].spans.iter().map(|s| s.chord).collect(); + assert_eq!((g.stats.spikes, chords), (1, vec![true, true, false])); + let g = graph(&[road(&[[0.0, 0.0], [10.0, 0.0], [10.0, 0.0], [20.0, 0.0]], 0.0)]); + assert_eq!((g.stats.repeated, g.parts[0].vertices.len()), (1, 3)); + let mut folded = road(&[[0.0, 0.0], [10.0, 0.0], [20.0, 0.0]], 0.0); + folded.tangents = Some(vec![0.0, core::f64::consts::PI, 0.0]); + let g = graph(&[folded]); + assert_eq!(g.stats.folded, 2); + assert!(g.parts[0].spans.iter().all(|s| s.chord)); +} + +#[test] +fn a_way_across_a_tile_line_is_one_part_with_each_spans_along_from_its_owner() { + // A cell on a zoom-13 tile line: the way runs from the west tile into the east one. + let line_x = cell().feature_tiles().iter().map(|t| tile::tile_square(*t)[2]).min().unwrap(); + let key = CellKey::of(GlobalPoint { x: line_x, y: cell().origin().y }); + let tiles = key.feature_tiles(); + assert!(tiles.len() >= 2); + let y = key.origin().y + 1000; + let unit = (10.0 / metres_per_unit(y)) as i64; + let p = |k: i64| GlobalPoint { x: line_x + k * unit + 7, y }; + let tags: Tags = [("highway".to_string(), "residential".to_string())].into(); + let copy = |tile: (u32, u32), ks: std::ops::RangeInclusive, along_m: f64| { + let points: Vec = ks.map(p).collect(); + let n = points.len(); + let own = tile::own(Geometry::Line, &points, &tiles, tiles.iter().position(|&t| t == tile).unwrap()); + let plan = Alignment { + along_m, + backward: false, + tangent: vec![0.0; n], + grade: vec![0.0; n], + bank: vec![0.0; n], + widen: vec![0.0; n], + side: vec![0; n], + walk: vec![0; n], + }; + let part = tile::Part { outer: false, tile, own, points, heights: Some(vec![Some(1.0); n]), plan: Some(plan) }; + Feature { index: 0, kind: "road".into(), tags: tags.clone(), geometry: Geometry::Line, parts: vec![part] } + }; + let holding = |q: GlobalPoint| { + *tiles.iter().find(|&&t| tile::tile_square(t)[0] <= q.x && q.x < tile::tile_square(t)[2]).unwrap() + }; + let (west, east) = (holding(p(-1)), holding(p(1))); + let features = vec![copy(west, -4..=1, 0.0), copy(east, -1..=4, 30.1)]; + let g = build(key, &CellInput { key, features, terrain: Terrain::new(key, Vec::new()) }, Sections::embedded()); + assert_eq!((g.parts.len(), g.joints.len()), (1, 0)); + let along: Vec = g.parts[0].spans.iter().map(|s| s.along0_m).collect(); + // The west tile owns the four spans before the line and the one that meets it. + assert!((along[3] - 30.0).abs() < 0.01 && (along[4] - 40.1).abs() < 0.01, "{along:?}"); +} + +#[test] +fn a_footway_on_a_roads_vertices_loses_the_run_in_either_direction() { + for reversed in [false, true] { + let mut walk = vec![[-30.0, -10.0], [-10.0, 0.0], [10.0, 0.0], [30.0, -10.0]]; + if reversed { + walk.reverse(); + } + let g = graph(&[road(&[[-40.0, 0.0], [-10.0, 0.0], [10.0, 0.0], [40.0, 0.0]], 0.0), footway(&walk, 0.0)]); + assert_eq!(g.stats.shared_runs, 1); + assert_eq!(g.junctions.len(), 2, "{reversed}"); + assert_eq!(g.ways.iter().filter(|w| w.family == Family::Path).count(), 2); + } +} + +/// The tangent at the lower vertex of each of the two shared segments, of the part that keeps it. +fn keepers(g: &WayGraph) -> Vec { + keepers_of(g, &[[[-30.0, 0.0], [0.0, 0.0]], [[0.0, 0.0], [30.0, 0.0]]]) +} + +fn keepers_of(g: &WayGraph, segments: &[[[f64; 2]; 2]]) -> Vec { + let segments: Vec<[GlobalPoint; 2]> = segments.iter().map(|[a, b]| [at(*a), at(*b)]).collect(); + segments + .iter() + .map(|[a, b]| { + let (a, b) = ([a.x, a.y], [b.x, b.y]); + let kept: Vec = (g.ways.iter()) + .flat_map(|w| { + let part = &g.parts[w.part as usize]; + (w.from.span..w.to.span.max(w.from.span + 1)).filter_map(move |k| { + let (p, q) = (part.vertices.get(k as usize)?, part.vertices.get(k as usize + 1)?); + let lower = if p.pos <= q.pos { p } else { q }; + let mut ends = [p.pos, q.pos]; + ends.sort(); + (ends == [a.min(b), a.max(b)] && (w.to.span > k || w.to.u == 1.0)).then_some(lower.tangent) + }) + }) + .collect(); + assert_eq!(kept.len(), 1, "one part keeps each shared segment"); + kept[0] + }) + .collect() +} + +#[test] +fn a_shared_run_of_equal_ranks_is_decided_by_each_segment_alone() { + // Two service roads on one run, with mirrored exits and their own tangents on it. + let service = |points: &[[f64; 2]], tangents: &[f64]| { + let mut l = line("road", &[("highway", "service")], points, 0.0); + l.tangents = Some(tangents.to_vec()); + l + }; + let a = |far: bool| { + let (mut p, mut t) = + (vec![[-60.0, -20.0], [-30.0, 0.0], [0.0, 0.0], [30.0, 0.0], [60.0, 20.0]], vec![0.6, 0.3, 0.0, 0.2, 0.5]); + if !far { + p.remove(0); + t.remove(0); + } + service(&p, &t) + }; + let b = service( + &[[-60.0, 20.0], [-30.0, 0.0], [0.0, 0.0], [30.0, 0.0], [60.0, -20.0]], + &[-0.6, -0.3, 0.05, -0.2, -0.5], + ); + let full = keepers(&graph(&[a(true), b.clone()])); + assert_eq!(full, keepers(&graph(&[b.clone(), a(true)])), "the input order decides nothing"); + assert_eq!(full, keepers(&graph(&[a(false), b.clone()])), "a far vertex decides nothing"); + // The same run near the east border, built by the cell and by its east neighbour. + let shift = (CELL_UNITS / 2) as f64 * mpu() - 60.0; + let moved = |l: &Line| Line { points: l.points.iter().map(|p| [p[0] + shift, p[1]]).collect(), ..l.clone() }; + let lines = [moved(&a(true)), moved(&b)]; + let east = CellKey { x: cell().x + 1, y: cell().y }; + let keep = |g: &WayGraph| { + let segments = [[[shift - 30.0, 0.0], [shift, 0.0]], [[shift, 0.0], [shift + 30.0, 0.0]]]; + keepers_of(g, &segments) + }; + assert_eq!(keep(&graph_of(cell(), &lines)), keep(&graph_of(east, &lines)), "two cells decide alike"); + // An exact duplicate the other way round: the part along the lower position first keeps it. + let back = |l: &Line| { + let mut r = l.clone(); + r.points.reverse(); + r.tangents = l.tangents.as_ref().map(|t| t.iter().rev().map(|a| a + core::f64::consts::PI).collect()); + r + }; + let one = keepers(&graph(&[b.clone(), back(&b)])); + assert_eq!(one, keepers(&graph(&[back(&b), b.clone()]))); + // The same way twice, one way: the copy of the lower position in its tile keeps every span. + let g = graph(&[b.clone(), b.clone()]); + assert_eq!((g.ways.len(), g.junctions.len(), g.joints.len()), (1, 0, 0)); +} + +#[test] +fn hosts_follow_side_then_the_fallback_rule() { + // A side road whose end carries its side bit: the through road hosts. + let mut side = road(&[[0.0, 40.0], [0.0, 0.0]], 0.0); + side.side = vec![0, SIDE_BACK]; + let g = graph(&[road(&[[-40.0, 0.0], [0.0, 0.0], [40.0, 0.0]], 0.0), side]); + assert_eq!(g.junctions[0].host_rule, HostRule::Side); + assert_eq!(hosts(&g), [("residential".into(), false), ("residential".into(), true), ("residential".into(), true)]); + let straight = |g: &WayGraph| { + let h: Vec<&Arm> = g.junctions[0].arms.iter().filter(|a| a.host).collect(); + h[0].heading[0] * h[1].heading[0] + h[0].heading[1] * h[1].heading[1] + }; + // No side: the pair most nearly straight on. + let g = graph(&[ + road(&[[-40.0, 0.0], [0.0, 0.0]], 0.0), + road(&[[0.0, 0.0], [40.0, 3.0]], 0.0), + road(&[[0.0, 0.0], [10.0, 40.0]], 0.0), + ]); + assert_eq!(g.junctions[0].host_rule, HostRule::Fallback); + assert!(straight(&g) < -0.99); + // A road that ends where two footways run on is the only host. + let g = graph(&[ + road(&[[-40.0, 0.0], [0.0, 0.0]], 0.0), + footway(&[[0.0, 0.0], [40.0, 0.0]], 0.0), + footway(&[[0.0, 0.0], [0.0, 40.0]], 0.0), + ]); + assert_eq!(hosts(&g), [("footway".into(), false), ("footway".into(), false), ("residential".into(), true)]); + // Footways alone: the straight pair. + let g = graph(&[ + footway(&[[-40.0, 0.0], [0.0, 0.0]], 0.0), + footway(&[[0.0, 0.0], [40.0, 0.0]], 0.0), + footway(&[[0.0, 0.0], [0.0, 40.0]], 0.0), + ]); + assert!(straight(&g) < -0.99); + // A flight of steps with a short footway stub: the steps run through. + let g = graph(&[ + line("path", &[("highway", "steps")], &[[-20.0, 0.0], [0.0, 0.0], [20.0, 0.0]], 0.0), + footway(&[[0.0, 0.0], [0.0, 2.5]], 0.0), + ]); + assert_eq!(hosts(&g), [("footway".into(), false), ("steps".into(), true), ("steps".into(), true)]); + // A footway that ends on a street vertex, and one across it at a shared vertex: the street hosts. + for walk in [vec![[0.0, 0.0], [0.0, 40.0]], vec![[0.0, -40.0], [0.0, 0.0], [0.0, 40.0]]] { + let g = graph(&[road(&[[-40.0, 0.0], [0.0, 0.0], [40.0, 0.0]], 0.0), footway(&walk, 0.0)]); + assert!(g.junctions[0].arms.iter().all(|a| a.host == (class(&g, a) == "residential"))); + } +} + +#[test] +fn ends_snap_by_the_table() { + // A residential road, 2.5 m half-width, along x; a footway end beside it. + let street = || road(&[[-50.0, 0.0], [0.0, 0.0], [50.0, 0.0]], 0.0); + let end = |y: f64, z: f64| footway(&[[0.0, -30.0], [0.0, y]], z); + let links = |g: &WayGraph| (g.stats.links_carriageway, g.stats.links_end, g.stats.link_crossed); + for (what, lines, expect) in [ + ("0.9 m from the edge, 0.4 m up", vec![street(), end(-3.4, 0.4)], (1, 0, 0)), + ("1.1 m from the edge", vec![street(), end(-3.6, 0.0)], (0, 0, 0)), + ("0.9 m from the edge, 0.6 m up", vec![street(), end(-3.4, 0.6)], (0, 0, 0)), + ("inside the carriageway", vec![street(), end(-1.0, 0.0)], (1, 0, 0)), + ( + "two ends 5 cm apart", + vec![footway(&[[-30.0, -20.0], [0.0, -20.0]], 0.0), footway(&[[0.05, -20.0], [30.0, -20.0]], 0.0)], + (0, 1, 0), + ), + ( + "an end near its own way along the graph", + vec![street(), footway(&[[0.0, 0.0], [0.0, -8.0], [6.0, -8.0], [6.0, -3.0]], 0.0)], + (0, 0, 0), + ), + ( + "a link across a stream", + vec![street(), end(-3.4, 0.0), stream(&[], &[[-20.0, -2.0], [20.0, -2.0]], 0.0)], + (0, 0, 1), + ), + ] { + let g = graph(&lines); + assert_eq!(links(&g), expect, "{what}"); + if expect.0 == 1 { + let j = g.junctions.iter().find(|j| j.arms.iter().any(|a| g.ways[a.way as usize].link.is_some())).unwrap(); + assert!(j.arms.iter().all(|a| a.host == (g.ways[a.way as usize].link.is_none())), "{what}"); + } + } + // A foot within `snap_m` of a junction of the street attaches there. + let g = graph(&[street(), road(&[[0.0, 0.0], [0.0, 40.0]], 0.0), footway(&[[0.6, -30.0], [0.6, -3.0]], 0.0)]); + assert_eq!(g.stats.links_carriageway, 1); + assert_eq!(g.junctions.len(), 1); + assert_eq!(g.junctions[0].arms.len(), 4); +} + +/// The one crossing of two lines, as (kind, source), or None. +fn crossing(lines: &[Line]) -> Option<(CrossingKind, Source)> { + let g = graph(lines); + assert!(g.crossings.len() <= 1, "{:?}", g.crossings); + g.crossings.first().map(|c| (c.kind, c.source)) +} + +#[test] +fn a_short_culvert_chain_under_a_road_opens_on_one_straight_line_and_a_long_one_stays_buried() { + // Two pipes of `half` metres meet end to end under a road, between open water at 10 m and at 8 m. + let pipe = + |a: f64, b: f64| Line { z: vec![None, None], ..stream(&[("tunnel", "culvert")], &[[a, 0.0], [b, 0.0]], 0.0) }; + let chain = |half: f64| { + graph(&[ + road(&[[-1.0, -40.0], [-1.0, 40.0]], 12.0), + stream(&[], &[[-half - 30.0, 0.0], [-half, 0.0]], 10.0), + pipe(-half, 0.0), + pipe(0.0, half), + stream(&[], &[[half, 0.0], [half + 30.0, 0.0]], 8.0), + ]) + }; + let east = |s: &Sample| f64::from(s.pos[0] - (CELL_UNITS / 2) as i32) * mpu(); + let g = chain(25.0); + let water: Vec<&Way> = g.ways.iter().filter(|w| w.family == Family::Water).collect(); + assert!(water.iter().all(|w| w.level == Level::Ground), "the chain of 50 m lies open"); + for w in water { + for s in &g.samples[w.samples.start as usize..w.samples.end as usize] { + let x = east(s).clamp(-25.0, 25.0); + let line = 10.0 - 2.0 * (x + 25.0) / 50.0; + assert!((s.z_m - line).abs() < 0.05, "{x} m east: {} m, the line {line} m", s.z_m); + } + } + let g = chain(35.0); + assert_eq!((g.crossings[0].kind, g.crossings[0].source), (CrossingKind::Culvert, Source::Fallback)); + let tunnels = g.ways.iter().filter(|w| w.family == Family::Water && w.level == Level::Tunnel).count(); + assert_eq!(tunnels, 2, "the chain of 70 m stays buried"); +} + +#[test] +fn crossings_take_the_first_row_of_the_table() { + use CrossingKind::*; + let across = |z: f64| road(&[[0.0, -40.0], [0.0, 40.0]], z); + let along = |kind, tags: &[(&'static str, &'static str)], z| line(kind, tags, &[[-40.0, 0.0], [40.0, 0.0]], z); + let at_angle = |deg: f64, l: Line| { + let (c, s) = (libm::cos(deg.to_radians()) * 40.0, libm::sin(deg.to_radians()) * 40.0); + line(l.kind, &l.tags, &[[-c, -s], [c, s]], l.z.first().copied().flatten().unwrap_or(0.0)) + }; + let bridge = [("highway", "residential"), ("bridge", "yes"), ("deck", "1")]; + // An open stream, a culvert of 2 × half metres under the road, and the open stream again. + let culvert = |half: f64| { + let pipe = Line { z: vec![None, None], ..stream(&[("tunnel", "culvert")], &[[-half, 0.0], [half, 0.0]], 0.0) }; + vec![ + across(0.0), + stream(&[], &[[-40.0, 0.0], [-half, 0.0]], 0.0), + pipe, + stream(&[], &[[half, 0.0], [40.0, 0.0]], 0.0), + ] + }; + type Row = (&'static str, Vec, Option<(CrossingKind, Source)>); + let rows: Vec = vec![ + ( + "a deck", + vec![ + line("road", &bridge, &[[0.0, -40.0], [0.0, 40.0]], 6.0), + along("road", &[("highway", "residential")], 0.0), + ], + Some((Deck, Source::Tag)), + ), + ("a short culvert", culvert(5.0), Some((Culvert, Source::Tag))), + ("a buried stream", culvert(35.0), Some((Culvert, Source::Fallback))), + ( + "a track's ford over a river", + vec![ + line("road", &[("highway", "track"), ("ford", "yes")], &[[0.0, -40.0], [0.0, 40.0]], 0.0), + along("river", &[("waterway", "river")], 0.0), + ], + Some((Ford, Source::Tag)), + ), + ( + "a path's ford over a stream", + vec![ + line("path", &[("highway", "footway"), ("ford", "yes")], &[[0.0, -40.0], [0.0, 40.0]], 0.0), + stream(&[], &[[-40.0, 0.0], [40.0, 0.0]], 0.0), + ], + Some((Ford, Source::Tag)), + ), + ( + "a track's ford over a stream: a culvert, as the bake lays it", + vec![ + line("road", &[("highway", "track"), ("ford", "yes")], &[[0.0, -40.0], [0.0, 40.0]], 0.0), + stream(&[], &[[-40.0, 0.0], [40.0, 0.0]], 0.0), + ], + Some((Culvert, Source::Rule)), + ), + ( + "a track's ford over a stream at 19°", + vec![ + line("road", &[("highway", "track"), ("ford", "yes")], &[[0.0, -40.0], [0.0, 40.0]], 0.0), + at_angle(71.0, stream(&[], &[[0.0, 0.0]], 0.0)), + ], + Some((Stacked, Source::Fallback)), + ), + ( + "a road over a stream", + vec![across(0.0), stream(&[], &[[-40.0, 0.0], [40.0, 0.0]], 0.0)], + Some((Culvert, Source::Rule)), + ), + ( + "a road over a river", + vec![across(0.0), along("river", &[("waterway", "river")], 0.0)], + Some((Deck, Source::Rule)), + ), + ( + "a path over a ditch", + vec![ + footway(&[[0.0, -40.0], [0.0, 40.0]], 0.0), + stream(&[("width", "0.5")], &[[-40.0, 0.0], [40.0, 0.0]], 0.0), + ], + Some((PipeInStones, Source::Rule)), + ), + ( + "a path over a stream", + vec![footway(&[[0.0, -40.0], [0.0, 40.0]], 0.0), stream(&[], &[[-40.0, 0.0], [40.0, 0.0]], 0.0)], + Some((SteppingStones, Source::Rule)), + ), + ( + "a path over a brook", + vec![ + footway(&[[0.0, -40.0], [0.0, 40.0]], 0.0), + stream(&[("width", "5")], &[[-40.0, 0.0], [40.0, 0.0]], 0.0), + ], + Some((Footbridge, Source::Rule)), + ), + ( + "a road over a railway", + vec![across(0.2), along("railway", &[("railway", "rail")], 0.0)], + Some((LevelCrossing, Source::Rule)), + ), + ( + "a road over a road", + vec![across(5.0), along("road", &[("highway", "residential")], 0.0)], + Some((Deck, Source::Rule)), + ), + ( + "a road just over a road", + vec![across(2.0), along("road", &[("highway", "residential")], 0.0)], + Some((Stacked, Source::Fallback)), + ), + ( + "a road over a wide river at 25°", + vec![across(0.0), at_angle(65.0, along("river", &[("waterway", "river"), ("width", "30")], 0.0))], + Some((Stacked, Source::Fallback)), + ), + ( + "a bridge over a road at 15°", + vec![ + line("road", &bridge, &[[0.0, -40.0], [0.0, 40.0]], 6.0), + at_angle(75.0, along("road", &[("highway", "residential")], 0.0)), + ], + Some((Deck, Source::Tag)), + ), + ( + "a road that ends on a stream", + vec![road(&[[0.0, 0.0], [0.0, 40.0]], 0.0), along("stream", &[("waterway", "stream")], 0.0)], + None, + ), + ( + "the same road reversed", + vec![road(&[[0.0, 40.0], [0.0, 0.0]], 0.0), along("stream", &[("waterway", "stream")], 0.0)], + None, + ), + ( + "a road over a road at 19°", + vec![across(5.0), at_angle(71.0, along("road", &[("highway", "residential")], 0.0))], + None, + ), + ( + "a road over a stream at 19°", + vec![across(0.0), at_angle(71.0, stream(&[], &[[0.0, 0.0]], 0.0))], + Some((Stacked, Source::Fallback)), + ), + ( + "a road and a railway at a shared vertex", + vec![ + road(&[[0.0, -40.0], [0.0, 0.0], [0.0, 40.0]], 0.0), + line("railway", &[("railway", "rail")], &[[-40.0, 0.0], [0.0, 0.0], [40.0, 0.0]], 0.0), + ], + Some((LevelCrossing, Source::SharedVertex)), + ), + ]; + for (what, lines, expect) in rows { + assert_eq!(crossing(&lines), expect, "{what}"); + } + let wide = graph(&[across(0.0), at_angle(65.0, along("river", &[("waterway", "river"), ("width", "30")], 0.0))]); + assert_eq!(wide.stats.deck_fallback, 1); + // A deck stretch that would hold a junction of the upper road falls back. + let g = graph(&[ + road(&[[0.0, -40.0], [0.0, -3.0], [0.0, 40.0]], 0.0), + road(&[[0.0, -3.0], [30.0, -3.0]], 0.0), + along("river", &[("waterway", "river")], 0.0), + ]); + assert_eq!((g.stats.deck_fallback, g.crossings[0].kind), (1, Stacked)); + // A deck stretch past a way's end at the work area's edge is cut there. + let east = (work_area(cell())[2] - cell().origin().x - CELL_UNITS / 2) as f64 * mpu(); + let g = graph(&[ + road(&[[east - 60.0, 0.0], [east - 20.0, 0.0], [east + 3.0, 0.0], [east + 200.0, 0.0]], 0.0), + line("river", &[("waterway", "river")], &[[east - 1.0, -40.0], [east - 1.0, 40.0]], 0.0), + ]); + assert_eq!((g.stats.deck_cut, g.crossings[0].kind, g.decks.len()), (1, Deck, 1)); + // A culvert chain runs on through the joint of two pipes: 70 m is a buried stream. + let pipe = + |a: f64, b: f64| Line { z: vec![None, None], ..stream(&[("tunnel", "culvert")], &[[a, 0.0], [b, 0.0]], 0.0) }; + let lines = vec![ + road(&[[-1.0, -40.0], [-1.0, 40.0]], 0.0), + stream(&[], &[[-60.0, 0.0], [-35.0, 0.0]], 0.0), + pipe(-35.0, 0.0), + pipe(0.0, 35.0), + stream(&[], &[[35.0, 0.0], [60.0, 0.0]], 0.0), + ]; + assert_eq!(crossing(&lines), Some((Culvert, Source::Fallback))); + // A crossing at a shared vertex reads its arms by position: a far vertex changes nothing. + let shared = |far: bool| { + let mut street = vec![[0.0, -40.0], [0.0, 0.0], [0.0, 40.0]]; + if far { + street.insert(0, [-60.0, -120.0]); + } + let g = graph(&[ + road(&street, 0.0), + footway(&[[-40.0, -40.0], [0.0, 0.0], [40.0, 40.0]], 0.0), + stream(&[], &[[-40.0, 0.0], [0.0, 0.0], [40.0, 0.0]], 0.0), + ]); + let c = &g.crossings[0]; + (c.kind, c.source, c.angle_rad, class(&g, &g.junctions[0].arms[0])) + }; + assert_eq!(shared(false), shared(true)); + assert_eq!((shared(false).0, shared(false).2), (Culvert, core::f64::consts::FRAC_PI_2)); + // A path that shares a vertex with a stream fords it. + let g = graph(&[ + footway(&[[0.0, -40.0], [0.0, 0.0], [0.0, 40.0]], 0.0), + stream(&[], &[[-40.0, 0.0], [0.0, 0.0], [40.0, 0.0]], 0.0), + ]); + assert_eq!((g.crossings[0].kind, g.crossings[0].source), (Ford, Source::SharedVertex)); + // A culvert's mouth on a road vertex: a culvert, as one water arm there is in a tunnel. + let g = graph(&[ + road(&[[0.0, -40.0], [0.0, 0.0], [0.0, 40.0]], 0.0), + stream(&[], &[[-40.0, 0.0], [0.0, 0.0]], 0.0), + Line { z: vec![None, None], ..stream(&[("tunnel", "culvert")], &[[0.0, 0.0], [40.0, 0.0]], 0.0) }, + ]); + assert_eq!((g.crossings[0].kind, g.crossings[0].source), (Culvert, Source::SharedVertex)); + // A curved stream: the crossing is decided on its chord and placed where the curves cross. + let g = graph(&[ + road(&[[-30.0, -40.0], [-30.0, 60.0]], 0.0), + stream(&[], &[[-60.0, 20.0], [0.0, -10.0], [60.0, 20.0]], 0.0), + ]); + let c = &g.crossings[0]; + let on = |st: &Station| { + let part = &g.parts[st.part as usize]; + let (p, p0) = (point(part, st.span as usize, st.u), part.vertices[st.span as usize].pos); + [(p0[0] as f64 + p.d[0]) * mpu(), (p0[1] as f64 + p.d[1]) * mpu()] + }; + let (over, under) = (on(&c.over), on(&c.under)); + let d = [over[0] - under[0], over[1] - under[1]]; + let apart = (d[0] * d[0] + d[1] * d[1]).sqrt(); + assert!(apart < 0.05, "the stations lie where the curves cross: {apart} m apart"); + // Two roads at one height: an implicit junction, and a synthetic deck splits the upper road. + let g = graph(&[across(0.0), along("road", &[("highway", "residential")], 0.2)]); + assert!( + g.crossings.is_empty() && g.junctions.len() == 1 && g.junctions[0].implicit && g.junctions[0].arms.len() == 4 + ); + let g = graph(&[across(5.0), along("road", &[("highway", "residential")], 0.0)]); + let deck = &g.decks[0]; + assert!(deck.synthetic && g.ways[deck.ways[0] as usize].level == Level::Deck); + assert_eq!(g.joints.len(), 2, "the deck's two ends"); +} + +#[test] +fn the_ladder_follows_the_room_by_the_class_rows_at_every_boundary() { + use Step::*; + let upper = |kind, tags: &[(&'static str, &'static str)], z| line(kind, tags, &[[0.0, -40.0], [0.0, 40.0]], z); + let lower = |kind, tags: &[(&'static str, &'static str)], z| line(kind, tags, &[[-40.0, 0.0], [40.0, 0.0]], z); + let bridge = [("highway", "residential"), ("bridge", "yes"), ("deck", "1")]; + let footbridge = [("highway", "footway"), ("bridge", "yes"), ("deck", "0.4")]; + let street = [("highway", "residential")]; + let foot = [("highway", "footway")]; + let rail = [("railway", "rail")]; + let tunnel = [("highway", "residential"), ("tunnel", "yes")]; + let rail_tunnel = [("railway", "rail"), ("tunnel", "yes")]; + // (what, upper, lower, step, whether the upper way ends on step 3). A residential deck over a + // residential road: full 4.5 + 1.0, least 3.0 + 0.4; a residential bore: full 5.0 + 1.0, least + // 3.0 + 0.3; snap 0.5 everywhere. + type Row = (&'static str, Line, Line, Step, bool); + let rows: Vec = vec![ + ("deck, full", upper("road", &bridge, 5.5), lower("road", &street, 0.0), Full, false), + ("deck, thin", upper("road", &bridge, 5.45), lower("road", &street, 0.0), Thin, false), + ("deck, least", upper("road", &bridge, 3.4), lower("road", &street, 0.0), Thin, false), + ( + "deck, closed: the lower way of one class ends", + upper("road", &bridge, 3.35), + lower("road", &street, 0.0), + Closed, + false, + ), + ("deck, closed over snap", upper("road", &bridge, 0.55), lower("road", &street, 0.0), Closed, false), + ("deck, at grade", upper("road", &bridge, 0.5), lower("road", &street, 0.0), AtGrade, false), + ("deck, at grade under", upper("road", &bridge, -0.5), lower("road", &street, 0.0), AtGrade, false), + ("deck, inverted", upper("road", &bridge, -0.55), lower("road", &street, 0.0), Inverted, false), + ( + "footbridge over a railway, closed: the footway ends", + upper("path", &footbridge, 4.95), + lower("railway", &rail, 0.0), + Closed, + true, + ), + ( + "footbridge over a railway, least", + upper("path", &footbridge, 5.0), + lower("railway", &rail, 0.0), + Thin, + false, + ), + ( + "railway bridge over a road, closed: the road ends", + upper("railway", &[("railway", "rail"), ("bridge", "yes"), ("deck", "1")], 3.0), + lower("road", &street, 0.0), + Closed, + false, + ), + ("bore, full", upper("road", &street, 6.0), lower("tunnel", &tunnel, 0.0), Full, false), + ("bore, thin", upper("road", &street, 5.95), lower("tunnel", &tunnel, 0.0), Thin, false), + ("bore, least", upper("road", &street, 3.3), lower("tunnel", &tunnel, 0.0), Thin, false), + ( + "bore, closed: the tunnel way ends", + upper("road", &street, 3.25), + lower("tunnel", &tunnel, 0.0), + Closed, + false, + ), + ("bore, inverted", upper("road", &street, -0.55), lower("tunnel", &tunnel, 0.0), Inverted, false), + ( + "railway bore under a footway, closed: the railway ends", + upper("path", &foot, 5.05), + lower("tunnel", &rail_tunnel, 0.0), + Closed, + false, + ), + ]; + for (what, u, l, want, upper_ends) in rows { + let g = graph(&[u, l]); + let c = g.crossings.iter().find(|c| c.ladder.is_some()).unwrap_or_else(|| panic!("{what}: {:?}", g.crossings)); + let ladder = c.ladder.as_ref().unwrap(); + assert_eq!(ladder.step, want, "{what}: room {}", ladder.room_m); + if matches!(want, Closed | Inverted) { + let ends = if upper_ends { ladder.upper } else { ladder.lower }; + assert_eq!(ladder.ends, Some(ends), "{what}"); + } + } +} + +#[test] +fn a_deck_over_another_deck_lies_on_storey_2() { + // Two residential bridges, square to each other, the upper one 6 m over the lower: room for a full deck (4.5 + 1.0). + let bridge = [("highway", "residential"), ("bridge", "yes"), ("deck", "1")]; + let upper = line("road", &bridge, &[[0.0, -40.0], [0.0, 40.0]], 16.0); + let lower = line("road", &bridge, &[[-40.0, 0.0], [40.0, 0.0]], 10.0); + let lines = [upper, lower]; + let (g, input) = (graph(&lines), input_of(cell(), &lines)); + let found = super::level_tags::found(&g, &input, Sections::embedded()); + let key = |feature: usize| { + [input.features[feature].parts[0].tile.0, input.features[feature].parts[0].tile.1, feature as u32] + }; + assert_eq!(found.over, [(key(1), key(0))], "the lower bridge under the upper one"); + // The bake's merge, with the features' positions as their ids. + let ids = |k: [u32; 3]| k[2]; + let cells = BTreeMap::from_iter(found.found.into_iter().map(|(k, f)| (ids(k), vec![f]))); + let tags = super::level_tags::merge(&cells, &[], &[(1, 0)]); + let storey = |id: u32| tags.get(&id).and_then(|t| t.get(super::level_tags::STOREY)).cloned(); + assert_eq!((storey(0), storey(1)), (Some("2".to_string()), None)); +} + +#[test] +fn the_room_reads_each_way_on_its_own_curve() { + // A residential deck on a hairpin of radius 12 m over a road, both level: the room at every corner + // of the overlap is the height difference, though the hairpin's far leg passes within 24 m. + let arc: Vec<[f64; 2]> = (0..=12) + .map(|i| { + let a = core::f64::consts::PI * f64::from(i) / 12.0; + [12.0 * libm::cos(a) - 12.0, 12.0 * libm::sin(a) - 30.0] + }) + .collect(); + let mut points = vec![[0.0, -60.0]]; + points.extend(arc.iter().rev().map(|p| [p[0] + 24.0, -p[1] - 60.0])); + let deck = line("road", &[("highway", "residential"), ("bridge", "yes"), ("deck", "1")], &points, 6.0); + let road = line("road", &[("highway", "residential")], &[[-40.0, -40.0], [40.0, -40.0]], 0.0); + let g = graph(&[deck, road]); + for c in g.crossings.iter().filter_map(|c| c.ladder.as_ref()) { + assert!((c.room_m - 6.0).abs() < 0.05, "room {}", c.room_m); + assert_eq!(c.step, Step::Full); + } + assert!(g.crossings.iter().any(|c| c.ladder.is_some())); +} + +/// The states of a way's runs in order, and its end lines by kind and metres along it. +type WayLevels = (Vec, Vec<(EndKind, f64)>); + +/// The levels of the one tunnel way of a graph. +fn tunnel_levels(g: &WayGraph) -> WayLevels { + let tunnels: Vec<&Way> = g.ways.iter().filter(|w| w.level == Level::Tunnel).collect(); + assert_eq!(tunnels.len(), 1); + let w = tunnels[0]; + let states = g.levels.runs.iter().filter(|r| r.way == w.id).map(|r| r.state).collect(); + let at = |l: &EndLine| (l.kind, super::points::between(&g.parts, &w.from, &l.at)); + (states, g.levels.end_lines.iter().filter(|l| l.way == w.id).map(at).collect()) +} + +#[test] +fn a_tunnel_that_comes_in_over_the_terrain_is_open_from_its_tag_end_up_to_open_max_m() { + use EndKind::*; + use State::*; + // A residential way 3 m over flat terrain, a tunnel from x 0 to `len` through a ridge that rises `slope` per metre + // from each tag end. The bore needs the least room less the lift on free ground: 3.0 + 0.3 - 1.0 = 2.3 m of + // cover, at (3 + 2.3) / slope in from each end. On the steep ridge that lies within `open_max_m` (30 m): the way is + // open from its tag end, on its bank, to the portal. On the gentle one it lies past 30 m: open to 30 m, then + // closed. + let street = [("highway", "residential")]; + let tunnel = [("highway", "residential"), ("tunnel", "yes")]; + let cases: [(f64, f64, WayLevels); 2] = [ + (0.5, 80.0, (vec![Open, Bore, Open], vec![(Portal, 10.6), (Portal, 69.4)])), + ( + 0.1, + 160.0, + ( + vec![Open, Hidden, Bore, Hidden, Open], + vec![(Closed, 30.0), (Closed, 53.0), (Closed, 107.0), (Closed, 130.0)], + ), + ), + ]; + for (slope, len, (want_states, want_lines)) in cases { + let lines = [ + line("road", &street, &[[-60.0, 0.0], [0.0, 0.0]], 3.0), + line("tunnel", &tunnel, &[[0.0, 0.0], [len, 0.0]], 3.0), + line("road", &street, &[[len, 0.0], [len + 60.0, 0.0]], 3.0), + ]; + let g = graph_on(&lines, &|x, _| (slope * x.min(len - x)).max(0.0)); + let (states, lines) = tunnel_levels(&g); + assert_eq!(states, want_states, "slope {slope}: {lines:?}"); + assert_eq!(lines.len(), want_lines.len(), "slope {slope}: {lines:?}"); + for (got, want) in lines.iter().zip(&want_lines) { + assert!(got.0 == want.0 && (got.1 - want.1).abs() < 0.3, "slope {slope}: {got:?}, want {want:?}"); + } + } +} + +#[test] +fn a_paved_stroke_hides_a_tunnel_station_only_where_it_lies_on_top() { + // A residential tunnel with no cover on flat terrain between two roads at its height, and a residential road + // beside it from x 5 to 30, 2 m off its middle, so that the road's paved stroke covers the tunnel's middle line. + // Lower than the tunnel's floor, or within `snap_height_m` (0.5 m) over it, the road lies beside it and the tunnel + // is open along its whole length; higher, the road lies on top and hides the tunnel under its stroke. + let street = [("highway", "residential")]; + let tunnel = [("highway", "residential"), ("tunnel", "yes")]; + for (dz, hidden) in [(-2.0, false), (0.5, false), (0.55, true)] { + let lines = [ + line("road", &street, &[[-60.0, 0.0], [0.0, 0.0]], 0.0), + line("tunnel", &tunnel, &[[0.0, 0.0], [40.0, 0.0]], 0.0), + line("road", &street, &[[40.0, 0.0], [100.0, 0.0]], 0.0), + line("road", &street, &[[5.0, 2.0], [30.0, 2.0]], dz), + ]; + let g = graph_on(&lines, &|_, _| 0.0); + let (states, lines) = tunnel_levels(&g); + if hidden { + assert_eq!(states, [State::Open, State::Hidden, State::Open], "dz {dz}: {lines:?}"); + let (a, b) = (lines[0].1, lines[1].1); + assert!(a > 2.0 && a < 5.0 && b > 30.0 && b < 33.0, "dz {dz}: the road's stroke, {lines:?}"); + } else { + assert_eq!((states, lines), (vec![State::Open], Vec::new()), "dz {dz}"); + } + } +} + +#[test] +fn a_passage_through_a_building_of_kind_tunnel_lies_on_the_ground_and_a_tunnel_does_not() { + let level = |tunnel: &'static str| { + let l = line("tunnel", &[("highway", "residential"), ("tunnel", tunnel)], &[[-20.0, 0.0], [20.0, 0.0]], 500.0); + parts::classify(&feature(&l, cell().feature_tiles()[0], 0), Sections::embedded()).map(|c| c.2) + }; + assert_eq!(level("building_passage"), Some(Level::Ground)); + assert_eq!(level("yes"), Some(Level::Tunnel)); +} diff --git a/host/obc-ground-plan/src/lib.rs b/host/obc-ground-plan/src/lib.rs new file mode 100644 index 0000000000..47f49832ca --- /dev/null +++ b/host/obc-ground-plan/src/lib.rs @@ -0,0 +1,134 @@ +//! The TrailView ground plan of one cell: from the feature tiles about it, its stored terrain pages +//! and the rule tables to exact integer geometry, terrain heights and cross-sections. A pure +//! function of its inputs: integers, `libm` and ordered collections, no I/O and no threads. + +pub mod cell; +pub mod debug; +pub mod faces; +pub mod frame; +pub mod graph; +pub mod mesh; +pub mod probe; +pub mod sections; +pub mod terrain; +pub mod tile; +pub mod transport; + +use frame::{CellKey, GlobalPoint}; +use terrain::{StoredPage, Terrain}; +use tile::{own, DecodeError, Feature, Geometry, Part, TileCache}; + +/// The inputs of one cell: the parts of each read tile that meet the cell grown by its margin, with +/// `own` set, and the terrain under it. +#[derive(Clone, Debug)] +pub struct CellInput { + pub key: CellKey, + pub features: Vec, + pub terrain: Terrain, +} + +/// Whether the box of the points meets the closed square [x0, y0, x1, y1]. +fn box_meets(points: &[GlobalPoint], [x0, y0, x1, y1]: [i64; 4]) -> bool { + let lo = |f: fn(&GlobalPoint) -> i64| points.iter().map(f).min(); + let hi = |f: fn(&GlobalPoint) -> i64| points.iter().map(f).max(); + match (lo(|p| p.x), lo(|p| p.y), hi(|p| p.x), hi(|p| p.y)) { + (Some(a), Some(b), Some(c), Some(d)) => c >= x0 && a <= x1 && d >= y0 && b <= y1, + _ => false, + } +} + +impl CellInput { + /// The input of a cell from the tiles of `key.feature_tiles()`, in that order. `load` gives a + /// tile's bytes after gzip, or None: no features. Nothing is clipped. A point or a line part stays + /// when its box meets the grown cell and it owns an element; an area keeps every copy of each + /// polygon (an outer ring and its holes) whose outer ring's box meets the grown cell. + pub fn new( + key: CellKey, + cache: &mut TileCache, + mut load: impl FnMut(u32, u32) -> Option>, + pages: Vec, + ) -> Result { + let tiles = key.feature_tiles(); + let grown = key.grown(); + let mut features = Vec::new(); + for (at, &(column, row)) in tiles.iter().enumerate() { + for feature in cache.tile(column, row, || load(column, row))?.iter() { + let mut parts = Vec::new(); + let mut polygon_kept = false; + // The box test comes first: most parts of the tile lie outside the grown cell. + for part in &feature.parts { + let meets = match feature.geometry { + Geometry::Area => { + if part.outer { + polygon_kept = box_meets(&part.points, grown); + } + polygon_kept + } + Geometry::Point | Geometry::Line => box_meets(&part.points, grown), + }; + if !meets { + continue; + } + let own = own(feature.geometry, &part.points, &tiles, at); + if feature.geometry == Geometry::Area || own.iter().any(|&own| own) { + parts.push(Part { own, ..part.clone() }); + } + } + if !parts.is_empty() { + let Feature { index, kind, tags, geometry, .. } = feature; + features.push(Feature { + index: *index, + kind: kind.clone(), + tags: tags.clone(), + geometry: *geometry, + parts, + }); + } + } + } + Ok(CellInput { key, features, terrain: Terrain::new(key, pages) }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use frame::tile_point; + + fn tile_bytes() -> Vec { + std::fs::read( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../specs/vectors/trailview-features.bin"), + ) + .unwrap() + } + + #[test] + fn neighbouring_cells_load_a_tile_once_and_a_small_cache_changes_nothing() { + let origin = tile_point(13, 4286, 2888, false, 0, 0); + let key = |dx: i64| { + CellKey::of(GlobalPoint { x: origin.x + dx * frame::CELL_UNITS, y: origin.y + 3 * frame::CELL_UNITS }) + }; + let mut loads = Vec::new(); + let mut cache = TileCache::new(16); + let build = |cache: &mut TileCache, key: CellKey, loads: &mut Vec<(u32, u32)>| { + CellInput::new( + key, + cache, + |c, r| { + loads.push((c, r)); + ((c, r) == (4286, 2888)).then(tile_bytes) + }, + Vec::new(), + ) + .unwrap() + }; + let (a, b) = (build(&mut cache, key(3), &mut loads), build(&mut cache, key(4), &mut loads)); + assert_eq!(loads, [(4286, 2888)], "two cells in the tile's middle read it once"); + assert!(!a.features.is_empty() && !b.features.is_empty()); + let mut small = TileCache::new(1); + for k in [key(0), key(3), key(-1), key(0)] { + let (big, little) = (build(&mut cache, k, &mut Vec::new()), build(&mut small, k, &mut Vec::new())); + assert_eq!(format!("{:?}", big.features), format!("{:?}", little.features)); + } + } +} diff --git a/host/obc-ground-plan/src/mesh/cdt.rs b/host/obc-ground-plan/src/mesh/cdt.rs new file mode 100644 index 0000000000..9710989323 --- /dev/null +++ b/host/obc-ground-plan/src/mesh/cdt.rs @@ -0,0 +1,98 @@ +//! One constrained Delaunay triangulation of D: a single bulk load of every point and constraint, no +//! refinement, then a flood fill that gives each triangle the face that holds it. +//! +//! Every point is an integer in frame units, exact in f64, and spade's predicates are exact, so +//! native and WASM builds give the same triangles. + +use spade::handles::FixedVertexHandle; +use spade::{ConstrainedDelaunayTriangulation, Point2, Triangulation}; + +use super::points::P; +use super::MeshError; + +type Cdt = ConstrainedDelaunayTriangulation>; + +/// The side of a constraint that lies in D with no face named: D's border. +pub const INSIDE: u32 = u32::MAX - 1; +/// The side outside D, and a triangle outside D. +pub const OUTSIDE: u32 = crate::faces::OUTSIDE; +/// A triangle that no seed reached yet. +const UNSET: u32 = u32::MAX - 2; + +/// D's triangles with their classes, and the count of face-edge pieces split at a point on them. +pub type Triangles = (Vec<([u32; 3], u32)>, u32); + +/// A constraint from point a to point b, with the class of the triangles on each side: a face of the +/// plan, `INSIDE` or `OUTSIDE`. `left` is the side where the shoelace sum of (a, b, point) is +/// positive. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Segment { + pub a: u32, + pub b: u32, + pub left: u32, + pub right: u32, +} + +/// The triangles of D: point indices turning as the terrain's `gridIndices` (negative signed area in +/// x east, y south), and the class of each: the face of a face edge that bounds its region, else +/// `INSIDE`. A face edge names the faces; D's border, given after them, only parts D from the rest. +/// Also the count of face-edge pieces that the triangulation split at a point on them. +pub fn triangulate(points: &[P], segments: &[Segment], edges: usize) -> Result { + let vertices: Vec> = points.iter().map(|p| Point2::new(f64::from(p[0]), f64::from(p[1]))).collect(); + let pairs: Vec<[usize; 2]> = segments.iter().filter(|s| s.a != s.b).map(|s| [s.a as usize, s.b as usize]).collect(); + let mut conflict = None; + let cdt = Cdt::try_bulk_load_cdt(vertices, pairs, |e| { + conflict.get_or_insert(e); + }) + .map_err(|e| MeshError::InvalidPlan { at: points.first().copied().unwrap_or_default(), why: format!("{e:?}") })?; + if let Some([a, b]) = conflict { + return Err(MeshError::InvalidPlan { + at: points[a], + why: format!("constraint {:?}-{:?} crosses another", points[a], points[b]), + }); + } + let mut class = vec![UNSET; cdt.num_all_faces()]; + let mut stack = Vec::new(); + let mut split = 0; + for (k, range) in [0..edges, edges..segments.len()].into_iter().enumerate() { + for s in &segments[range] { + let Some(e) = cdt.get_edge_from_neighbors( + FixedVertexHandle::from_index(s.a as usize), + FixedVertexHandle::from_index(s.b as usize), + ) else { + split += u32::from(k == 0 && s.a != s.b); + continue; + }; + for (face, c) in [(e.face(), s.left), (e.rev().face(), s.right)] { + if let Some(f) = face.as_inner() { + if class[f.index()] == UNSET { + class[f.index()] = c; + stack.push(f.fix()); + } + } + } + } + while let Some(f) = stack.pop() { + let c = class[f.index()]; + for e in cdt.face(f).adjacent_edges() { + if e.is_constraint_edge() { + continue; + } + if let Some(g) = e.rev().face().as_inner() { + if class[g.index()] == UNSET { + class[g.index()] = c; + stack.push(g.fix()); + } + } + } + } + } + let tris = (cdt.inner_faces()) + .filter(|f| !matches!(class[f.index()], OUTSIDE | UNSET)) + .map(|f| { + let v = f.vertices().map(|v| v.fix().index() as u32); + ([v[0], v[2], v[1]], class[f.index()]) + }) + .collect(); + Ok((tris, split)) +} diff --git a/host/obc-ground-plan/src/mesh/check.rs b/host/obc-ground-plan/src/mesh/check.rs new file mode 100644 index 0000000000..f3b942845a --- /dev/null +++ b/host/obc-ground-plan/src/mesh/check.rs @@ -0,0 +1,281 @@ +//! The checks of a cell's mesh: valid topology, labels as the records give them, and two cells alike +//! on their shared line. + +use std::collections::BTreeMap; + +use super::params::GRID; +use super::region::grid_of; +use super::{CellMesh, NO_LABEL}; +use crate::faces::heights::height_at; +use crate::faces::records::{find, label}; +use crate::faces::HeightRule; +use crate::frame::{CellKey, GlobalPoint, CELL_UNITS}; +use crate::terrain::Terrain; + +fn area(p: [[i32; 2]; 3]) -> i64 { + let d = |a: [i32; 2], b: [i32; 2]| [i64::from(b[0] - a[0]), i64::from(b[1] - a[1])]; + let (u, v) = (d(p[0], p[1]), d(p[0], p[2])); + u[0] * v[1] - u[1] * v[0] +} + +/// The faults of a mesh's topology: a triangle that does not turn as `gridIndices` or has no area, a +/// directed edge used twice, an edge with one triangle off the cell's lines that is not an edge of +/// the terrain grid between two terrain vertices (on ∂R, or the diagonal of a terrain ear). +pub fn validity(mesh: &CellMesh) -> Vec { + let mut faults = Vec::new(); + let mut edges: BTreeMap<([i32; 2], [i32; 2]), u32> = BTreeMap::new(); + for (k, t) in mesh.triangles.iter().enumerate() { + let p = t.map(|c| mesh.corner(c as usize).0); + if area(p) >= 0 { + faults.push(format!("triangle {k} at {p:?} turns the wrong way or has no area")); + } + for i in 0..3 { + *edges.entry((p[i], p[(i + 1) % 3])).or_default() += 1; + } + } + let c = CELL_UNITS as i32; + let on_line = |a: [i32; 2], b: [i32; 2]| (0..2).any(|i| a[i] == b[i] && (a[i] == 0 || a[i] == c)); + // ∂R: the terrain vertices. + let mut boundary: Vec<[i32; 2]> = + (0..mesh.corners.len()).map(|k| mesh.corner(k)).filter(|c| c.2).map(|c| c.0).collect(); + boundary.sort_unstable(); + let on_boundary = |p: &[i32; 2]| boundary.binary_search(p).is_ok(); + let grid_edge = |a: [i32; 2], b: [i32; 2]| { + let d = [b[0] - a[0], b[1] - a[1]]; + d[0].abs() + d[1].abs() == GRID || (d[0].abs() == GRID && d[0] == -d[1]) + }; + for (&(a, b), &n) in &edges { + if n > 1 { + faults.push(format!("edge {a:?}-{b:?} used {n} times")); + } + if !edges.contains_key(&(b, a)) && !on_line(a, b) && !(on_boundary(&a) && on_boundary(&b) && grid_edge(a, b)) { + faults.push(format!("edge {a:?}-{b:?} has one triangle")); + } + } + faults +} + +/// The records and the face plan may differ this near a face edge: the slice's snap (GP3R's own +/// check allows 8 units). +const EDGE_UNITS: f64 = 8.0; + +/// What `labels` counts: triangles whose label is not the records' at their centroid (sharp ones +/// with the face's label, ground ones with a ground label), where the centroid lies farther than +/// `EDGE_UNITS` from the triangle's sides; ground corners at grid points with no other corner (off +/// every face edge between two labels) whose label is not the records' there (`ground_wrong`), or +/// another ground label (`ground_other`: a point on an edge between two ground faces, whose heights +/// agree). `sharp_wrong` holds GP3R's known misses, where the records decide a patch apart from the +/// face plan (a crossing over a rail bed): the mesh takes the face plan's label. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Labels { + pub sharp_wrong: u64, + pub ground_wrong: u64, + pub ground_other: u64, + /// The first places of the wrong ones. + pub first: Vec, +} + +fn is_ground(words: &[u32], l: u32) -> bool { + l == NO_LABEL || label(words, l)[0] >> 24 <= HeightRule::Slope as u32 +} + +/// The labels of a mesh against `records::find` in the block it was built with. +pub fn labels(mesh: &CellMesh, words: &[u32]) -> Labels { + let mut out = Labels::default(); + let mut points: Vec<[i32; 2]> = (0..mesh.corners.len()).map(|k| mesh.corner(k).0).collect(); + points.sort_unstable(); + let alone = |p: [i32; 2]| points.partition_point(|q| *q <= p) - points.partition_point(|q| *q < p) == 1; + let found = |q: [f64; 2]| find(words, q).unwrap_or(NO_LABEL); + let wrong = |out: &mut Labels, what: &str, q: [f64; 2], l: u32, f: u32| { + if out.first.len() < 8 { + out.first.push(format!("{what} at {q:?}: {l}, the records {f}")); + } + }; + for t in &mesh.triangles { + let c = t.map(|k| mesh.corner(k as usize)); + let p = c.map(|c| [f64::from(c.0[0]), f64::from(c.0[1])]); + let mid = [(p[0][0] + p[1][0] + p[2][0]) / 3.0, (p[0][1] + p[1][1] + p[2][1]) / 3.0]; + let inner = (0..3) + .map(|i| { + let (a, b) = (p[i], p[(i + 1) % 3]); + let e = [b[0] - a[0], b[1] - a[1]]; + ((mid[0] - a[0]) * e[1] - (mid[1] - a[1]) * e[0]).abs() / libm::hypot(e[0], e[1]) + }) + .fold(f64::INFINITY, f64::min); + let sharp = c.iter().all(|c| !c.2 && !is_ground(words, c.1)); + if inner > EDGE_UNITS { + let f = found(mid); + let bad = if sharp { c[0].1 != f } else { !is_ground(words, f) }; + if bad { + *(if sharp { &mut out.sharp_wrong } else { &mut out.ground_wrong }) += 1; + wrong(&mut out, if sharp { "sharp triangle" } else { "ground triangle" }, mid, c[0].1, f); + } + } + if sharp { + continue; + } + for (i, c) in c.iter().enumerate() { + if c.2 || grid_of(c.0).is_none() || !alone(c.0) { + continue; + } + let f = found(p[i]); + if f != c.1 && is_ground(words, f) { + out.ground_other += 1; + } else if f != c.1 { + out.ground_wrong += 1; + wrong(&mut out, "ground corner", p[i], c.1, f); + } + } + } + out +} + +/// A cell's mesh with the block and terrain that it reads, for `border`. +pub struct Cell<'a> { + pub key: CellKey, + pub mesh: &'a CellMesh, + pub words: &'a [u32], + pub terrain: &'a Terrain, +} + +/// The distinct heights of a cell's corners on one of its lines, by place along it, as bits; a +/// terrain vertex as `None`. +fn on_line(cell: &Cell, vertical: bool, at: i32) -> BTreeMap>> { + let mut out: BTreeMap>> = BTreeMap::new(); + let o = cell.key.origin(); + for k in 0..cell.mesh.corners.len() { + let (p, l, terrain) = cell.mesh.corner(k); + let (along, across) = if vertical { (p[1], p[0]) } else { (p[0], p[1]) }; + if across != at { + continue; + } + let h = (!terrain).then(|| { + let t = cell.terrain.height(GlobalPoint { x: o.x + i64::from(p[0]), y: o.y + i64::from(p[1]) }); + let label = (l != NO_LABEL).then_some(l); + t.map_or(u64::MAX, |t| height_at(cell.words, [f64::from(p[0]), f64::from(p[1])], label, t).h.to_bits()) + }); + out.entry(along).or_default().push(h); + } + for v in out.values_mut() { + v.sort_unstable(); + v.dedup(); + } + out +} + +/// The places on the shared line of cell `b`, east (`east`) or south of `a`, where the two cells' +/// corners differ in place, flag or height bits, and the count of places where one cell holds a +/// further corner within `SUB_MM` of a height of both (two labels whose heights GP6 joins). A +/// terrain vertex may stand in one cell alone: the other's cell beside it lies outside R. +pub fn border(a: &Cell, b: &Cell, east: bool) -> (Vec, u32) { + let (x, y) = (on_line(a, east, CELL_UNITS as i32), on_line(b, east, 0)); + let terrain_only = |v: Option<&Vec>>| v.is_none_or(|v| v.iter().all(Option::is_none)); + let (mut out, mut sub_mm) = (Vec::new(), 0); + let mut alongs: Vec = x.keys().chain(y.keys()).copied().collect(); + alongs.sort_unstable(); + alongs.dedup(); + for along in alongs { + let (p, q) = (x.get(&along), y.get(&along)); + if p == q || (p.is_none() && terrain_only(q)) || (q.is_none() && terrain_only(p)) { + continue; + } + let (p, q) = (p.cloned().unwrap_or_default(), q.cloned().unwrap_or_default()); + let shared: Vec = p.iter().filter(|h| q.contains(h)).flatten().map(|&h| f64::from_bits(h)).collect(); + let near = |h: &Option| h.is_some_and(|h| shared.iter().any(|s| (f64::from_bits(h) - s).abs() <= SUB_MM)); + if !shared.is_empty() && p.iter().chain(&q).filter(|h| !(p.contains(h) && q.contains(h))).all(near) { + sub_mm += 1; + } else { + out.push(format!("{:?}|{:?} at {along}: heights {p:?} and {q:?}", a.key, b.key)); + } + } + (out, sub_mm) +} + +/// GP6 joins two sides whose heights differ by at most `heights.step_m` (1 mm). +const SUB_MM: f64 = 0.001; + +/// Within this many units of a deck end line, a slot's ends lie on it (`faces` rounds the stroke's corners). +const END_UNITS: f64 = 2.0; +/// The ground near a deck end line that `deck_ends` reads: within this many metres of it. +pub const NEAR_END_M: f64 = 3.0; + +/// A ground triangle is steeper than `face_max` past this share of it: a face at `face_max` (the ceiling's rise +/// past a deck's stroke) gives a plane a hair steeper. +const STEEP_SHARE: f64 = 1.01; + +/// The deck ends of a cell's mesh: the end faces that lie on no deck end line of the records +/// (`heights::check::end_lines`), the slots that lie on one but are not end faces, and the ground triangles +/// within `NEAR_END_M` of an end line steeper than `face_max` where the plain terrain is not, with their +/// steepness. +pub fn deck_ends( + mesh: &CellMesh, + words: &[u32], + terrain: &Terrain, + cell: CellKey, +) -> (Vec, Vec, Vec) { + use crate::faces::heights::{check::end_lines, HeightRules}; + let ends = end_lines(words); + let (mut stray, mut missed, mut steep) = (Vec::new(), Vec::new(), Vec::new()); + if ends.is_empty() && mesh.end_faces == 0 { + return (stray, missed, steep); + } + let at = |c: u32| mesh.corner(c as usize).0.map(f64::from); + let on = |q: [f64; 2]| { + ends.iter().any(|e| { + let [along, across] = e.place(q); + along.abs() <= END_UNITS && across.abs() <= e.half + END_UNITS + }) + }; + let first = mesh.steps.len() - mesh.end_faces as usize; + for (k, s) in mesh.steps.iter().enumerate() { + match (on(at(s[0])) && on(at(s[1])), k >= first) { + (false, true) => stray.push(format!("end face {k} at {:?} on no end line", at(s[0]))), + (true, false) => missed.push(format!("slot {k} at {:?} on an end line", at(s[0]))), + _ => {} + } + } + let o = cell.origin(); + let p = HeightRules::of(words); + let rule = |l: u32| if l == NO_LABEL { 0 } else { label(words, l)[0] >> 24 }; + let mpu = crate::frame::metres_per_unit(o.y + CELL_UNITS / 2); + let near = |q: [f64; 2]| { + ends.iter().any(|e| { + let [along, across] = e.place(q); + libm::hypot(along, (across.abs() - e.half).max(0.0)) * mpu <= NEAR_END_M + }) + }; + for t in &mesh.triangles { + let corners = t.map(|c| mesh.corner(c as usize)); + if corners.iter().any(|&(_, l, terrain)| !terrain && rule(l) > 1) { + continue; + } + let q = corners.map(|(p, ..)| p.map(f64::from)); + if !near([(q[0][0] + q[1][0] + q[2][0]) / 3.0, (q[0][1] + q[1][1] + q[2][1]) / 3.0]) { + continue; + } + let plain = |p: [f64; 2]| terrain.height(GlobalPoint { x: o.x + p[0] as i64, y: o.y + p[1] as i64 }); + let Some(t) = q.iter().map(|&p| plain(p)).collect::>>() else { continue }; + let h: Vec = (0..3) + .map(|k| { + let (_, l, vertex) = corners[k]; + if vertex { + t[k] + } else { + height_at(words, q[k], (l != NO_LABEL).then_some(l), t[k]).h + } + }) + .collect(); + // The plane's rise per metre through three points. + let grade = |z: &[f64]| { + let (u, v) = ([q[1][0] - q[0][0], q[1][1] - q[0][1]], [q[2][0] - q[0][0], q[2][1] - q[0][1]]); + let (du, dv) = (z[1] - z[0], z[2] - z[0]); + let det = u[0] * v[1] - u[1] * v[0]; + libm::hypot(du * v[1] - dv * u[1], dv * u[0] - du * v[0]) / det.abs() / mpu + }; + let (g, gt) = (grade(&h), grade(&t)); + if g > STEEP_SHARE * p.face_max && gt <= p.face_max { + steep.push(format!("ground triangle at {:?}: {g:.3} m/m, terrain {gt:.3}, heights {h:.3?}", q[0])); + } + } + (stray, missed, steep) +} diff --git a/host/obc-ground-plan/src/mesh/mod.rs b/host/obc-ground-plan/src/mesh/mod.rs new file mode 100644 index 0000000000..4fa5fc5296 --- /dev/null +++ b/host/obc-ground-plan/src/mesh/mod.rs @@ -0,0 +1,672 @@ +//! The near mesh of a cell: its sharp faces, one ring of ground about them and the strip that meets +//! the terrain grid, as flat 2D topology for the GPU. The CPU builds no height: the GPU gives each +//! corner its height, look fields and normal from the one height function (`terrain/heights.wgsl` +//! with the corner's label), once per cell. +//! +//! The stages: R and its strip S from the sharp faces' region cells of the cell and its neighbours +//! (`region`, `Reads`); the points and constraints of D = (R ∖ S) ∩ cell (`points`); one bulk-loaded +//! constrained Delaunay triangulation with a flood fill for each triangle's face (`cdt`); the strip, a +//! fixed fan of each strip cell (`strip`); then the corners and the step slots. +//! +//! The grid is that of the terrain's nodes of `params::MESH_LEVEL`, and a region cell is a grid cell +//! of the level above (2 × 2 grid cells). +//! +//! A corner is a point with a label. A sharp face's triangles take the face's label; a ground +//! triangle takes at each point the point's one ground corner, labelled by the ground face that holds +//! the point (the face's label is `records::find`'s there). So every face edge between two labels has +//! the two corners of each side at its ends, and its step slot closes it at any heights. +//! +//! # Bytes (`CellMesh::to_bytes`), little-endian u32 words +//! +//! | Words | Holds | +//! | --- | --- | +//! | head | `HEAD` words: `MAGIC`, the cell's x and y (zoom 16), the counts of corners, triangles, strip triangles, triangle runs, step slots and step runs, of the last triangle runs that draw only over level-18 nodes, of the last step slots, the end faces, and of the culvert mouths | +//! | corners | 2 words each (below), sorted by point (y, then x) | +//! | triangle runs | 2 words each: the run's count of triangles and its base corner | +//! | triangles | 3 u16 each, the run's base subtracted, turning as the terrain's `gridIndices` (negative signed area in x east, y south); the strip's triangles last, and last of all, in runs of their own, the strip's triangles of halves that the level-17 terrain draws (`strip`); a zero u16 pads an odd count of u16 | +//! | step runs | 2 words each, as the triangle runs | +//! | steps | 4 u16 each, the run's base subtracted: `a_p, a_q, b_q, b_p` (below); the slots on a deck end line (`EdgeKind::DeckEdge`) last, in runs of their own: the end faces | +//! | region | `REGION_WORDS` words: R on the cell and one ring of region cells, bit (cy + 1) × (`CELLS` + 2) + cx + 1 for region cell (cx, cy) of the cell, −1 ≤ cx, cy ≤ `CELLS` | +//! | mouths | 4 words each: the corners of a culvert mouth's model (below), the zone outline's unit direction there (`pack2x16snorm`, x east, y south) and the water's half-width (f32, m) | +//! +//! A run is a stretch of triangles (or slots) whose corners lie within 65,536 of its base: draw it +//! with `baseVertex` = the base (`drawIndexed` with 16-bit indices), and a slot run with its base from +//! the run table. +//! +//! A corner: word 0 holds x in bits 0–18 and the label's bits 0–12 in bits 19–31; word 1 holds y in +//! bits 0–18, the label's bits 13–24 in bits 19–30 and the terrain-vertex flag in bit 31. x and y are +//! frame units from the cell's origin (x east, y south), 0 to 2^18. The label indexes the labels of +//! the cell's near records (the block built with the faces); `NO_LABEL` is the terrain rule (the plain +//! terrain). A terrain vertex is a grid point on ∂R: it draws with the terrain's own vertex code +//! (`vertex_place`, `place_height`), so it slides, morphs and takes the page's height as the terrain +//! grid does; its label is `NO_LABEL`. +//! +//! A step slot stands on a face-edge piece p → q between two labels: a holds the corners at p and q of +//! the face left of p → q (where the shoelace sum of (p, q, point) is positive), b those of the face +//! right of it. Draw every slot as two triangles on its four corners every frame: each edge that it +//! shares with a face or a neighbour slot is that edge exactly, so no pixel falls between them at any +//! heights. Where h(a) − h(b) changes sign between p and q, the diagonal joins the lower corners at p +//! and q, so the fold hangs below both faces; a slot of equal heights covers no pixel. A slot faces its +//! lower side, so it draws without back-face culling or turns toward that side; the step's look (kerb +//! or wall) comes from the two labels and the step's height, an end face's from its place in the slots. +//! +//! A culvert mouth (`faces::CulvertMouth`) whose point lies in the cell has two corners in no triangle, `MOUTH_M` +//! from the point on the water's middle line: one on the water, one in the zone. The GPU gives them their heights +//! as every corner's, and the mouth's model stands on them (`plan/piece.wgsl`). +//! +//! # Sunk points +//! +//! A grid point (i, j) of the cell, 0 ≤ i, j ≤ 2 · `CELLS`, is sunk when every region cell that +//! touches it is in R: cells ⌊(i − 1) / 2⌋ to ⌊i / 2⌋ across, the same for j down (two cells on an +//! even line, one between; in WGSL `(i - 1) >> 1`, as `/` truncates −1 / 2 to 0). The terrain draws a +//! sunk vertex far below the mesh. Every terrain triangle inside R then has a sunk corner, or all +//! three corners on ∂R: a strip ear at a north-west or south-east convex corner of R, which the +//! terrain draws and the strip leaves out. So the terrain never shows through the mesh +//! and needs no floors. "Far" is more than the ground can change over one region cell (a kilometre is +//! safe). +//! +//! The same holds over a level-17 node, whose vertices are the even grid points: the strip draws there +//! as at morph 1 and leaves out each half of a strip cell that is a terrain triangle of level 17 +//! (`strip`). It needs the terrain's vertices off their morph to level 16 and without the snap to road +//! edges (`vertex_place` with the snap on moves a vertex up to 15/16 of a grid cell), so the terrain +//! sinks a point only where the cell's mesh draws whole. + +pub mod cdt; +pub mod check; +pub mod params; +pub mod points; +pub mod region; +pub mod shell; +pub mod strip; + +use crate::faces::records::find; +use crate::faces::{Face, FacePlan, Surface}; +use crate::frame::{metres_per_unit, CellKey, CELL_UNITS}; +use params::{sharp, SIDE}; +use region::{grid_of, Region, MARK_WORDS}; + +pub use region::REGION_WORDS; + +/// "OBM" and the layout's version. +pub const MAGIC: u32 = 0x4f42_4d05; +pub const HEAD: usize = 12; +/// A culvert mouth's corners lie this far from its point, on the water and in the zone (metres). +pub const MOUTH_M: f64 = 0.1; +/// The label of a corner of the terrain rule. +pub const NO_LABEL: u32 = (1 << 25) - 1; +/// A corner's key: its label, and this bit for a terrain vertex. +const TERRAIN_VERTEX: u32 = 1 << 25; +const NONE: u32 = u32::MAX; + +#[derive(Clone, Debug, PartialEq)] +pub enum MeshError { + /// Two constraints cross: a fault in the faces. The place in frame units from the cell's origin. + InvalidPlan { at: [i32; 2], why: String }, + /// The corners of one triangle or slot span more than 16 bits of index: the corner order failed. + Wide, +} + +/// What a cell's neighbours read of it: its sharp marks (`region::sharp_cells`) and the coordinates +/// along its north, east, south and west lines of its plan vertices on them. +#[derive(Clone, Debug, PartialEq)] +pub struct Rim { + pub cell: CellKey, + pub sharp: Vec, + pub lines: [Vec; 4], +} + +impl Rim { + pub fn of(plan: &FacePlan) -> Rim { + let c = CELL_UNITS as i32; + let mut lines: [Vec; 4] = Default::default(); + for p in &plan.vertices { + for (side, on, along) in + [(0, p[1] == 0, p[0]), (1, p[0] == c, p[1]), (2, p[1] == c, p[0]), (3, p[0] == 0, p[1])] + { + if on { + lines[side].push(along); + } + } + } + for l in &mut lines { + l.sort_unstable(); + l.dedup(); + } + Rim { cell: plan.cell, sharp: region::sharp_cells(plan), lines } + } + + /// x, y, the sharp marks as pairs of words (low first), then per line its count and coordinates. + pub fn to_words(&self) -> Vec { + let mut out = vec![self.cell.x, self.cell.y]; + out.extend(self.sharp.iter().flat_map(|&w| [w as u32, (w >> 32) as u32])); + for l in &self.lines { + out.push(l.len() as u32); + out.extend(l.iter().map(|&v| v as u32)); + } + out + } + + /// The rims of a run of `to_words`. + pub fn from_words(mut w: &[u32]) -> Result, String> { + let mut out = Vec::new(); + while !w.is_empty() { + let short = || "a rim's words end early".to_string(); + let marks = w.get(2..2 + 2 * MARK_WORDS).ok_or_else(short)?; + let sharp = marks.chunks(2).map(|p| u64::from(p[0]) | u64::from(p[1]) << 32).collect(); + let mut at = 2 + 2 * MARK_WORDS; + let mut lines: [Vec; 4] = Default::default(); + for l in &mut lines { + let n = *w.get(at).ok_or_else(short)? as usize; + *l = w.get(at + 1..at + 1 + n).ok_or_else(short)?.iter().map(|&v| v as i32).collect(); + at += 1 + n; + } + out.push(Rim { cell: CellKey { x: w[0], y: w[1] }, sharp, lines }); + w = &w[at..]; + } + Ok(out) + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MeshStats { + /// Level-17 cells of the cell in R, S and D. + pub cells: [u32; 3], + pub points: u32, + pub grid_points: u32, + pub corners: u32, + pub triangles: u32, + pub strip_triangles: u32, + /// Strip triangles that draw only over level-18 nodes. + pub level18_triangles: u32, + pub steps: u32, + /// Sharp faces' edges outside D, sharp faces with no label in the records, and face-edge pieces + /// that the triangulation split at a point on them: none expected. + pub outside_d: u32, + pub unlabelled: u32, + pub split_edges: u32, +} + +/// The stages of `mesh_cell` in their order: `CellMesh::times` holds one time per stage. +pub const STAGES: [&str; 3] = ["points", "triangulation", "corners"]; + +/// A cell's near mesh: see the module's bytes. The triangles and steps hold whole corner indices, +/// in the order of their runs. +#[derive(Clone, Debug, PartialEq)] +pub struct CellMesh { + pub cell: CellKey, + pub corners: Vec<[u32; 2]>, + pub triangles: Vec<[u32; 3]>, + pub strip_triangles: u32, + pub triangle_runs: Vec<[u32; 2]>, + /// The last runs of `triangle_runs`, which draw only over level-18 nodes. + pub level18_runs: u32, + pub steps: Vec<[u32; 4]>, + pub step_runs: Vec<[u32; 2]>, + /// The last slots of `steps`: the end faces. + pub end_faces: u32, + pub region: Vec, + pub mouths: Vec<[u32; 4]>, + pub stats: MeshStats, + pub times: Vec, +} + +/// Indices less a run's base, two u16 to a word, low first; a zero pads an odd count. +fn packed(items: &[[u32; K]], runs: &[[u32; 2]]) -> Vec { + let bases = runs.iter().flat_map(|&[count, base]| std::iter::repeat_n(base, count as usize)); + let short: Vec = items.iter().zip(bases).flat_map(|(t, base)| t.map(|c| c - base)).collect(); + short.chunks(2).map(|p| p[0] | p.get(1).map_or(0, |&h| h << 16)).collect() +} + +/// Cuts a list of triangles or slots into runs: each the longest stretch from its start whose +/// corners lie within 65,536 of its least corner, the base. +fn runs(items: &[[u32; K]]) -> Result, MeshError> { + let mut out: Vec<[u32; 2]> = Vec::new(); + let mut top = 0; + for t in items { + let (lo, hi) = (*t.iter().min().unwrap(), *t.iter().max().unwrap()); + if hi - lo > u32::from(u16::MAX) { + return Err(MeshError::Wide); + } + match out.last_mut() { + Some(run) if hi.max(top) - lo.min(run[1]) <= u32::from(u16::MAX) => { + run[0] += 1; + run[1] = run[1].min(lo); + top = top.max(hi); + } + _ => { + out.push([1, lo]); + top = hi; + } + } + } + Ok(out) +} + +impl CellMesh { + pub fn to_bytes(&self) -> Vec { + let head = [ + MAGIC, + self.cell.x, + self.cell.y, + self.corners.len() as u32, + self.triangles.len() as u32, + self.strip_triangles, + self.triangle_runs.len() as u32, + self.steps.len() as u32, + self.step_runs.len() as u32, + self.level18_runs, + self.end_faces, + self.mouths.len() as u32, + ]; + let words = head + .into_iter() + .chain(self.corners.iter().flatten().copied()) + .chain(self.triangle_runs.iter().flatten().copied()) + .chain(packed(&self.triangles, &self.triangle_runs)) + .chain(self.step_runs.iter().flatten().copied()) + .chain(packed(&self.steps, &self.step_runs)) + .chain(self.region.iter().copied()) + .chain(self.mouths.iter().flatten().copied()); + words.flat_map(u32::to_le_bytes).collect() + } + + /// A corner's point, label (`NO_LABEL` for the terrain rule) and terrain-vertex flag. + pub fn corner(&self, k: usize) -> ([i32; 2], u32, bool) { + let [w0, w1] = self.corners[k]; + let mask = (1 << 19) - 1; + ([(w0 & mask) as i32, (w1 & mask) as i32], w0 >> 19 | (w1 >> 19 & 0xfff) << 13, w1 >> 31 == 1) + } +} + +/// The labels of a plan's faces in a block: the label whose words match the face's (surface, owner, +/// rank, rule, material and crossing lines, each the line of its way's leg, or on a storey over the ground the +/// line of that storey); none for terrain. +pub fn face_labels(faces: &[Face], words: &[u32]) -> Vec> { + use crate::faces::records::{owner, JUNCTION, LABEL, LEG_SHIFT, LINE, PLATFORM, STOREY, TERRAIN, WAY_OWNER}; + use crate::faces::{Owner, Surface}; + let (labels, lines) = (words[2] as usize, words[3] as usize); + let line_of = |way: Option, leg: u8, level: i8| { + let (flag, leg) = if level != 0 { (STOREY, u32::from(level as u8)) } else { (0, u32::from(leg)) }; + way.map_or(u32::MAX, |w| { + let at = |l: usize| &words[words[6] as usize + LINE * l..]; + (0..lines) + .find(|&l| at(l)[0] == w && at(l)[1] & STOREY == flag && (at(l)[1] >> LEG_SHIFT) & 0xff == leg) + .map_or(u32::MAX, |l| l as u32) + }) + }; + faces + .iter() + .map(|f| { + if f.surface == Surface::Terrain { + return None; + } + let (kind, id) = match f.owner { + Owner::Terrain => (TERRAIN, 0), + Owner::Way(w) => (WAY_OWNER, w), + Owner::Junction(j) => (JUNCTION, j), + Owner::Platform(p) => (PLATFORM, p), + }; + let w = [ + f.surface as u32 | kind << 8 | u32::from(f.rank) << 16 | (f.rule as u32) << 24, + id, + line_of(f.material, f.legs[0], f.level), + line_of(f.crossing, f.legs[1], f.level), + ]; + (0..labels as u32).find(|&l| { + let x = &words[words[5] as usize + LABEL * l as usize..][..4]; + [x[0], owner(words, l), x[2], x[3]] == w + }) + }) + .collect() +} + +/// The corners of a cell, a short list per point. +struct Corners { + points: Vec<[i32; 2]>, + head: Vec, + next: Vec, + keys: Vec, + of: Vec, +} + +impl Corners { + fn get(&mut self, point: u32, key: u32) -> u32 { + let mut c = self.head[point as usize]; + while c != NONE { + if self.keys[c as usize] == key { + return c; + } + c = self.next[c as usize]; + } + let id = self.keys.len() as u32; + self.keys.push(key); + self.of.push(point); + self.next.push(self.head[point as usize]); + self.head[point as usize] = id; + id + } + + /// Appends the corners of a point. + fn of_point(&self, point: u32, out: &mut Vec) { + let mut c = self.head[point as usize]; + while c != NONE { + out.push(c); + c = self.next[c as usize]; + } + } + + fn add_point(&mut self, p: [i32; 2]) -> u32 { + self.points.push(p); + self.head.push(NONE); + self.points.len() as u32 - 1 + } +} + +/// What a cell's mesh reads of the rims: R about the cell, and on each side line with a span of D the +/// plan vertices of both cells on it. Two rim sets with equal reads give the same mesh. +#[derive(PartialEq)] +pub struct Reads { + region: Region, + lines: [Vec; 4], +} + +impl Reads { + /// From the rims of the cell and its eight neighbours; a missing neighbour counts as one with no + /// sharp face. + pub fn of(plan: &FacePlan, rims: &[Rim]) -> Reads { + let cell = plan.cell; + let own; + let own = match rims.iter().find(|r| r.cell == cell) { + Some(r) => r, + None => { + own = Rim::of(plan); + &own + } + }; + let near = |r: &Rim| { + let d = [i64::from(r.cell.x) - i64::from(cell.x), i64::from(r.cell.y) - i64::from(cell.y)]; + (d[0].abs() <= 1 && d[1].abs() <= 1 && d != [0, 0]).then_some([d[0] as i32, d[1] as i32]) + }; + let mut marks = vec![([0, 0], own.sharp.as_slice())]; + marks.extend(rims.iter().filter_map(|r| Some((near(r)?, r.sharp.as_slice())))); + let region = Region::new(&marks); + let mut spans = [false; 4]; + for b in region.bounds().into_iter().filter(|b| b.span) { + if let Some(side) = points::side(b.a, b.b) { + spans[side] = true; + } + } + // Each side line with a span holds the plan vertices of both cells on it. + let mut lines: [Vec; 4] = Default::default(); + for (side, d, opposite) in [(0, [0, -1], 2), (1, [1, 0], 3), (2, [0, 1], 0), (3, [-1, 0], 1)] { + if !spans[side] { + continue; + } + lines[side] = own.lines[side].clone(); + if let Some(r) = rims.iter().find(|r| near(r) == Some(d)) { + lines[side].extend(&r.lines[opposite]); + lines[side].sort_unstable(); + lines[side].dedup(); + } + } + Reads { region, lines } + } +} + +/// Triangles or slots with their corners renamed by `rank`, in the order of their least corner (a +/// counting sort, stable). +fn by_least(items: &[[u32; K]], rank: &[u32]) -> Vec<[u32; K]> { + let renamed: Vec<[u32; K]> = items.iter().map(|t| t.map(|c| rank[c as usize])).collect(); + let least = |t: &[u32; K]| *t.iter().min().unwrap() as usize; + let mut at = vec![0; rank.len() + 1]; + for t in &renamed { + at[least(t) + 1] += 1; + } + for k in 1..at.len() { + at[k] += at[k - 1]; + } + let mut out = vec![[0; K]; renamed.len()]; + for t in &renamed { + out[at[least(t)]] = *t; + at[least(t)] += 1; + } + out +} + +/// The near mesh of a cell from its plan, its near records (`words`) and what it reads of the rims. +/// `now` gives milliseconds; no output depends on it. +pub fn mesh_cell( + plan: &FacePlan, + words: &[u32], + reads: &Reads, + now: &mut dyn FnMut() -> f64, +) -> Result { + let mut times = Vec::with_capacity(STAGES.len()); + let mut last = now(); + let mut lap = |times: &mut Vec| { + let t = now(); + times.push(t - last); + last = t; + }; + let (cell, region) = (plan.cell, &reads.region); + let input = points::input(plan, region, &reads.lines, cell.origin().y as f64); + lap(&mut times); + let (tris, split_edges) = cdt::triangulate(&input.points, &input.segments, input.edges)?; + lap(&mut times); + let labels = face_labels(&plan.faces, words); + let label_of = |f: u32| labels[f as usize].unwrap_or(NO_LABEL); + let is_sharp = |f: u32| f != cdt::INSIDE && sharp(plan.faces[f as usize].rule); + let unlabelled = (0..plan.faces.len()).filter(|&f| sharp(plan.faces[f].rule) && labels[f].is_none()).count() as u32; + // A point's ground face, from the face edges at it. + let mut ground_face = vec![NONE; input.points.len()]; + for s in &input.segments[..input.edges] { + for f in [s.left, s.right].into_iter().filter(|&f| !is_sharp(f)) { + for v in [s.a, s.b] { + ground_face[v as usize] = ground_face[v as usize].min(f); + } + } + } + let raster = points::grid_faces(plan); + let mut ground = vec![NONE; input.points.len()]; + let ground_key = |v: u32, p: [i32; 2], ground: &mut Vec| { + if ground.len() <= v as usize { + ground.resize(v as usize + 1, NONE); + } + if ground[v as usize] == NONE { + let face = match ground_face.get(v as usize) { + Some(&f) if f != NONE => f, + _ => grid_of(p).map_or(NONE, |g| raster[(g[1] * SIDE + g[0]) as usize]), + }; + ground[v as usize] = if face == NONE || face == crate::faces::OUTSIDE { + find(words, [f64::from(p[0]), f64::from(p[1])]).unwrap_or(NO_LABEL) + } else { + label_of(face) + }; + } + ground[v as usize] + }; + let mut corners = Corners { + points: input.points.clone(), + head: vec![NONE; input.points.len()], + next: Vec::new(), + keys: Vec::new(), + of: Vec::new(), + }; + let mut triangles = Vec::with_capacity(tris.len()); + for (t, class) in &tris { + let key = |v: u32, ground: &mut Vec| { + if is_sharp(*class) { + label_of(*class) + } else { + ground_key(v, input.points[v as usize], ground) + } + }; + let k = t.map(|v| key(v, &mut ground)); + triangles.push([0, 1, 2].map(|i| corners.get(t[i], k[i]))); + } + let (mut steps, mut faces) = (Vec::new(), Vec::new()); + for (s, &end) in input.segments[..input.edges].iter().zip(&input.end_faces) { + let side = |f: u32, v: u32, ground: &mut Vec| { + if is_sharp(f) { + label_of(f) + } else { + ground_key(v, input.points[v as usize], ground) + } + }; + let (la, lb) = (side(s.left, s.a, &mut ground), side(s.left, s.b, &mut ground)); + let (ra, rb) = (side(s.right, s.a, &mut ground), side(s.right, s.b, &mut ground)); + if la != ra || lb != rb { + let slot = [corners.get(s.a, la), corners.get(s.b, lb), corners.get(s.b, rb), corners.get(s.a, ra)]; + if end { + faces.push(slot); + } else { + steps.push(slot); + } + } + } + // The strip: its grid points are the triangulation's where D's border holds them. + let mut grid = vec![NONE; (SIDE * SIDE) as usize]; + for (k, &p) in input.points.iter().enumerate() { + if let Some(g) = grid_of(p) { + grid[(g[1] * SIDE + g[0]) as usize] = k as u32; + } + } + let first_strip = triangles.len(); + let mut level18 = Vec::new(); + for j in 0..params::CELLS { + for i in 0..params::CELLS { + if !region.strip(i, j) { + continue; + } + let halves = strip::halves(i, j).map(|h| h.iter().all(|g| region.on_boundary(g[0], g[1]))); + for (k, tri) in strip::triangles(i, j).into_iter().enumerate() { + let terrain = tri.map(|g| region.on_boundary(g[0], g[1])); + if terrain == [true; 3] && strip::TERRAIN_EARS.contains(&k) { + continue; + } + let out = if halves[k / 3] { &mut level18 } else { &mut triangles }; + out.push([0, 1, 2].map(|c| { + let g = tri[c]; + let at = (g[1] * SIDE + g[0]) as usize; + let p = [g[0] * params::GRID, g[1] * params::GRID]; + if grid[at] == NONE { + grid[at] = corners.add_point(p); + } + let key = if terrain[c] { NO_LABEL | TERRAIN_VERTEX } else { ground_key(grid[at], p, &mut ground) }; + corners.get(grid[at], key) + })); + } + } + } + // The culvert mouths of the cell: a corner on the water and one in the zone, which the faces must hold there. + let mut mouths = Vec::new(); + for m in &plan.mouths { + let inside = |c: f64| (0.0..CELL_UNITS as f64).contains(&c); + if !(inside(m.at[0]) && inside(m.at[1])) { + continue; + } + let d = MOUTH_M / metres_per_unit(cell.origin().y + libm::round(m.at[1]) as i64); + let at = |s: f64| [0, 1].map(|k| libm::round(m.at[k] + s * d * m.into[k]) as i32); + let label = |p: [i32; 2], surface: Surface| { + find(words, [f64::from(p[0]), f64::from(p[1])]) + .filter(|&id| crate::faces::records::label(words, id)[0] & 0xff == surface as u32) + }; + let (pw, pz) = (at(-1.0), at(1.0)); + // A corner lies on its cell: a mouth within MOUTH_M of a cell line draws in neither cell. + if [pw, pz].iter().flatten().any(|&c| !(0..=CELL_UNITS as i32).contains(&c)) { + continue; + } + let (Some(lw), Some(lz)) = (label(pw, Surface::Water), label(pz, Surface::Zone)) else { continue }; + let (vw, vz) = (corners.add_point(pw), corners.add_point(pz)); + let snorm = |x: f64| u32::from(libm::round(x.clamp(-1.0, 1.0) * 32767.0) as i16 as u16); + let edge = snorm(m.edge[0]) | snorm(m.edge[1]) << 16; + mouths.push([corners.get(vw, lw), corners.get(vz, lz), edge, (m.half_m as f32).to_bits()]); + } + // The corners by point (y, then x), so that the corners of a triangle or slot lie near each other + // in the list: the triangulation's points are sorted, the strip's added points follow them. + let yx = |v: u32| { + let p = corners.points[v as usize]; + (p[1], p[0]) + }; + let mut added: Vec = (input.points.len() as u32..corners.points.len() as u32).collect(); + added.sort_unstable_by_key(|&v| yx(v)); + let (mut order, mut k) = (Vec::with_capacity(corners.keys.len()), 0); + for v in 0..input.points.len() as u32 { + while k < added.len() && yx(added[k]) < yx(v) { + corners.of_point(added[k], &mut order); + k += 1; + } + corners.of_point(v, &mut order); + } + for &v in &added[k..] { + corners.of_point(v, &mut order); + } + let mut rank = vec![0; order.len()]; + for (new, &old) in order.iter().enumerate() { + rank[old as usize] = new as u32; + } + let shared = [by_least(&triangles[..first_strip], &rank), by_least(&triangles[first_strip..], &rank)].concat(); + let level18 = by_least(&level18, &rank); + let mut triangle_runs = runs(&shared)?; + let level18_runs = runs(&level18)?; + let level18_count = level18.len() as u32; + triangle_runs.extend(&level18_runs); + let triangles = [shared, level18].concat(); + let end_faces = faces.len(); + let steps = [by_least(&steps, &rank), by_least(&faces, &rank)].concat(); + let mouths = mouths.into_iter().map(|[w, z, e, h]| [rank[w as usize], rank[z as usize], e, h]).collect(); + let step_runs = [runs(&steps[..steps.len() - end_faces])?, runs(&steps[steps.len() - end_faces..])?].concat(); + let packed = (order.iter()) + .map(|&c| { + let (key, v) = (corners.keys[c as usize], corners.of[c as usize]); + let p = corners.points[v as usize].map(|c| c as u32); + let label = key & NO_LABEL; + [p[0] | label << 19, p[1] | (label >> 13) << 19 | (key >> 25) << 31] + }) + .collect::>(); + let stats = MeshStats { + cells: region.counts(), + points: input.points.len() as u32, + grid_points: input.grid_points, + corners: packed.len() as u32, + triangles: triangles.len() as u32, + strip_triangles: (triangles.len() - first_strip) as u32, + level18_triangles: level18_count, + steps: steps.len() as u32, + outside_d: input.outside_d, + unlabelled, + split_edges, + }; + lap(&mut times); + Ok(CellMesh { + cell, + corners: packed, + strip_triangles: stats.strip_triangles, + triangle_runs, + level18_runs: level18_runs.len() as u32, + triangles, + step_runs, + steps, + end_faces: end_faces as u32, + region: region.bits(), + mouths, + stats, + times, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_run_ends_where_its_corners_would_span_more_than_16_bits() { + // From base 5, corner 5 + 65,535 fits and 65,541 starts a run. + let triangles = [[5, 7, 6], [6, 9, 65_540], [7, 65_541, 8]]; + let runs = runs(&triangles).unwrap(); + assert_eq!(runs, [[2, 5], [1, 7]]); + assert_eq!(super::runs(&[[0, 65_536, 1]]), Err(MeshError::Wide)); + // The u16 0, 2, 1 | 1, 4, 65535 | 0, 65534, 1 and a zero pad. + assert_eq!(packed(&triangles, &runs), [2 << 16, 1 | 1 << 16, 4 | 0xffff << 16, 0xfffe << 16, 1]); + } +} diff --git a/host/obc-ground-plan/src/mesh/params.rs b/host/obc-ground-plan/src/mesh/params.rs new file mode 100644 index 0000000000..b719369aaa --- /dev/null +++ b/host/obc-ground-plan/src/mesh/params.rs @@ -0,0 +1,50 @@ +//! The mesher's parameters. They are the same in every region, so they live here with their +//! reasons and not in a rule table. + +use crate::faces::{HeightRule, Surface}; +use crate::frame::{CELL_UNITS, FRAME_BITS}; + +/// The terrain level whose grid the mesh uses: the finest level that the terrain draws. Every grid +/// size below derives from it. +pub const MESH_LEVEL: u32 = 18; +/// Frame units per grid cell: a terrain node of a level spans 2^(`FRAME_BITS` − level) units in 64 +/// grid cells (`GRID` of `terrain/lod.ts`). +pub const GRID: i32 = 1 << (FRAME_BITS - MESH_LEVEL - 6); +/// Frame units per cell of the region: a grid cell of the next coarser level, 2 × 2 grid cells. +pub const COARSE: i32 = 2 * GRID; +/// Region cells along a side of the cell. +pub const CELLS: i32 = (CELL_UNITS / COARSE as i64) as i32; +/// Grid points along a side of the cell, both borders included. +pub const SIDE: i32 = (CELL_UNITS / GRID as i64) as i32 + 1; + +/// The region rings that a sharp face's cells grow by into R: one ring of ground that holds the +/// crease at the face's outer edge, and the strip. +pub const FACE_RING: i32 = 2; + +/// A grid point keeps this far from every face edge (m): nearer, it adds only a sliver beside the +/// edge's own points. +pub const GRID_CLEARANCE_M: f64 = 0.4; + +/// A sharp face: its height rule is neither slope nor terrain. The terrain grid cannot draw its +/// edges, so the mesh draws it. +pub fn sharp(rule: HeightRule) -> bool { + !matches!(rule, HeightRule::Terrain | HeightRule::Slope) +} + +/// The longest piece of a face edge (m). The grid samples a face's inside; an edge has no grid +/// points, so it splits into equal pieces no longer than this: +/// - paved faces, rail beds and platforms: 4 m, the chord of a vertical radius of 200 m stays under +/// 1 cm; +/// - shoulders and verges: 3 m, narrow bands beside the carriageway; +/// - blend faces (junction regions, corner fills): 2 m, the blend heights curve; +/// - water: 4 m, its level runs along its line as a paved face's height; +/// - slope and terrain: 2.4 m, the grid's diagonal at the mesh level. +pub fn l_max_m(surface: Surface, rule: HeightRule) -> f64 { + match (rule, surface) { + (HeightRule::Owner, Surface::Water) => 4.0, + (HeightRule::Terrain | HeightRule::Slope, _) => 2.4, + (HeightRule::Blend, _) | (_, Surface::CornerFill) => 2.0, + (_, Surface::Shoulder | Surface::Verge) => 3.0, + _ => 4.0, + } +} diff --git a/host/obc-ground-plan/src/mesh/points.rs b/host/obc-ground-plan/src/mesh/points.rs new file mode 100644 index 0000000000..5d57e8a7fe --- /dev/null +++ b/host/obc-ground-plan/src/mesh/points.rs @@ -0,0 +1,241 @@ +//! The points and constraints of D's triangulation: +//! - every face edge with a sharp face on a side, split into equal pieces no longer than the +//! `l_max_m` of its faces; +//! - D's border, locked: each side of a cell of D toward a cell outside D, with its middle (a grid +//! point). A span of the cell line also holds the plan vertices that either cell has on it, and its +//! middle only where that lies farther than `GRID_CLEARANCE_M` from them, so both cells give it the +//! same points; +//! - the grid points inside D farther than `GRID_CLEARANCE_M` from every face edge, in every face. +//! +//! Every point is an integer of the cell's frame. Ground faces' edges are no constraints: the ground +//! is one continuous field, so a triangle may span two ground faces. + +use super::cdt::{Segment, INSIDE}; +use super::params::{l_max_m, sharp, GRID, GRID_CLEARANCE_M, SIDE}; +use super::region::Region; +use crate::faces::{Edge, EdgeKind, FacePlan, OUTSIDE}; +use crate::frame::{metres_per_unit_at, CELL_UNITS}; + +pub type P = [i32; 2]; + +pub struct Input { + /// Sorted by (y, x), each once. + pub points: Vec

, + pub segments: Vec, + /// `segments[..edges]` are face edges, the rest D's border. + pub edges: usize, + /// Per face edge piece, whether it lies on a deck end line (`EdgeKind::DeckEdge`): its slot is an end face. + pub end_faces: Vec, + pub grid_points: u32, + /// Face edges of a sharp face that do not lie in D: none, as R grows past every sharp face. + pub outside_d: u32, +} + +/// The cell's four side lines in the order of `Rim::lines`: north, east, south, west. +pub(super) fn side(a: P, b: P) -> Option { + let c = CELL_UNITS as i32; + match (a, b) { + (a, b) if a[1] == 0 && b[1] == 0 => Some(0), + (a, b) if a[0] == c && b[0] == c => Some(1), + (a, b) if a[1] == c && b[1] == c => Some(2), + (a, b) if a[0] == 0 && b[0] == 0 => Some(3), + _ => None, + } +} + +/// The point at k/n of the way from a to b, rounded to the frame unit. +fn part(a: P, b: P, k: i64, n: i64) -> P { + [0, 1].map(|i| { + let v = i64::from(a[i]) * (n - k) + i64::from(b[i]) * k; + (2 * v + n).div_euclid(2 * n) as i32 + }) +} + +fn dist(a: P, b: P, p: [f64; 2]) -> f64 { + let (e, w) = ([f64::from(b[0] - a[0]), f64::from(b[1] - a[1])], [p[0] - f64::from(a[0]), p[1] - f64::from(a[1])]); + let l2 = e[0] * e[0] + e[1] * e[1]; + let t = if l2 > 0.0 { ((w[0] * e[0] + w[1] * e[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + libm::hypot(w[0] - t * e[0], w[1] - t * e[1]) +} + +/// The points of face edge e of a plan in the mesh, from its first to its last: it splits into equal pieces no +/// longer than the `l_max_m` of its two faces. A storey's end on an end line takes them too (`mesh::shell`). +pub fn edge_points(plan: &FacePlan, e: &Edge, origin_y: f64) -> Vec

{ + let (a, b) = (plan.vertices[e.a as usize], plan.vertices[e.b as usize]); + let mid = [(a[0] + b[0]).div_euclid(2), (a[1] + b[1]).div_euclid(2)]; + let l = [e.left, e.right] + .map(|f| { + let f = &plan.faces[f as usize]; + l_max_m(f.surface, f.rule) + }) + .into_iter() + .fold(f64::INFINITY, f64::min); + let len = + libm::hypot(f64::from(b[0] - a[0]), f64::from(b[1] - a[1])) * metres_per_unit_at(origin_y + f64::from(mid[1])); + let n = (len / l).ceil().max(1.0) as i64; + let mut out = vec![a]; + for k in 1..=n { + let p = if k == n { b } else { part(a, b, k, n) }; + if Some(&p) != out.last() { + out.push(p); + } + } + out +} + +/// The input of D's triangulation. `lines`: the plan vertices of the cell and its neighbour on each +/// side line, as coordinates along it; `origin_y`: the cell's global row, for the metres per unit. +pub fn input(plan: &FacePlan, region: &Region, lines: &[Vec; 4], origin_y: f64) -> Input { + let mpu = |y: f64| metres_per_unit_at(origin_y + y); + let mut ends: Vec<(P, P, u32, u32)> = Vec::new(); + let mut end_faces = Vec::new(); + let mut outside_d = 0; + for e in plan.edges.iter().filter(|e| e.left != OUTSIDE && e.right != OUTSIDE) { + let rule = |f: u32| plan.faces[f as usize].rule; + if !sharp(rule(e.left)) && !sharp(rule(e.right)) { + continue; + } + let (a, b) = (plan.vertices[e.a as usize], plan.vertices[e.b as usize]); + let mid = [(a[0] + b[0]).div_euclid(2), (a[1] + b[1]).div_euclid(2)]; + if !region.d(mid[0].div_euclid(2 * GRID), mid[1].div_euclid(2 * GRID)) { + outside_d += 1; + continue; + } + for w in edge_points(plan, e, origin_y).windows(2) { + ends.push((w[0], w[1], e.left, e.right)); + end_faces.push(e.kind == EdgeKind::DeckEdge); + } + } + let edges = ends.len(); + // Grid points within the clearance of a face edge stay out. + let n = SIDE as usize; + let mut blocked = vec![false; n * n]; + for &(a, b, _, _) in &ends { + let clear = GRID_CLEARANCE_M / mpu(f64::from(a[1] + b[1]) / 2.0); + let range = |lo: i32, hi: i32| { + let first = ((f64::from(lo) - clear) / f64::from(GRID)).ceil().max(0.0) as i32; + let last = ((f64::from(hi) + clear) / f64::from(GRID)).floor().min(f64::from(SIDE - 1)) as i32; + first..=last + }; + for j in range(a[1].min(b[1]), a[1].max(b[1])) { + for i in range(a[0].min(b[0]), a[0].max(b[0])) { + if dist(a, b, [f64::from(i * GRID), f64::from(j * GRID)]) <= clear { + blocked[(j * SIDE + i) as usize] = true; + } + } + } + } + // D's border, D on the left of each piece. + for bound in region.bounds() { + let (a, b) = (bound.a, bound.b); + let mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + let mut pts = vec![a, b]; + match side(a, b).filter(|_| bound.span) { + Some(s) => { + let k = if s % 2 == 0 { 0 } else { 1 }; + let (lo, hi) = (a[k].min(b[k]), a[k].max(b[k])); + let on: Vec = lines[s].iter().copied().filter(|&v| v > lo && v < hi).collect(); + let clear = GRID_CLEARANCE_M / mpu(f64::from(mid[1])); + if on.iter().all(|&v| f64::from((v - mid[k]).abs()) > clear) { + pts.push(mid); + } + pts.extend(on.into_iter().map(|v| if k == 0 { [v, a[1]] } else { [a[0], v] })); + } + None => pts.push(mid), + } + let k = if a[0] == b[0] { 1 } else { 0 }; + let toward = (b[k] - a[k]).signum(); + pts.sort_unstable_by_key(|p| p[k] * toward); + pts.dedup(); + for w in pts.windows(2) { + ends.push((w[0], w[1], INSIDE, OUTSIDE)); + } + } + let mut points: Vec

= ends.iter().flat_map(|e| [e.0, e.1]).collect(); + let mut grid_points = 0; + for j in 0..SIDE { + for i in 0..SIDE { + if region.inside_d(i, j) && !blocked[(j * SIDE + i) as usize] { + points.push([i * GRID, j * GRID]); + grid_points += 1; + } + } + } + points.sort_unstable_by_key(|p| (p[1], p[0])); + points.dedup(); + let at = |p: P| points.binary_search_by_key(&(p[1], p[0]), |q| (q[1], q[0])).unwrap() as u32; + let segments = ends.iter().map(|&(a, b, left, right)| Segment { a: at(a), b: at(b), left, right }).collect(); + Input { segments, edges, end_faces, grid_points, outside_d, points } +} + +/// The face of the plan at each grid point of the cell, index j × `SIDE` + i, by scan lines half a +/// unit south of the rows: no plan vertex lies on such a line, so no two crossings tie at a vertex. A +/// grid point on a face edge takes a face beside it: it lies within `GRID_CLEARANCE_M` of the edge or +/// on an edge between two ground faces, where either face is right. `OUTSIDE` on the cell's lines. +pub fn grid_faces(plan: &FacePlan) -> Vec { + let n = SIDE as usize; + let mut rows: Vec> = vec![Vec::new(); n]; + for e in &plan.edges { + let (a, b) = (plan.vertices[e.a as usize], plan.vertices[e.b as usize]); + if a[1] == b[1] { + continue; + } + // The rows y with min ≤ y < max: their scan lines y + ½ cross the edge. + let (lo, hi) = (a[1].min(b[1]), a[1].max(b[1])); + let first = lo.div_euclid(GRID) + i32::from(lo.rem_euclid(GRID) != 0); + let last = (hi - 1).div_euclid(GRID); + // The face east of the edge: on its right where it runs south. + let east = if b[1] > a[1] { e.right } else { e.left }; + for j in first.max(1)..=last.min(SIDE - 2) { + let y = f64::from(j * GRID) + 0.5; + let x = f64::from(a[0]) + (y - f64::from(a[1])) * f64::from(b[0] - a[0]) / f64::from(b[1] - a[1]); + rows[j as usize].push((x, east)); + } + } + let mut out = vec![OUTSIDE; n * n]; + for (j, row) in rows.iter_mut().enumerate() { + row.sort_by(|a, b| a.0.total_cmp(&b.0)); + let mut k = 0; + let mut face = OUTSIDE; + for i in 1..n - 1 { + let x = (i as i32 * GRID) as f64; + while k < row.len() && row[k].0 <= x { + face = row[k].1; + k += 1; + } + out[j * n + i] = face; + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::faces::{Edge, EdgeKind}; + use crate::frame::CellKey; + + #[test] + fn a_face_tip_on_a_grid_row_gives_the_row_east_of_it_the_ground_in_either_edge_order() { + // Face 1, a triangle whose north tip lies on row 10; face 0 about it. + let edge = |a, b, left, right| Edge { a, b, left, right, kind: EdgeKind::Continuous, flags: 0 }; + let orders = [ + vec![edge(0, 1, 0, 1), edge(2, 0, 0, 1), edge(1, 2, 1, 0)], + vec![edge(2, 0, 0, 1), edge(0, 1, 0, 1), edge(1, 2, 1, 0)], + ]; + for edges in orders { + let plan = FacePlan { + cell: CellKey { x: 0, y: 0 }, + level: 0, + vertices: vec![[5000, 10 * GRID], [3000, 14000], [7000, 14000]], + faces: Vec::new(), + edges, + corners: Vec::new(), + mouths: Vec::new(), + stats: Default::default(), + }; + let row = &grid_faces(&plan)[10 * SIDE as usize..]; + assert_eq!(row[6..10], [0, 0, 0, 0], "{:?}", plan.edges); + } + } +} diff --git a/host/obc-ground-plan/src/mesh/region.rs b/host/obc-ground-plan/src/mesh/region.rs new file mode 100644 index 0000000000..92b3d0cf25 --- /dev/null +++ b/host/obc-ground-plan/src/mesh/region.rs @@ -0,0 +1,294 @@ +//! The owned region R about a cell, its strip S and the interior domain D = (R ∖ S) ∩ cell. +//! +//! R is every region cell whose open square meets the inside of a sharp face, grown by `FACE_RING` +//! rings. S is R's outer ring: the cells of R with an 8-neighbour outside R. R is a union of 5 × 5 +//! squares, so S is one cell wide and every cell of D lies a cell or more from ∂R. +//! +//! Each cell marks its own sharp cells (`sharp_cells`); R about a cell reads its neighbours' marks +//! within `RING` cells, so two cells agree on R wherever both read it. + +use super::params::{sharp, CELLS, COARSE, FACE_RING, GRID}; +use crate::faces::FacePlan; + +/// The window of sharp marks about the cell: R is exact on the cell and two rings, which S and the +/// spans of the cell's lines read. +const RING: i32 = FACE_RING + 2; +/// Level-17 cells along a side of the window. +const N: i32 = CELLS + 2 * RING; +/// The 8 neighbours. +const NEIGHBOURS: [[i32; 2]; 8] = [[-1, -1], [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0]]; +/// Words of a cell's sharp marks: one bit per region cell, row by row. +pub const MARK_WORDS: usize = (CELLS * CELLS / 64) as usize; +/// Words of R on the cell and one ring (`Region::bits`). +pub const REGION_WORDS: usize = (((CELLS + 2) * (CELLS + 2)) as usize).div_ceil(32); + +#[derive(PartialEq)] +pub struct Region { + r: Vec, +} + +/// A side of a cell of D that faces a cell outside D, D on its left (the side where the shoelace sum +/// of (a, b, point) is positive). `span`: on the cell line with R ∖ S of the next cell beyond it; +/// else the inner border, with S beyond it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Bound { + pub a: [i32; 2], + pub b: [i32; 2], + pub span: bool, +} + +fn index(i: i32, j: i32) -> Option { + let (x, y) = (i + RING, j + RING); + ((0..N).contains(&x) && (0..N).contains(&y)).then_some((y * N + x) as usize) +} + +impl Region { + /// R from the sharp marks of the cell and its neighbours, by (dx, dy) of the neighbour: a missing + /// neighbour has none. + pub fn new(marks: &[([i32; 2], &[u64])]) -> Region { + let mut faces = vec![false; (N * N) as usize]; + for &(d, bits) in marks { + for j in 0..CELLS { + for i in 0..CELLS { + let k = (j * CELLS + i) as usize; + if bits[k / 64] >> (k % 64) & 1 == 1 { + if let Some(at) = index(i + d[0] * CELLS, j + d[1] * CELLS) { + faces[at] = true; + } + } + } + } + } + Region { r: dilate(&faces, FACE_RING) } + } + + /// Whether region cell (i, j) of the cell's frame lies in R. + pub fn r(&self, i: i32, j: i32) -> bool { + index(i, j).is_some_and(|k| self.r[k]) + } + + /// A strip cell: in R with an 8-neighbour outside R. + pub fn strip(&self, i: i32, j: i32) -> bool { + self.r(i, j) && NEIGHBOURS.iter().any(|d| !self.r(i + d[0], j + d[1])) + } + + fn interior(&self, i: i32, j: i32) -> bool { + self.r(i, j) && !self.strip(i, j) + } + + /// D: R ∖ S in the cell. + pub fn d(&self, i: i32, j: i32) -> bool { + (0..CELLS).contains(&i) && (0..CELLS).contains(&j) && self.interior(i, j) + } + + /// The region cells that touch grid point (i, j) of the cell: one, two or four. + fn touching(i: i32, j: i32) -> impl Iterator { + let span = |v: i32| if v % 2 == 0 { (v / 2 - 1)..=(v / 2) } else { (v / 2)..=(v / 2) }; + span(j).flat_map(move |cy| span(i).map(move |cx| [cx, cy])) + } + + /// Whether grid point (i, j) lies on ∂R: it touches a cell of R and one outside. + pub fn on_boundary(&self, i: i32, j: i32) -> bool { + let (mut inside, mut outside) = (false, false); + for c in Self::touching(i, j) { + if self.r(c[0], c[1]) { + inside = true; + } else { + outside = true; + } + } + inside && outside + } + + /// R on the cell and one ring: bit (j + 1) × (`CELLS` + 2) + i + 1 for region cell (i, j), + /// −1 ≤ i, j ≤ `CELLS`. + pub fn bits(&self) -> Vec { + let n = CELLS + 2; + let mut out = vec![0u32; REGION_WORDS]; + for j in -1..=CELLS { + for i in -1..=CELLS { + if self.r(i, j) { + let k = ((j + 1) * n + i + 1) as usize; + out[k / 32] |= 1 << (k % 32); + } + } + } + out + } + + /// The cells of R, S and D in the cell. + pub fn counts(&self) -> [u32; 3] { + let mut c = [0; 3]; + for j in 0..CELLS { + for i in 0..CELLS { + c[0] += u32::from(self.r(i, j)); + c[1] += u32::from(self.strip(i, j)); + c[2] += u32::from(self.d(i, j)); + } + } + c + } + + /// D's border, cell by cell in rows, each cell's sides north, east, south, west. + pub fn bounds(&self) -> Vec { + let mut out = Vec::new(); + for j in 0..CELLS { + for i in 0..CELLS { + if !self.d(i, j) { + continue; + } + let (x0, y0, x1, y1) = (i * COARSE, j * COARSE, (i + 1) * COARSE, (j + 1) * COARSE); + for (n, a, b) in [ + ([i, j - 1], [x0, y0], [x1, y0]), + ([i + 1, j], [x1, y0], [x1, y1]), + ([i, j + 1], [x1, y1], [x0, y1]), + ([i - 1, j], [x0, y1], [x0, y0]), + ] { + if !self.d(n[0], n[1]) { + out.push(Bound { a, b, span: self.interior(n[0], n[1]) }); + } + } + } + } + out + } + + /// Whether grid point (i, j) lies inside D, off D's border: every cell that it touches + /// is in D. + pub fn inside_d(&self, i: i32, j: i32) -> bool { + Self::touching(i, j).all(|c| self.d(c[0], c[1])) + } +} + +/// The grid point of a frame point on the grid. +pub fn grid_of(p: [i32; 2]) -> Option<[i32; 2]> { + (p[0] % GRID == 0 && p[1] % GRID == 0).then(|| [p[0] / GRID, p[1] / GRID]) +} + +/// The cell's sharp marks: bit i + `CELLS` · j where region cell (i, j) of the cell's open square +/// meets the inside of a sharp face. +pub fn sharp_cells(plan: &FacePlan) -> Vec { + let mut out = vec![0u64; MARK_WORDS]; + for face in plan.faces.iter().filter(|f| f.level == 0 && sharp(f.rule)) { + let rings: Vec> = (face.rings.iter()) + .map(|r| r.iter().map(|&v| plan.vertices[v as usize].map(i64::from)).collect()) + .collect(); + mark(&rings, &mut |i, j| { + let k = (j * CELLS + i) as usize; + out[k / 64] |= 1 << (k % 64); + }); + } + out +} + +fn cross(a: [i64; 2], b: [i64; 2], p: [i64; 2]) -> i128 { + i128::from(b[0] - a[0]) * i128::from(p[1] - a[1]) - i128::from(b[1] - a[1]) * i128::from(p[0] - a[0]) +} + +/// Whether the closed segment ab meets the open square of region cell (i, j): the separating axes +/// of the square's sides and of the segment's normal, exact. +fn meets_open(a: [i64; 2], b: [i64; 2], i: i32, j: i32) -> bool { + let s = i64::from(COARSE); + let (x0, y0) = (i64::from(i) * s, i64::from(j) * s); + let (x1, y1) = (x0 + s, y0 + s); + if a[0].max(b[0]) <= x0 || a[0].min(b[0]) >= x1 || a[1].max(b[1]) <= y0 || a[1].min(b[1]) >= y1 { + return false; + } + let c = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]].map(|p| cross(a, b, p)); + c.iter().any(|&v| v < 0) && c.iter().any(|&v| v > 0) +} + +/// Marks the cells of the cell whose open square meets the inside of a polygon (rings in the cell's +/// frame): the cells that an edge enters, and the cells whose centre lies inside (even-odd over all +/// rings), which no edge enters. +fn mark(rings: &[Vec<[i64; 2]>], set: &mut dyn FnMut(i32, i32)) { + let s = i64::from(COARSE); + let cell = |v: i64| v.div_euclid(s).clamp(-1, i64::from(CELLS)) as i32; + let edges = || rings.iter().flat_map(|r| (0..r.len()).map(move |k| (r[k], r[(k + 1) % r.len()]))); + let mut bbox = [i64::MAX, i64::MAX, i64::MIN, i64::MIN]; + for (a, b) in edges() { + bbox = [bbox[0].min(a[0]), bbox[1].min(a[1]), bbox[2].max(a[0]), bbox[3].max(a[1])]; + for j in cell(a[1].min(b[1])).max(0)..=cell(a[1].max(b[1])).min(CELLS - 1) { + for i in cell(a[0].min(b[0])).max(0)..=cell(a[0].max(b[0])).min(CELLS - 1) { + if meets_open(a, b, i, j) { + set(i, j); + } + } + } + } + if bbox[0] > bbox[2] { + return; + } + let half = s as f64 / 2.0; + for j in cell(bbox[1]).max(0)..=cell(bbox[3]).min(CELLS - 1) { + let y = (i64::from(j) * s) as f64 + half; + let mut xs: Vec = edges() + .filter(|(a, b)| (a[1] as f64 <= y) != (b[1] as f64 <= y)) + .map(|(a, b)| a[0] as f64 + (y - a[1] as f64) * (b[0] - a[0]) as f64 / (b[1] - a[1]) as f64) + .collect(); + xs.sort_by(f64::total_cmp); + for pair in xs.as_chunks::<2>().0 { + let first = ((pair[0] - half) / s as f64).ceil() as i64; + let last = ((pair[1] - half) / s as f64).floor() as i64; + for i in first.max(0)..=last.min(i64::from(CELLS - 1)) { + set(i as i32, j); + } + } + } +} + +/// The cells within `ring` cells (Chebyshev) of a marked cell. +fn dilate(cells: &[bool], ring: i32) -> Vec { + let n = N as usize; + let pass = |src: &[bool], along_rows: bool| { + (0..src.len()) + .map(|k| { + let (x, y) = ((k % n) as i32, (k / n) as i32); + (-ring..=ring).any(|d| { + let (xx, yy) = if along_rows { (x + d, y) } else { (x, y + d) }; + (0..N).contains(&xx) && (0..N).contains(&yy) && src[(yy * N + xx) as usize] + }) + }) + .collect::>() + }; + pass(&pass(cells, true), false) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn marked(rings: &[Vec<[i64; 2]>]) -> Vec<(i32, i32)> { + let mut out = Vec::new(); + mark(rings, &mut |i, j| out.push((i, j))); + out.sort_unstable(); + out.dedup(); + out + } + + #[test] + fn a_square_marks_the_cells_its_inside_meets_and_not_those_it_touches() { + // From (1, 1) to (3, 2) region cells, on the cell lines: cells (1, 1) and (2, 1) only. + let s = i64::from(COARSE); + assert_eq!(marked(&[vec![[s, s], [3 * s, s], [3 * s, 2 * s], [s, 2 * s]]]), [(1, 1), (2, 1)]); + // A thin sliver inside one cell marks it; a large square marks its inside without an edge. + assert_eq!(marked(&[vec![[10, 10], [20, 10], [20, 11]]]), [(0, 0)]); + let big = marked(&[vec![[-s / 2, -s / 2], [9 * s + 1, -s / 2], [9 * s + 1, 9 * s + 1], [-s / 2, 9 * s + 1]]]); + assert_eq!(big.len(), 10 * 10); + } + + #[test] + fn a_neighbours_mark_reaches_the_cell_and_the_strip_rings_it() { + // One sharp cell in the east neighbour's first column: R reaches two columns into the cell, + // the outer one is the strip, and the points of ∂R and inside R follow. + let mut bits = vec![0u64; MARK_WORDS]; + let k = (10 * CELLS) as usize; + bits[k / 64] |= 1 << (k % 64); + let region = Region::new(&[([1, 0], &bits)]); + let last = CELLS - 1; + assert!(region.r(last - 1, 10) && !region.r(last - 2, 10)); + assert!(region.strip(last - 1, 10) && region.d(last, 10) && !region.d(last, 8) && region.strip(last, 8)); + assert!(region.on_boundary(2 * (last - 1), 21) && !region.on_boundary(2 * last + 1, 21)); + assert_eq!(region.counts(), [10, 7, 3]); + } +} diff --git a/host/obc-ground-plan/src/mesh/shell.rs b/host/obc-ground-plan/src/mesh/shell.rs new file mode 100644 index 0000000000..440f4666e5 --- /dev/null +++ b/host/obc-ground-plan/src/mesh/shell.rs @@ -0,0 +1,985 @@ +//! The meshes of the storeys over the ground: each storey's sheet as a constrained triangulation of its faces alone +//! (no ground ring, no strip, no grid point), and the shell about it, each part a closed solid of a real thickness: +//! the underside (the top again, turned over, at the slab's depth, with a riser where two depths meet), the edge +//! faces on the free outline, a parapet or a railing on it, and the piers. A corner is a point with a label of the +//! cell's block and a height offset in metres: its height is the label's height there plus the offset. +//! +//! The free outline is every face edge between the sheet and the rest that lies on no cell line and on no end line +//! where storey 0 meets the deck (`EdgeKind::DeckEdge`): those stay open, as the neighbour cell or storey 0 goes on +//! there. Each part is cut by the cell square; its faces on a cell line stay open as well. The face edges split +//! into equal pieces no longer than the `l_max_m` of their sheet faces, as the cell mesh's, a rule that reads only the +//! edge: two cells, and storey 0 on an end line by the same rule, give it the same points. +//! +//! Every triangle turns counter-clockwise seen from outside its solid (x east, y north, up), and every slot turns as +//! the cell mesh's: its first two corners are those of the face left of its edge. +//! +//! # Bytes (`StoreyMesh::to_bytes`), little-endian u32 words +//! +//! | Words | Holds | +//! | --- | --- | +//! | head | `HEAD` words: `MAGIC`, the cell's x and y (zoom 16), the counts of corners, triangles, triangle runs, slots, slot runs and of the tops' slots, then the triangles of each part in the order of `PARTS` | +//! | corners | 3 words each, sorted by point (y, then x): x in bits 0–18 and the label's bits 0–12 in bits 19–31; y in bits 0–18 and the label's bits 13–24 in bits 19–30; the offset (f32, metres) | +//! | triangle runs, triangles | as the cell mesh's: 2 words a run (count, base corner), 3 u16 a triangle less its run's base; each part in runs of its own | +//! | slot runs, slots | 2 words a run, 4 u16 a slot (`a_p, a_q, b_q, b_p`): the tops' slots between two labels, then the undersides' risers | + +use std::collections::BTreeMap; + +use super::cdt::{self, Segment}; +use super::params::l_max_m; +use super::{by_least, face_labels, packed, runs, MeshError, NO_LABEL}; +use crate::faces::records::{self, find, LINE, SAMPLE}; +use crate::faces::{EdgeKind, FacePlan, Storeys, Surface, OUTSIDE}; +use crate::frame::{metres_per_unit_at, CellKey, CELL_UNITS}; +use crate::graph::Structures; + +/// "OBS" and the layout's version. +pub const MAGIC: u32 = 0x4f42_5301; +/// The parts of a storey's mesh, in the order of their triangles. +pub const PARTS: [&str; 7] = ["top", "underside", "edge", "parapet", "railing", "post", "pier"]; +const TOP: usize = 0; +const UNDER: usize = 1; +const EDGE: usize = 2; +const PARAPET: usize = 3; +const RAILING: usize = 4; +const POST: usize = 5; +const PIER: usize = 6; +pub const HEAD: usize = 9 + PARTS.len(); + +/// A parapet: its width and its height over the deck (the crossing block's thickness table). +const PARAPET_M: [f64; 2] = [0.35, 1.0]; +/// A railing: its height, and the side of its square rail and of its posts (the crossing block's thickness table). +const RAIL_M: f64 = 1.05; +const BAR_M: f64 = 0.08; + +type P = [i32; 2]; + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ShellStats { + pub piers: u32, + /// Piers whose foot stands in a paved face of storey 0 or on a lower storey's sheet: left out. + pub piers_left_out: u32, + /// Sheet faces with no label in the block: none expected. + pub unlabelled: u32, + /// Pieces between two deck ways whose lines lie more than a parapet's height apart: each deck has its own edge. + pub torn: u32, +} + +/// The meshes of a cell's storeys over the ground: see the module's bytes. Triangles and slots hold whole corner +/// indices; `open` holds the pieces that may stay open (on a cell line or an end line where storey 0 meets the deck). +#[derive(Clone, Debug, PartialEq)] +pub struct StoreyMesh { + pub cell: CellKey, + pub corners: Vec<[u32; 3]>, + pub triangles: Vec<[u32; 3]>, + pub triangle_runs: Vec<[u32; 2]>, + /// Triangles per part, in the order of `PARTS`. + pub parts: [u32; PARTS.len()], + pub slots: Vec<[u32; 4]>, + pub slot_runs: Vec<[u32; 2]>, + pub top_slots: u32, + pub open: Vec<[P; 2]>, + pub stats: ShellStats, +} + +impl StoreyMesh { + pub fn to_bytes(&self) -> Vec { + let mut head = vec![ + MAGIC, + self.cell.x, + self.cell.y, + self.corners.len() as u32, + self.triangles.len() as u32, + self.triangle_runs.len() as u32, + self.slots.len() as u32, + self.slot_runs.len() as u32, + self.top_slots, + ]; + head.extend(self.parts); + let words = (head.into_iter()) + .chain(self.corners.iter().flatten().copied()) + .chain(self.triangle_runs.iter().flatten().copied()) + .chain(packed(&self.triangles, &self.triangle_runs)) + .chain(self.slot_runs.iter().flatten().copied()) + .chain(packed(&self.slots, &self.slot_runs)); + words.flat_map(u32::to_le_bytes).collect() + } + + /// A corner's point, label and offset (metres). + pub fn corner(&self, k: usize) -> (P, u32, f64) { + let [w0, w1, w2] = self.corners[k]; + let mask = (1 << 19) - 1; + ([(w0 & mask) as i32, (w1 & mask) as i32], w0 >> 19 | (w1 >> 19 & 0xfff) << 13, f64::from(f32::from_bits(w2))) + } + + /// The range of `triangles` of part k of `PARTS`. + pub fn part(&self, k: usize) -> std::ops::Range { + let start = self.parts[..k].iter().sum::() as usize; + start..start + self.parts[k] as usize + } +} + +/// The corners and the items of the mesh as it grows. +#[derive(Default)] +struct Build { + /// Each corner as it is asked for, its key (`corner_key`) and its offset's bits; equal ones are one corner. + keys: Vec<(u64, u32)>, + tris: [Vec<[u32; 3]>; PARTS.len()], + /// The tops' slots, then the undersides' risers. + slots: [Vec<[u32; 4]>; 2], + /// A corner of a label at a point that takes another label (`stub_label`): its key (`corner_key`) and that label, + /// sorted. + relabel: Vec<(u64, u32)>, +} + +/// A point in one word, in the order y, then x. +fn yx(p: P) -> u64 { + u64::from(p[1] as u32 ^ 1 << 31) << 32 | u64::from(p[0] as u32 ^ 1 << 31) +} + +fn of_yx(k: u64) -> P { + [(k as u32 ^ 1 << 31) as i32, ((k >> 32) as u32 ^ 1 << 31) as i32] +} + +/// A corner's point and label in one word, in the order y, then x, then the label. +fn corner_key(p: P, label: u32) -> u64 { + (p[1] as u64) << 44 | (p[0] as u64) << 25 | u64::from(label & NO_LABEL) +} + +impl Build { + fn corner(&mut self, p: P, label: u32, offset: f64) -> u32 { + let label = self.relabelled(p, label).unwrap_or(label); + self.keys.push((corner_key(p, label), (offset as f32).to_bits())); + self.keys.len() as u32 - 1 + } + + /// The label that a corner of label l at p takes instead, if any. + fn relabelled(&self, p: P, l: u32) -> Option { + let k = corner_key(p, l); + self.relabel.binary_search_by_key(&k, |x| x.0).ok().map(|i| self.relabel[i].1) + } + + /// A quad with its corners counter-clockwise seen from outside. + fn quad(&mut self, part: usize, c: [u32; 4]) { + self.tris[part].extend([[c[0], c[1], c[2]], [c[0], c[2], c[3]]]); + } +} + +fn cross(o: P, a: P, b: P) -> i64 { + (i64::from(a[0]) - i64::from(o[0])) * (i64::from(b[1]) - i64::from(o[1])) + - (i64::from(a[1]) - i64::from(o[1])) * (i64::from(b[0]) - i64::from(o[0])) +} + +/// Twice the signed area in the frame (x east, y south): positive where the ring turns from +x toward +y. +fn area2(ring: &[P]) -> i64 { + (0..ring.len()).map(|i| cross([0, 0], ring[i], ring[(i + 1) % ring.len()])).sum() +} + +/// The points of `points` (`yx` keys, sorted) within a unit of the segment a → b and strictly between its ends, in +/// order from a. +fn on_segment(points: &[(u64, u32)], a: P, b: P) -> Vec

{ + let d = [f64::from(b[0] - a[0]), f64::from(b[1] - a[1])]; + let l2 = d[0] * d[0] + d[1] * d[1]; + if l2 <= 0.0 { + return Vec::new(); + } + let (lo, hi) = (yx([i32::MIN, a[1].min(b[1]) - 1]), yx([i32::MAX, a[1].max(b[1]) + 1])); + let first = points.partition_point(|p| p.0 < lo); + let mut out: Vec<(f64, P)> = Vec::new(); + for p in points[first..].iter().take_while(|p| p.0 <= hi).map(|p| of_yx(p.0)).filter(|&p| p != a && p != b) { + let w = [f64::from(p[0] - a[0]), f64::from(p[1] - a[1])]; + let t = (w[0] * d[0] + w[1] * d[1]) / l2; + if t > 0.0 && t < 1.0 && (w[0] * d[1] - w[1] * d[0]).abs() / l2.sqrt() <= 1.0 { + // A few points an edge: in order of t as they come. + let at = out.iter().position(|x| x.0 > t).unwrap_or(out.len()); + out.insert(at, (t, p)); + } + } + out.into_iter().map(|x| x.1).collect() +} + +/// Whether a and b lie on one line of the cell square. +fn on_cell_line(a: P, b: P) -> bool { + let c = CELL_UNITS as i32; + (a[0] == b[0] && (a[0] == 0 || a[0] == c)) || (a[1] == b[1] && (a[1] == 0 || a[1] == c)) +} + +fn on_square(p: P) -> bool { + let c = CELL_UNITS as i32; + p[0] == 0 || p[0] == c || p[1] == 0 || p[1] == c +} + +/// The point at k/n of the way from a to b, rounded to the frame unit (as the cell mesh's pieces). +fn part_of(a: P, b: P, k: i64, n: i64) -> P { + [0, 1].map(|i| { + let v = i64::from(a[i]) * (n - k) + i64::from(b[i]) * k; + (2 * v + n).div_euclid(2 * n) as i32 + }) +} + +/// A vertical quad on the corners `[a_lo, a_hi, b_lo, b_hi]` of a segment a → b, facing away from the solid, which +/// lies left of a → b in the frame (x east, y south) where `left`, else right. +fn wall_of(b: &mut Build, part: usize, [a_lo, a_hi, b_lo, b_hi]: [u32; 4], left: bool) { + if left { + b.quad(part, [b_lo, a_lo, a_hi, b_hi]); + } else { + b.quad(part, [a_lo, b_lo, b_hi, a_hi]); + } +} + +/// A wall on the segment a → b from offsets `lo` to `hi` (at a, at b), with the labels at a and at b. +fn wall( + b: &mut Build, + part: usize, + (pa, pb): (P, P), + left: bool, + (la, lb): (u32, u32), + (lo, hi): ([f64; 2], [f64; 2]), +) { + let c = [b.corner(pa, la, lo[0]), b.corner(pa, la, hi[0]), b.corner(pb, lb, lo[1]), b.corner(pb, lb, hi[1])]; + wall_of(b, part, c, left); +} + +/// A closed prism over a convex ring of the cell (cut by the cell square): its corners at each point take the top's +/// label and offset and the foot's. Its walls on a cell line stay open. +fn prism(b: &mut Build, part: usize, ring: &[P], top: (u32, f64), foot: (u32, f64)) { + let n = ring.len(); + if n < 3 || area2(ring) == 0 { + return; + } + // A positive ring in the frame holds its inside on the left of each edge and turns clockwise seen from above. + let left = area2(ring) > 0; + let t: Vec = ring.iter().map(|&p| b.corner(p, top.0, top.1)).collect(); + let f: Vec = ring.iter().map(|&p| b.corner(p, foot.0, foot.1)).collect(); + for i in 0..n { + let j = (i + 1) % n; + if !on_cell_line(ring[i], ring[j]) { + wall_of(b, part, [f[i], t[i], f[j], t[j]], left); + } + } + for i in 1..n - 1 { + let (up, down) = if left { + ([t[0], t[i + 1], t[i]], [f[0], f[i], f[i + 1]]) + } else { + ([t[0], t[i], t[i + 1]], [f[0], f[i + 1], f[i]]) + }; + b.tris[part].extend([up, down]); + } +} + +/// A convex ring about the point `o`, given as offsets from it, cut by the cell square, its points rounded to the +/// frame unit. The cut is reckoned from `o`, so two cells that share the ring cut it alike on their shared line. +fn clip(o: P, ring: &[[f64; 2]]) -> Vec

{ + let c = CELL_UNITS as f64; + let mut pts = ring.to_vec(); + let lines = [(0, -f64::from(o[0]), false), (0, c - f64::from(o[0]), true), (1, -f64::from(o[1]), false)]; + for (axis, bound, keep_low) in lines.into_iter().chain([(1, c - f64::from(o[1]), true)]) { + let inside = |p: &[f64; 2]| if keep_low { p[axis] <= bound } else { p[axis] >= bound }; + let mut out = Vec::new(); + for i in 0..pts.len() { + let (a, b) = (pts[i], pts[(i + 1) % pts.len()]); + if inside(&a) { + out.push(a); + } + if inside(&a) != inside(&b) { + let t = (bound - a[axis]) / (b[axis] - a[axis]); + let mut q = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])]; + q[axis] = bound; + out.push(q); + } + } + pts = out; + } + let mut ring: Vec

= pts.iter().map(|p| [0, 1].map(|k| o[k] + libm::round(p[k]) as i32)).collect(); + ring.dedup(); + if ring.len() > 1 && ring[0] == ring[ring.len() - 1] { + ring.pop(); + } + ring +} + +/// What the shell reads of a label: its way (the material line's) and that line's samples. +struct Lines<'a> { + words: &'a [u32], +} + +impl Lines<'_> { + fn line(&self, label: u32) -> Option<&[u32]> { + let l = records::label(self.words, label)[2]; + (l != u32::MAX).then(|| &self.words[self.words[6] as usize + LINE * l as usize..][..LINE]) + } + + fn way(&self, label: u32) -> Option { + self.line(label).map(|l| l[0]) + } + + /// The metres along the label's line and its unit direction at q's foot on its nearest segment. + fn along(&self, label: u32, q: [f64; 2]) -> Option<(f64, [f64; 2])> { + self.foot(label, q).map(|(m, d, _)| (m, d)) + } + + /// The metres along the label's line, its unit direction and its height at q's foot on its nearest segment. + fn foot(&self, label: u32, q: [f64; 2]) -> Option<(f64, [f64; 2], f64)> { + let l = self.line(label)?; + let (first, n) = (l[2] as usize, l[3] as usize); + let s = |i: usize| &self.words[self.words[7] as usize + SAMPLE * (first + i)..][..SAMPLE]; + let pos = |i: usize| [f64::from(s(i)[0] as i32), f64::from(s(i)[1] as i32)]; + let mut best = (f64::INFINITY, 0.0, [1.0, 0.0], 0.0); + let f = |i: usize, k: usize| f64::from(f32::from_bits(s(i)[k])); + for i in 0..n.saturating_sub(1) { + let (a, b) = (pos(i), pos(i + 1)); + let d = [b[0] - a[0], b[1] - a[1]]; + let l2 = d[0] * d[0] + d[1] * d[1]; + if l2 <= 0.0 { + continue; + } + let t = (((q[0] - a[0]) * d[0] + (q[1] - a[1]) * d[1]) / l2).clamp(0.0, 1.0); + let e = libm::hypot(q[0] - a[0] - t * d[0], q[1] - a[1] - t * d[1]); + if e < best.0 { + let len = l2.sqrt(); + let mix = |k: usize| f(i, k) + t * (f(i + 1, k) - f(i, k)); + best = (e, mix(3), [d[0] / len, d[1] / len], mix(5)); + } + } + best.0.is_finite().then_some((best.1, best.2, best.3)) + } +} + +/// Whether q lies in face f of a plan (even-odd over its rings). +fn in_face(plan: &FacePlan, f: usize, q: [f64; 2]) -> bool { + let mut inside = false; + for ring in &plan.faces[f].rings { + let n = ring.len(); + for i in 0..n { + let (a, b) = (plan.vertices[ring[i] as usize], plan.vertices[ring[(i + 1) % n] as usize]); + let (a, b) = ([f64::from(a[0]), f64::from(a[1])], [f64::from(b[0]), f64::from(b[1])]); + if (a[1] > q[1]) != (b[1] > q[1]) && q[0] < a[0] + (q[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) { + inside = !inside; + } + } + } + inside +} + +/// Whether q lies in a carriageway, a rail bed or a crossing of a storey's plan, past its edge. +fn paved_at(plan: &FacePlan, q: [f64; 2]) -> bool { + (0..plan.faces.len()).any(|f| { + matches!(plan.faces[f].surface, Surface::Carriageway | Surface::RailBed | Surface::Crossing) + && in_face(plan, f, q) + && edge_distance(plan, f, q) > ON_EDGE_UNITS + }) +} + +/// The label of storey 0's paved face or shoulder that meets a deck's end at point p of its end line: of those a probe +/// `STUB_PROBE_M` to each side of p finds, the one whose line at p lies nearest label l's, within `STUB_STEP_M`. +fn stub_label(words: &[u32], lines: &Lines, l: u32, p: P, mpu: f64) -> Option { + let q = [f64::from(p[0]), f64::from(p[1])]; + let (_, dir, z) = lines.foot(l, q)?; + let r = STUB_PROBE_M / mpu; + let probes = [[q[0] + dir[0] * r, q[1] + dir[1] * r], [q[0] - dir[0] * r, q[1] - dir[1] * r]]; + (probes.iter().filter_map(|&x| find(words, x))) + .filter(|&g| { + let s = records::label(words, g)[0] & 0xff; + [Surface::Carriageway, Surface::Shoulder, Surface::RailBed, Surface::Crossing] + .iter() + .any(|&x| x as u32 == s) + }) + .filter_map(|g| lines.foot(g, q).map(|x| (g, (x.2 - z).abs()))) + .filter(|&(_, d)| d <= STUB_STEP_M) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(g, _)| g) +} + +/// The probes of `stub_label` stand this far along the deck's line from its end point. +const STUB_PROBE_M: f64 = 0.3; +/// A stub's line and its deck's meet at the end line; past this apart a face's line belongs to another way (metres). +const STUB_STEP_M: f64 = 0.25; + +/// A corner within this many frame units of a face's edge stands on it: the rings' corners are rounded. +const ON_EDGE_UNITS: f64 = 4.0; + +/// The distance from q to the nearest edge of face f (frame units). +fn edge_distance(plan: &FacePlan, f: usize, q: [f64; 2]) -> f64 { + let mut best = f64::INFINITY; + for ring in &plan.faces[f].rings { + let n = ring.len(); + for i in 0..n { + let (a, b) = (plan.vertices[ring[i] as usize], plan.vertices[ring[(i + 1) % n] as usize]); + let (a, b) = ([f64::from(a[0]), f64::from(a[1])], [f64::from(b[0]), f64::from(b[1])]); + let d = [b[0] - a[0], b[1] - a[1]]; + let l2 = d[0] * d[0] + d[1] * d[1]; + let t = if l2 > 0.0 { (((q[0] - a[0]) * d[0] + (q[1] - a[1]) * d[1]) / l2).clamp(0.0, 1.0) } else { 0.0 }; + best = best.min(libm::hypot(q[0] - a[0] - t * d[0], q[1] - a[1] - t * d[1])); + } + } + best +} + +/// The sheet face of a storey's plan that holds q, with its label. +fn sheet_at(plan: &FacePlan, labels: &[Option], q: [f64; 2]) -> Option { + (0..plan.faces.len()) + .filter(|&f| plan.faces[f].surface != Surface::Terrain) + .find(|&f| in_face(plan, f, q)) + .and_then(|f| labels[f]) +} + +/// The inner points of a box along a polyline of the free outline (the sheet on its left in the frame), `width_m` +/// into the sheet: mitred at each inner point; at an end on a cell line, on that line, so the neighbour's box meets it. +fn inner_points(pts: &[P], width_m: f64, origin_y: f64, along: &dyn Fn(usize) -> Option<[f64; 2]>) -> Vec

{ + let n = pts.len(); + let unit = |a: P, c: P| { + let d = [f64::from(c[0] - a[0]), f64::from(c[1] - a[1])]; + let l = libm::hypot(d[0], d[1]).max(1e-9); + [d[0] / l, d[1] / l] + }; + let left = |d: [f64; 2]| [-d[1], d[0]]; + let w = |p: P| width_m / metres_per_unit_at(origin_y + f64::from(p[1])); + let c = CELL_UNITS as i32; + (0..n) + .map(|i| { + let p = pts[i]; + let d_in = if i > 0 { Some(unit(pts[i - 1], p)) } else { None }; + let d_out = if i + 1 < n { Some(unit(p, pts[i + 1])) } else { None }; + // The offset from p, rounded as one vector: two cells that share p give it alike. + let delta = match (d_in, d_out) { + (Some(a), Some(b)) => { + let (na, nb) = (left(a), left(b)); + let m = [na[0] + nb[0], na[1] + nb[1]]; + let ml = libm::hypot(m[0], m[1]); + let m = if ml > 1e-9 { [m[0] / ml, m[1] / ml] } else { na }; + let s = w(p) / (m[0] * na[0] + m[1] * na[1]).max(0.5); + [s * m[0], s * m[1]] + } + (Some(d), None) | (None, Some(d)) => { + let on = |axis: usize| p[axis] == 0 || p[axis] == c; + // An end on a cell line takes the direction of its way's line there, which both cells read from + // the same samples, and its inner point slides along it onto the cell line. + let d = match along(i).filter(|_| on(0) || on(1)) { + Some(e) if e[0] * d[0] + e[1] * d[1] < 0.0 => [-e[0], -e[1]], + Some(e) => e, + None => d, + }; + let nrm = left(d); + let mut v = [w(p) * nrm[0], w(p) * nrm[1]]; + for axis in (0..2).filter(|&axis| on(axis) && d[axis].abs() > 0.2) { + let t = -v[axis] / d[axis]; + v = [v[0] + t * d[0], v[1] + t * d[1]]; + v[axis] = 0.0; + } + v + } + (None, None) => [0.0, 0.0], + }; + [0, 1].map(|k| (p[k] + libm::round(delta[k]) as i32).clamp(0, c)) + }) + .collect() +} + +/// A box along a polyline of the free outline with its inner points (`inner_points`), from offset `lo` to `hi`, one +/// label at each point. Its ends are closed, except on a cell line. +fn strip(b: &mut Build, part: usize, pts: &[P], inner: &[P], labels: &[u32], (lo, hi): (f64, f64)) { + let n = pts.len(); + if n < 2 { + return; + } + for i in 0..n - 1 { + let (p0, p1, q0, q1) = (pts[i], pts[i + 1], inner[i], inner[i + 1]); + let (l0, l1) = (labels[i], labels[i + 1]); + wall(b, part, (p0, p1), true, (l0, l1), ([lo; 2], [hi; 2])); + wall(b, part, (q0, q1), false, (l0, l1), ([lo; 2], [hi; 2])); + let top = [b.corner(p0, l0, hi), b.corner(q0, l0, hi), b.corner(q1, l1, hi), b.corner(p1, l1, hi)]; + b.quad(part, top); + let bottom = [b.corner(p0, l0, lo), b.corner(p1, l1, lo), b.corner(q1, l1, lo), b.corner(q0, l0, lo)]; + b.quad(part, bottom); + } + if !on_square(pts[0]) { + wall(b, part, (inner[0], pts[0]), true, (labels[0], labels[0]), ([lo; 2], [hi; 2])); + } + if !on_square(pts[n - 1]) { + wall(b, part, (inner[n - 1], pts[n - 1]), false, (labels[n - 1], labels[n - 1]), ([lo; 2], [hi; 2])); + } +} + +/// The meshes of cell `cell`'s storeys over the ground from their plans, the cell's block (`words`, with every +/// storey's records) and what their shells read. +pub fn mesh_storeys( + cell: CellKey, + storeys: &Storeys, + words: &[u32], + structures: &Structures, +) -> Result { + let origin_y = cell.origin().y as f64; + let mpu = |y: i32| metres_per_unit_at(origin_y + f64::from(y)); + let lines = Lines { words }; + let mut ground_ends: Vec<(u64, u32)> = storeys.ground_ends.iter().map(|&p| (yx(p), 0)).collect(); + ground_ends.sort_unstable(); + ground_ends.dedup(); + let mut b = Build::default(); + let mut stats = ShellStats::default(); + let mut open = Vec::new(); + let mut all_labels = Vec::new(); + for plan in &storeys.plans { + let labels = face_labels(&plan.faces, words); + let sheet = |f: u32| f != OUTSIDE && plan.faces[f as usize].surface != Surface::Terrain; + stats.unlabelled += + (0..plan.faces.len() as u32).filter(|&f| sheet(f) && labels[f as usize].is_none()).count() as u32; + let label = |f: u32| labels[f as usize].unwrap_or(NO_LABEL); + let way = |l: u32| lines.way(l).and_then(|w| storeys.way(w)); + let depth = |l: u32| way(l).map_or(0.0, |w| w.depth_m); + // The face edges of the sheet in pieces. + let mut pieces: Vec<(P, P, u32, u32, EdgeKind)> = Vec::new(); + for e in plan.edges.iter().filter(|e| sheet(e.left) || sheet(e.right)) { + let (pa, pb) = (plan.vertices[e.a as usize], plan.vertices[e.b as usize]); + // The sheet's faces split it: past the sheet lies nothing of the storey. + let l = [e.left, e.right] + .iter() + .filter(|&&f| sheet(f)) + .map(|&f| l_max_m(plan.faces[f as usize].surface, plan.faces[f as usize].rule)) + .fold(f64::INFINITY, f64::min); + let mid = (pa[1] + pb[1]) / 2; + let len = libm::hypot(f64::from(pb[0] - pa[0]), f64::from(pb[1] - pa[1])) * mpu(mid); + // An end line of the free outline takes storey 0's points on it, where it has any. + let ground = if e.kind == EdgeKind::DeckEdge && sheet(e.left) != sheet(e.right) { + on_segment(&ground_ends, pa, pb) + } else { + Vec::new() + }; + let n = if ground.is_empty() { (len / l).ceil().max(1.0) as i64 } else { ground.len() as i64 + 1 }; + let mut last = pa; + for k in 1..=n { + let p = if k == n { + pb + } else if ground.is_empty() { + part_of(pa, pb, k, n) + } else { + ground[k as usize - 1] + }; + if p != last { + pieces.push((last, p, e.left, e.right, e.kind)); + last = p; + } + } + } + // Where storey 0 meets the deck on an end line of the free outline, the deck's corners there take the label + // of storey 0's paved face or shoulder past it: the two meshes stand at one height on the line. + for &(pa, pc, left, right, _) in pieces.iter().filter(|p| p.4 == EdgeKind::DeckEdge && sheet(p.2) != sheet(p.3)) + { + let l = label(if sheet(left) { left } else { right }); + for p in [pa, pc] { + if let Some(g) = stub_label(words, &lines, l, p, mpu(p[1])) { + b.relabel.push((corner_key(p, l), g)); + } + } + } + b.relabel.sort_unstable(); + b.relabel.dedup_by_key(|x| x.0); + let mut keyed: Vec<(u64, u32)> = pieces.iter().flat_map(|p| [(yx(p.0), 0), (yx(p.1), 0)]).collect(); + keyed.sort_unstable(); + keyed.dedup(); + let points: Vec

= keyed.iter().map(|k| of_yx(k.0)).collect(); + let at = |p: P| keyed.binary_search(&(yx(p), 0)).unwrap() as u32; + let segments: Vec = + pieces.iter().map(|&(a, c, left, right, _)| Segment { a: at(a), b: at(c), left, right }).collect(); + let (tris, _) = cdt::triangulate(&points, &segments, segments.len())?; + for (t, class) in tris.iter().filter(|(_, c)| sheet(*c) && labels[*c as usize].is_some()) { + let l = label(*class); + let top = t.map(|v| b.corner(points[v as usize], l, 0.0)); + let under = t.map(|v| b.corner(points[v as usize], l, -depth(l))); + b.tris[TOP].push(top); + b.tris[UNDER].push([under[0], under[2], under[1]]); + } + // Slots between two labels; the free outline's edge faces; the open pieces. Two deck ways side by side on + // the sheet are one deck, but where their lines lie more than a parapet's height apart at either end of a + // piece, each has its own edge there: a slot would be a wall from one deck to the other. A piece decides from + // its own two points, so two cells decide alike; where a torn run meets a slot, all their corners at the + // shared point lie on one vertical line, which closes them. + let mut free: Vec<(P, P, u32)> = Vec::new(); + let deck = |f: u32| lines.way(label(f)).filter(|&w| storeys.way(w).is_some()); + let apart = |p: P, l: u32, r: u32| { + let z = |f: u32| lines.foot(label(f), [f64::from(p[0]), f64::from(p[1])]).map(|x| x.2); + z(l).zip(z(r)).is_some_and(|(za, zb)| (za - zb).abs() > PARAPET_M[1]) + }; + for &(pa, pc, left, right, kind) in &pieces { + let torn = sheet(left) + && sheet(right) + && deck(left).zip(deck(right)).is_some_and(|(a, c)| a != c) + && (apart(pa, left, right) || apart(pc, left, right)); + stats.torn += u32::from(torn); + let sides: &[bool] = match (sheet(left), sheet(right)) { + _ if torn => &[true, false], + (true, true) => &[], + (s_left, _) => &[s_left], + }; + if sides.is_empty() { + let (la, lb) = (label(left), label(right)); + // Two labels that take one label at both ends (`relabel`) need no slot. + let one = |p: P| b.relabelled(p, la).is_some_and(|g| b.relabelled(p, lb) == Some(g)); + if la != lb && !(one(pa) && one(pc)) { + let (da, db) = (-depth(la), -depth(lb)); + let top = + [b.corner(pa, la, 0.0), b.corner(pc, la, 0.0), b.corner(pc, lb, 0.0), b.corner(pa, lb, 0.0)]; + let under = + [b.corner(pa, la, da), b.corner(pc, la, da), b.corner(pc, lb, db), b.corner(pa, lb, db)]; + b.slots[0].push(top); + b.slots[1].push(under); + } + continue; + } + if !torn && (kind == EdgeKind::DeckEdge || kind == EdgeKind::CellBorder || on_cell_line(pa, pc)) { + open.push([pa, pc]); + continue; + } + for &s_left in sides { + let f = if s_left { left } else { right }; + let l = label(f); + let d = -depth(l); + wall(&mut b, EDGE, (pa, pc), s_left, (l, l), ([d; 2], [0.0; 2])); + // The parapet or the railing stands on the band: across a deck's free end it would stand on + // the carriageway. + if plan.faces[f as usize].surface == Surface::DeckEdge { + free.push(if s_left { (pa, pc, l) } else { (pc, pa, l) }); + } + } + } + // The free outline's chains, the sheet on their left; each run of one edge feature a parapet or a railing. A + // chain stays on one deck way: past a torn run's end, the next free piece may be the other deck's. The pieces + // by their first point, and their last points with their way, in sorted lists; a chain starts at a piece that + // no piece of its way leads to. + let way_of = |k: usize| lines.way(free[k].2).unwrap_or(u32::MAX); + let mut from: Vec<(u64, u32)> = free.iter().enumerate().map(|(k, f)| (yx(f.0), k as u32)).collect(); + from.sort_unstable(); + let mut to: Vec<(u64, u32)> = (0..free.len()).map(|k| (yx(free[k].1), way_of(k))).collect(); + to.sort_unstable(); + let mut used = vec![false; free.len()]; + let starts: Vec = (0..free.len()) + .filter(|&k| to.binary_search(&(yx(free[k].0), way_of(k))).is_err()) + .chain(0..free.len()) + .collect(); + for s in starts { + if used[s] { + continue; + } + let mut chain = vec![s]; + used[s] = true; + loop { + let last = *chain.last().unwrap(); + let end = yx(free[last].1); + let first = from.partition_point(|e| e.0 < end); + let next = (from[first..].iter().take_while(|e| e.0 == end).map(|e| e.1 as usize)) + .find(|&k| !used[k] && way_of(k) == way_of(last)); + let Some(k) = next else { break }; + used[k] = true; + chain.push(k); + } + let railing = |k: usize| way(free[k].2).is_some_and(|w| w.railing); + let mut i = 0; + while i < chain.len() { + let mut j = i + 1; + while j < chain.len() && railing(chain[j]) == railing(chain[i]) { + j += 1; + } + let run = &chain[i..j]; + let mut pts: Vec

= run.iter().map(|&k| free[k].0).collect(); + pts.push(free[run[run.len() - 1]].1); + let mut ls: Vec = run.iter().map(|&k| free[k].2).collect(); + ls.push(*ls.last().unwrap()); + let width = if railing(run[0]) { BAR_M } else { PARAPET_M[0] }; + let inner = inner_points(&pts, width, origin_y, &|i| { + lines.along(ls[i], [f64::from(pts[i][0]), f64::from(pts[i][1])]).map(|(_, d)| d) + }); + // The box stands on the band: where its inner side would stand in a paved face (another way's that + // meets the band), it ends. + let ok: Vec = inner.iter().map(|q| !paved_at(plan, [f64::from(q[0]), f64::from(q[1])])).collect(); + let mut k = 0; + while k + 1 < pts.len() { + if !(ok[k] && ok[k + 1]) { + k += 1; + continue; + } + let mut e = k + 1; + while e + 1 < pts.len() && ok[e + 1] { + e += 1; + } + let (p, q, l) = (&pts[k..=e], &inner[k..=e], &ls[k..=e]); + if railing(run[0]) { + strip(&mut b, RAILING, p, q, l, (RAIL_M - BAR_M, RAIL_M)); + posts(&mut b, &lines, p, l, structures.post_spacing_m, origin_y, &|x| paved_at(plan, x)); + } else { + strip(&mut b, PARAPET, p, q, l, (0.0, PARAPET_M[1])); + } + k = e; + } + i = j; + } + } + all_labels.push(labels); + } + piers(&mut b, storeys, words, &lines, &all_labels, structures, &mut stats); + // The corners by point (y, then x), then label and offset, each once; and the items in runs: each part and each + // kind of slot apart. + let mut unique = b.keys.clone(); + unique.sort_unstable(); + unique.dedup(); + let rank: Vec = b.keys.iter().map(|k| unique.binary_search(k).unwrap() as u32).collect(); + let (mut triangles, mut triangle_runs, mut parts) = (Vec::new(), Vec::new(), [0; PARTS.len()]); + for (k, tris) in b.tris.iter().enumerate() { + let sorted = by_least(tris, &rank); + triangle_runs.extend(runs(&sorted)?); + parts[k] = sorted.len() as u32; + triangles.extend(sorted); + } + let (mut slots, mut slot_runs) = (Vec::new(), Vec::new()); + for s in &b.slots { + let sorted = by_least(s, &rank); + slot_runs.extend(runs(&sorted)?); + slots.extend(sorted); + } + let corners = (unique.iter()) + .map(|&(key, offset)| { + let (label, x, y) = ((key as u32) & NO_LABEL, (key >> 25) as u32 & 0x7ffff, (key >> 44) as u32); + [x | label << 19, y | (label >> 13) << 19, offset] + }) + .collect(); + Ok(StoreyMesh { + cell, + corners, + triangles, + triangle_runs, + parts, + slots, + slot_runs, + top_slots: b.slots[0].len() as u32, + open, + stats, + }) +} + +/// A railing's posts on a polyline of the free outline: where the metres along its labels' line pass a multiple of +/// `spacing_m`, and at each end that lies on no cell line, inside the polyline; each a closed square box under the +/// rail, a closed triangular prism `BAR_M` on a side. A post nearer another one than a quarter of the spacing, or +/// across a cell line, is left out. +fn posts( + b: &mut Build, + lines: &Lines, + pts: &[P], + labels: &[u32], + spacing_m: f64, + origin_y: f64, + paved: &dyn Fn([f64; 2]) -> bool, +) { + let f = |p: P| [f64::from(p[0]), f64::from(p[1])]; + let mpu = |p: [f64; 2]| metres_per_unit_at(origin_y + p[1]); + let mut at: Vec<([f64; 2], [f64; 2], u32)> = Vec::new(); + let n = pts.len(); + for i in 0..n - 1 { + let (a, c) = (f(pts[i]), f(pts[i + 1])); + let len = libm::hypot(c[0] - a[0], c[1] - a[1]); + if len <= 0.0 { + continue; + } + let d = [(c[0] - a[0]) / len, (c[1] - a[1]) / len]; + let l = labels[i]; + let inset = |p: [f64; 2], s: f64| { + let k = s * BAR_M / mpu(p); + [p[0] + k * d[0], p[1] + k * d[1]] + }; + if i == 0 && !on_square(pts[0]) { + at.push((inset(a, 1.0), d, l)); + } + if let (Some((ma, _)), Some((mc, _))) = (lines.along(l, a), lines.along(l, c)) { + let (lo, hi) = (ma.min(mc), ma.max(mc)); + let mut m = libm::ceil(lo / spacing_m) * spacing_m; + while m < hi { + let t = if mc != ma { (m - ma) / (mc - ma) } else { 0.0 }; + at.push(([a[0] + t * (c[0] - a[0]), a[1] + t * (c[1] - a[1])], d, l)); + m += spacing_m; + } + } + if i + 2 == n && !on_square(pts[n - 1]) { + at.push((inset(c, -1.0), d, l)); + } + } + let mut kept: Vec<[f64; 2]> = Vec::new(); + for (p, d, l) in at { + if kept.iter().any(|q| libm::hypot(p[0] - q[0], p[1] - q[1]) * mpu(p) < spacing_m / 4.0) { + continue; + } + kept.push(p); + let s = BAR_M / mpu(p); + let n = [-d[1], d[0]]; + let corner = |u: f64, v: f64| [p[0] + u * s * d[0] + v * s * n[0], p[1] + u * s * d[1] + v * s * n[1]]; + // A post across a cell line would stand in two cells, each with its own chain: it is left out. + // A triangular post: the least closed box, two faces less than a square one. + let ring = [corner(-0.5, 0.0), corner(0.5, 0.0), corner(0.0, 1.0)]; + let c = CELL_UNITS as f64; + if ring.iter().flatten().any(|&v| !(0.0..=c).contains(&v)) || ring.iter().any(|&v| paved(v)) { + continue; + } + prism(b, POST, &clip([0, 0], &ring), (l, RAIL_M - BAR_M), (l, 0.0)); + } +} + +/// The piers at the baked pier points: each under the highest sheet that holds its point, along the deck's line +/// there, from the underside to `pier_depth_m` under the ground; left out where its foot stands in a paved face of +/// storey 0 or on a lower storey's sheet. A pier on a cell line is one solid in two halves: each cell reads its +/// sheet at the point of its own square nearest the pier's point, and the line, the ground and the tests of the +/// foot at the pier's whole ring, the same in both cells. +fn piers( + b: &mut Build, + storeys: &Storeys, + words: &[u32], + lines: &Lines, + labels: &[Vec>], + structures: &Structures, + stats: &mut ShellStats, +) { + let Some(first) = storeys.plans.first() else { return }; + let origin_y = first.cell.origin().y as f64; + let c = CELL_UNITS as f64; + for &pt in &storeys.piers { + let q = [f64::from(pt[0]), f64::from(pt[1])]; + let own = [q[0].clamp(1.0, c - 1.0), q[1].clamp(1.0, c - 1.0)]; + let Some((k, top)) = + (0..storeys.plans.len()).rev().find_map(|k| sheet_at(&storeys.plans[k], &labels[k], own).map(|l| (k, l))) + else { + continue; + }; + let (Some(w), Some((_, d))) = (lines.way(top).and_then(|w| storeys.way(w)), lines.along(top, q)) else { + continue; + }; + let mpu = metres_per_unit_at(origin_y + q[1]); + let (along, across) = (w.pier_m[0] / 2.0 / mpu, w.pier_m[1] / 2.0 / mpu); + let n = [-d[1], d[0]]; + let corner = |u: f64, v: f64| [u * along * d[0] + v * across * n[0], u * along * d[1] + v * across * n[1]]; + let whole = [corner(-1.0, -1.0), corner(1.0, -1.0), corner(1.0, 1.0), corner(-1.0, 1.0)]; + let ring = clip(pt, &whole); + if ring.len() < 3 { + continue; + } + let paved = |p: [f64; 2]| { + find(words, p).is_some_and(|l| { + let s = records::label(words, l)[0] & 0xff; + [Surface::Carriageway, Surface::RailBed, Surface::Crossing].iter().any(|&x| x as u32 == s) + }) + }; + let lower = |p: [f64; 2]| (0..k).any(|j| sheet_at(&storeys.plans[j], &labels[j], p).is_some()); + let foot: Vec<[f64; 2]> = whole.iter().map(|p| [q[0] + p[0], q[1] + p[1]]).chain([q]).collect(); + if foot.iter().any(|&p| paved(p) || lower(p)) { + stats.piers_left_out += 1; + continue; + } + let ground = find(words, q).unwrap_or(NO_LABEL); + prism(b, PIER, &ring, (top, -w.depth_m), (ground, -structures.pier_depth_m)); + stats.piers += 1; + } +} + +/// The faults of a storey mesh's closure, per solid: the slab (top, underside, edge faces and slots), the parapets, +/// the railings' rails, their posts and the piers. In each, every edge between two corners at two points is the edge of exactly one +/// triangle in each direction (a closed, consistently turned surface), except on a cell line and on an open piece +/// (`StoreyMesh::open`), where storey 0 or the neighbour goes on. Two corners at one point (a seam between two +/// labels, or a vertical edge) span no area seen from above and count for nothing. +pub fn closure(m: &StoreyMesh) -> Vec { + let point = |c: u32| m.corner(c as usize).0; + let open = + |a: P, b: P| on_cell_line(a, b) || m.open.iter().any(|o| (o[0] == a && o[1] == b) || (o[0] == b && o[1] == a)); + let mut faults = Vec::new(); + let slab = |k: usize| m.triangles[m.part(k)].to_vec(); + let mut solids = vec![("slab", [slab(TOP), slab(UNDER), slab(EDGE)].concat())]; + for (k, s) in m.slots.iter().enumerate() { + let [ap, aq, bq, bp] = *s; + let two = if (k as u32) < m.top_slots { [[ap, aq, bq], [ap, bq, bp]] } else { [[ap, bq, aq], [ap, bp, bq]] }; + solids[0].1.extend(two); + } + for k in [PARAPET, RAILING, POST, PIER] { + solids.push((PARTS[k], slab(k))); + } + for (name, tris) in solids { + let mut uses: BTreeMap<(u32, u32), u32> = BTreeMap::new(); + // A triangle with two equal corners (a slot whose two labels take one label at an end) spans nothing. + for t in tris.iter().filter(|t| t[0] != t[1] && t[1] != t[2] && t[0] != t[2]) { + for i in 0..3 { + *uses.entry((t[i], t[(i + 1) % 3])).or_default() += 1; + } + } + for (&(a, b), &n) in &uses { + let (pa, pb) = (point(a), point(b)); + if pa == pb { + continue; + } + let back = uses.get(&(b, a)).copied().unwrap_or(0); + if n > 1 || (back != 1 && !open(pa, pb)) { + faults.push(format!("{:?} {name}: edge {pa:?}-{pb:?} ({a}->{b}) used {n} times, {back} back", m.cell)); + } + } + } + faults +} + +/// The corners of a storey mesh's parapets and railings that stand in a carriageway, a rail bed or a crossing of +/// their storey (`Storeys::plans`), by their label's storey: none expected, as they stand on the free outline. +pub fn on_paved(m: &StoreyMesh, storeys: &Storeys, words: &[u32]) -> Vec { + let lines = Lines { words }; + let mut out = Vec::new(); + for k in [PARAPET, RAILING, POST] { + for t in &m.triangles[m.part(k)] { + for &c in t { + let (p, label, _) = m.corner(c as usize); + let storey = lines.line(label).map_or(0, |l| (l[1] >> records::LEG_SHIFT) as i8); + let Some(plan) = storeys.plans.iter().find(|p| p.level == storey) else { continue }; + let q = [f64::from(p[0]), f64::from(p[1])]; + if paved_at(plan, q) { + out.push(format!("{:?}: {} corner at {p:?} in a paved face of storey {storey}", m.cell, PARTS[k])); + } + } + } + } + out.sort(); + out.dedup(); + out +} + +/// The faults of two neighbouring cells' storey meshes on their shared line (`east`: b lies east of a, else +/// south): per point of the line and offset exactly the same corners, whose heights (`height_at` of their labels in +/// each cell's block) agree within 1 mm. +pub fn border(a: (&StoreyMesh, &[u32]), b: (&StoreyMesh, &[u32]), east: bool) -> Vec { + use crate::faces::heights::height_at; + let c = CELL_UNITS as i32; + let (axis, along) = if east { (0, 1) } else { (1, 0) }; + let on = |(m, words): (&StoreyMesh, &[u32]), line: i32| { + let mut out: BTreeMap<(i32, u32), Vec> = BTreeMap::new(); + for k in 0..m.corners.len() { + let (p, l, off) = m.corner(k); + // A pier's foot on the plain terrain (NO_LABEL) stands at the terrain's height, which no record holds. + if p[axis] == line && l != NO_LABEL { + let h = height_at(words, [f64::from(p[0]), f64::from(p[1])], Some(l), f64::NAN).h + off; + out.entry((p[along], (off as f32).to_bits())).or_default().push(h); + } + } + for v in out.values_mut() { + v.sort_by(f64::total_cmp); + v.dedup_by(|x, y| (*x - *y).abs() <= 0.001); + } + out + }; + let (x, y) = (on(a, c), on(b, 0)); + let mut faults = Vec::new(); + for (from, to) in [(&x, &y), (&y, &x)] { + for (&key, p) in from { + let q = to.get(&key).cloned(); + let same = + q.as_ref().is_some_and(|q| p.len() == q.len() && p.iter().zip(q).all(|(u, v)| (u - v).abs() <= 0.001)); + if !same { + faults.push(format!( + "{:?}|{:?} at {} offset {}: {p:?} and {q:?}", + a.0.cell, + b.0.cell, + key.0, + f32::from_bits(key.1) + )); + } + } + } + faults.sort(); + faults.dedup(); + faults +} diff --git a/host/obc-ground-plan/src/mesh/strip.rs b/host/obc-ground-plan/src/mesh/strip.rs new file mode 100644 index 0000000000..62cc784b1e --- /dev/null +++ b/host/obc-ground-plan/src/mesh/strip.rs @@ -0,0 +1,287 @@ +//! The strip: each strip cell as a fixed fan of 6 triangles over its border, so the mesh meets the +//! terrain grid on ∂R at every morph, over level-18 and level-17 nodes. +//! +//! A strip cell holds the 8 grid points on its border: its corners and the middle of each side. Its +//! middle is never on ∂R and always sunk, so the strip leaves it out. The fan follows the terrain's +//! diagonal from the north-east to the south-west corner (`gridIndices`): three triangles tile the +//! north-west half, three the south-east half, and each half's side middles lie on the half's border. +//! A middle slides along its side to the cell's corner, so each half stays tiled at every morph, and at +//! morph 1 (a level-17 node) the halves are the terrain's two level-17 triangles of the cell. +//! +//! The ears at the north-west and south-east corners (`TERRAIN_EARS`) are the terrain's own level-18 +//! triangles there: with all three corners on ∂R, they have no sunk corner, the terrain draws them and +//! the strip leaves them out. In the same way a half whose three corners lie on ∂R is the terrain's own +//! level-17 triangle: over a level-17 node the strip leaves out the triangles of that half. Such a half +//! lies at a north-west or south-east convex corner of R, or where two parts of R touch at a corner. +//! +//! A point on ∂R is a terrain vertex: it draws with the terrain's own vertex code, so it slides, +//! morphs and takes the page's height as the terrain's vertex there does. Every other point is a fixed +//! ground corner. No strip triangle turns over for any morph of its terrain vertices (the test below, +//! for every neighbour pattern). Over a level-17 node the mesh range keeps the level-17 vertices out +//! of their morph, so the strip needs no level-17 morph. +//! +//! At morph 1 a strip triangle can lose its plan area and still be needed. At a straight west border +//! of R with the north cell in R, [m10 m01 c20] becomes (m10, c00, c20): a vertical triangle between +//! the fixed m10, which the north cell shares, and the half's edge c00–c20. It closes the surface +//! there, so no step may drop a strip triangle for a zero plan area. +//! +//! The claim holds where the terrain draws its vertices there without the snap to road edges: the snap +//! moves a terrain vertex across the strip's triangles. + +/// The 6 triangles of the strip cell at region cell (i, j), as grid points, turning as +/// `gridIndices` (negative signed area in x east, y south): the north-west half, then the south-east. +pub fn triangles(i: i32, j: i32) -> [[[i32; 2]; 3]; 6] { + let at = |u: i32, v: i32| [2 * i + u, 2 * j + v]; + let [c00, c20, c02, c22] = [at(0, 0), at(2, 0), at(0, 2), at(2, 2)]; + let [m10, m01, m21, m12] = [at(1, 0), at(0, 1), at(2, 1), at(1, 2)]; + [[c00, m01, m10], [m10, m01, c20], [m01, c02, c20], [c20, c02, m21], [m21, c02, m12], [m21, m12, c22]] +} + +/// The ears of `triangles` that are the terrain's own level-18 triangles: north-west and south-east. +pub const TERRAIN_EARS: [usize; 2] = [0, 5]; + +/// The corners of the cell's two halves, the terrain's level-17 triangles: triangles 0 to 2 of +/// `triangles` tile the first, 3 to 5 the second. +pub fn halves(i: i32, j: i32) -> [[[i32; 2]; 3]; 2] { + let at = |u: i32, v: i32| [2 * i + u, 2 * j + v]; + [[at(0, 0), at(0, 2), at(2, 0)], [at(2, 0), at(0, 2), at(2, 2)]] +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::super::params::GRID; + use super::super::region::Region; + use super::super::CellMesh; + use super::*; + + /// The point that a grid point slides to: each odd coordinate to the even one before it. + fn even(g: [i32; 2]) -> [i32; 2] { + g.map(|v| v - (v & 1)) + } + + /// Twice the signed area (x east, y south) of a triangle at the 8 corners of its morph cube: corner + /// k with vertex i at morph `k >> i & 1`, where only terrain vertices move. The area is + /// multilinear in the three morphs, so these bound it at every morph. + fn orientation_corners(tri: [[i32; 2]; 3], slides: [bool; 3]) -> [i64; 8] { + std::array::from_fn(|k| { + let [a, b, c] = std::array::from_fn(|i| if k >> i & 1 == 1 && slides[i] { even(tri[i]) } else { tri[i] }); + i64::from(b[0] - a[0]) * i64::from(c[1] - a[1]) - i64::from(b[1] - a[1]) * i64::from(c[0] - a[0]) + }) + } + + /// The terrain's 8 triangles over region cell (i, j), as `gridIndices`: (a, a + n, a + 1) and + /// (a + 1, a + n, a + n + 1) per grid cell a. + fn terrain(i: i32, j: i32) -> Vec<[[i32; 2]; 3]> { + [(0, 0), (1, 0), (0, 1), (1, 1)] + .into_iter() + .flat_map(|(u, v)| { + let a = [2 * i + u, 2 * j + v]; + let (n, r, nr) = ([a[0], a[1] + 1], [a[0] + 1, a[1]], [a[0] + 1, a[1] + 1]); + [[a, n, r], [r, n, nr]] + }) + .collect() + } + + #[test] + fn no_strip_triangle_turns_over_for_any_neighbour_pattern_or_morph() { + // The strip cell (1, 1) of a 3 × 3 window; bit k of the pattern puts neighbour k in R. + let neighbours = [[0, 0], [1, 0], [2, 0], [2, 1], [2, 2], [1, 2], [0, 2], [0, 1]]; + for pattern in 0..255u32 { + let r = |c: [i32; 2]| { + c == [1, 1] || neighbours.iter().enumerate().any(|(k, &n)| n == c && pattern >> k & 1 == 1) + }; + // A grid point lies on ∂R when it touches a cell of R and one outside. + let boundary = |g: [i32; 2]| { + let span = |v: i32| if v % 2 == 0 { vec![v / 2 - 1, v / 2] } else { vec![v / 2] }; + let cells: Vec<[i32; 2]> = + span(g[1]).into_iter().flat_map(|y| span(g[0]).into_iter().map(move |x| [x, y])).collect(); + cells.iter().any(|&c| r(c)) && cells.iter().any(|&c| !r(c)) + }; + for (k, tri) in triangles(1, 1).into_iter().enumerate() { + // A left-out ear is a triangle that the terrain draws. + if tri.map(boundary) == [true; 3] && TERRAIN_EARS.contains(&k) { + assert!(terrain(1, 1).contains(&tri), "pattern {pattern:08b}: ear {tri:?}"); + } + let corners = orientation_corners(tri, tri.map(boundary)); + assert!( + corners[0] < 0 && corners.iter().all(|&a| a <= 0), + "pattern {pattern:08b}: {tri:?} {corners:?}" + ); + } + } + } + + /// The region cells that touch grid point g: one, two or four. + fn touching(g: [i32; 2]) -> Vec<[i32; 2]> { + let span = |v: i32| if v % 2 == 0 { vec![v / 2 - 1, v / 2] } else { vec![v / 2] }; + span(g[1]).into_iter().flat_map(|y| span(g[0]).into_iter().map(move |x| [x, y])).collect() + } + + /// A drawn corner: its grid point and whether it is a terrain vertex; a drawn triangle. + type Corner = ([i32; 2], bool); + type Drawn = [Corner; 3]; + + /// What draws over region cells lo..hi with terrain nodes of `level` (18 or 17): the cell's mesh, at + /// 17 without its level-18 runs and with its terrain vertices at their even point, and the terrain's + /// triangles without a sunk corner (a point whose region cells all lie in R). + fn drawn(mesh: &CellMesh, region: &Region, level: u32, lo: i32, hi: i32) -> Vec { + let level18: u32 = + mesh.triangle_runs[mesh.triangle_runs.len() - mesh.level18_runs as usize..].iter().map(|r| r[0]).sum(); + let shown = mesh.triangles.len() - if level < 18 { level18 as usize } else { 0 }; + let mut out: Vec = mesh.triangles[..shown] + .iter() + .map(|t| { + t.map(|c| { + let (p, _, terrain) = mesh.corner(c as usize); + let g = p.map(|v| v / GRID); + (if level < 18 && terrain { even(g) } else { g }, terrain) + }) + }) + .collect(); + let sunk = |g: [i32; 2]| touching(g).iter().all(|c| region.r(c[0], c[1])); + for j in lo..hi { + for i in lo..hi { + let ground = if level < 18 { halves(i, j).to_vec() } else { terrain(i, j) }; + out.extend(ground.into_iter().filter(|t| !t.iter().any(|&g| sunk(g))).map(|t| t.map(|g| (g, true)))); + } + } + out + } + + /// Twice the area of a triangle in grid points, positive for `gridIndices`' turn (x east, y south). + fn turn(t: [[f64; 2]; 3]) -> f64 { + -((t[1][0] - t[0][0]) * (t[2][1] - t[0][1]) - (t[1][1] - t[0][1]) * (t[2][0] - t[0][0])) + } + + /// The faults of what draws inside region cells lo..hi less two: a sample point that is not covered + /// exactly once, and an edge without its reverse (vertices by point and kind, so a crack shows). A + /// zero-area triangle covers no point but closes edges. + fn faults(tris: &[Drawn], lo: i32, hi: i32) -> Vec { + let (a, b) = (2 * lo + 4, 2 * hi - 4); + let mut cells: BTreeMap<[i32; 2], Vec> = BTreeMap::new(); + for (k, t) in tris.iter().enumerate() { + let (x0, x1) = (t.iter().map(|c| c.0[0]).min().unwrap(), t.iter().map(|c| c.0[0]).max().unwrap()); + let (y0, y1) = (t.iter().map(|c| c.0[1]).min().unwrap(), t.iter().map(|c| c.0[1]).max().unwrap()); + for y in y0..y1.max(y0 + 1) { + for x in x0..x1.max(x0 + 1) { + cells.entry([x, y]).or_default().push(k); + } + } + } + let mut out = Vec::new(); + for y in a..b { + for x in a..b { + for o in [[0.1234, 0.3141], [0.6123, 0.1732], [0.2718, 0.866], [0.4142, 0.539]] { + let p = [f64::from(x) + o[0], f64::from(y) + o[1]]; + let n = (cells.get(&[x, y]).into_iter().flatten()) + .filter(|&&k| { + let t = tris[k].map(|c| c.0.map(f64::from)); + (0..3).all(|e| turn([t[e], t[(e + 1) % 3], p]) > 0.0) + }) + .count(); + if n != 1 { + out.push(format!("point {p:?} drawn {n} times")); + } + } + } + } + let mut edges: BTreeMap<(Corner, Corner), i32> = BTreeMap::new(); + for t in tris { + for e in 0..3 { + let (p, q) = (t[e], t[(e + 1) % 3]); + if p.0 != q.0 { + *edges.entry((p, q)).or_default() += 1; + *edges.entry((q, p)).or_default() -= 1; + } + } + } + let inside = |g: [i32; 2]| g.iter().all(|v| (a..=b).contains(v)); + out.extend( + (edges.iter()) + .filter(|(e, &n)| n != 0 && inside(e.0 .0) && inside(e.1 .0)) + .map(|(e, n)| format!("edge {e:?} open {n}")), + ); + out + } + + #[test] + fn mesh_cell_and_the_terrain_draw_each_point_once_and_close_at_level_18_and_17() { + use super::super::params::{CELLS, FACE_RING}; + use super::super::region::MARK_WORDS; + use super::super::{mesh_cell, Reads}; + use crate::faces::{records, Rules}; + use crate::frame::CellKey; + use crate::terrain::Terrain; + // An empty cell: one terrain face, so every corner of the mesh is ground. + let key = CellKey { x: 34_307, y: 23_107 }; + let input = crate::CellInput { key, features: Vec::new(), terrain: Terrain::new(key, Vec::new()) }; + let rules = Rules::embedded(); + let (plan, near, _) = + records::near(&crate::graph::build(key, &input, &rules.sections), &input, rules, key, 0, true); + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: u64| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n) as i32 + }; + // A sharp cell grows to a square of this side: two at this offset across and down touch at a corner. + let side = 2 * FACE_RING + 1; + let (lo, hi) = (20 - FACE_RING - 3, 44 + side + FACE_RING + 3); + let (mut contacts, mut halves18) = (0, [0u32; 2]); + for shape in 0..50 { + let mut bits = vec![0u64; MARK_WORDS]; + let mut mark = |i: i32, j: i32| { + let k = (j * CELLS + i) as usize; + bits[k / 64] |= 1 << (k % 64); + }; + // Every other shape forces two parts of R to touch at a corner; random cells add every other shape. + if shape % 2 == 0 { + let (i, j, down) = (20 + next(20), 24 + next(16), if next(2) == 0 { 1 } else { -1 }); + mark(i, j); + mark(i + side, j + down * side); + } + for _ in 0..1 + next(6) { + mark(20 + next(24), 20 + next(24)); + } + let region = Region::new(&[([0, 0], bits.as_slice())]); + let reads = Reads { region, lines: Default::default() }; + let mesh = mesh_cell(&plan, &near.words, &reads, &mut || 0.0).expect("a mesh"); + let region = &reads.region; + let boundary = |g: [i32; 2]| region.on_boundary(g[0], g[1]); + for level in [18, 17] { + let found = faults(&drawn(&mesh, region, level, lo, hi), lo, hi); + assert!(found.is_empty(), "shape {shape} level {level}: {:?}", &found[..found.len().min(8)]); + } + // The level-18 runs hold exactly the strip triangles of halves with all three corners on ∂R. + let n = mesh.triangles.len(); + let level18: u32 = + mesh.triangle_runs[mesh.triangle_runs.len() - mesh.level18_runs as usize..].iter().map(|r| r[0]).sum(); + for (k, t) in mesh.triangles.iter().enumerate().skip(n - mesh.strip_triangles as usize) { + let c = t.iter().fold([0, 0], |s, &v| { + let p = mesh.corner(v as usize).0; + [s[0] + p[0] / GRID, s[1] + p[1] / GRID] + }); + let (i, j) = (c[0].div_euclid(6), c[1].div_euclid(6)); + let h = usize::from(c[0] - 6 * i + c[1] - 6 * j > 6); + let terrain_half = halves(i, j)[h].iter().all(|&g| boundary(g)); + assert_eq!( + k >= n - level18 as usize, + terrain_half, + "shape {shape}: strip triangle {k} of ({i}, {j}) half {h}" + ); + halves18[h] += u32::from(terrain_half); + } + for j in lo..hi { + for i in lo..hi { + let r = [[0, 0], [1, 0], [0, 1], [1, 1]].map(|d| region.r(i - 1 + d[0], j - 1 + d[1])); + contacts += u32::from(r == [true, false, false, true] || r == [false, true, true, false]); + } + } + } + // Both halves go to the level-18 runs, and parts of R touch at a corner. + assert!(halves18[0] > 0 && halves18[1] > 0 && contacts > 0, "{halves18:?} {contacts}"); + } +} diff --git a/host/obc-ground-plan/src/probe.rs b/host/obc-ground-plan/src/probe.rs new file mode 100644 index 0000000000..b32bc1bb7d --- /dev/null +++ b/host/obc-ground-plan/src/probe.rs @@ -0,0 +1,136 @@ +//! The caps that a build and the CPU height function hit, counted per thread for the native census +//! (the binary `census` of `obc-trailview-features`). The WASM build counts nothing: there `hit` and +//! `field` are empty. + +/// The fields that the records pack into 16 bits (8 for a junction's arms), and the leg index that a +/// `u8` holds: `field` keeps the largest value of each since the last `take`. A value past `limit` +/// wrapped or tripped an assert. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Field { + /// A candidate's index in a bin's candidate item. + Candidate, + /// The candidate items of a bin. + BinCandidates, + /// The segment items of a bin. + BinSegments, + /// The height segment items of a bin's window. + HeightSegments, + /// The height disc items of a bin's window. + HeightDiscs, + /// The item words of a bin (asserted). + BinItems, + /// The outline edges of a cell (asserted). + OutlineEdges, + /// The cuts before a point of a line: its leg. + Leg, + /// A record line's index in a segment item or an outline edge's host (asserted there). + Line, + /// A sample's index in a segment item. + Sample, + /// A disc's index in a height disc item. + Disc, + /// The sample offsets from its leg's start of a junction arm. + Span, + /// The arms of a junction record (8 bits, asserted). + JunctionArms, + /// A junction record's id (asserted). + JunctionId, + /// The blend edges of a bin's window (asserted). + BlendEdges, +} + +/// The fields in code order, with their names. +pub const FIELDS: [(Field, &str); 15] = [ + (Field::Candidate, "candidate"), + (Field::BinCandidates, "bin_candidates"), + (Field::BinSegments, "bin_segments"), + (Field::HeightSegments, "height_segments"), + (Field::HeightDiscs, "height_discs"), + (Field::BinItems, "bin_items"), + (Field::OutlineEdges, "outline_edges"), + (Field::Leg, "leg"), + (Field::Line, "line"), + (Field::Sample, "sample"), + (Field::Disc, "disc"), + (Field::Span, "span"), + (Field::JunctionArms, "junction_arms"), + (Field::JunctionId, "junction_id"), + (Field::BlendEdges, "blend_edges"), +]; + +impl Field { + /// The largest value that the field holds. + pub fn limit(self) -> u64 { + match self { + Field::Leg | Field::JunctionArms => u64::from(u8::MAX), + _ => u64::from(u16::MAX), + } + } +} + +/// A cap that leaves something out. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Cap { + /// More than `heights::SLOTS` lines at a point: the last in the painter's order went. + Slots, + /// A line with more than `heights::QUADS` quads within its leg reach at a point: one went. + Quads, + /// A third region beyond a junction region's edges near a point: the farthest went. + Regions, + /// i_overlay gave a slice tile no graph: the whole tile is one patch. + SliceFallback, +} + +/// The counts of a thread since its last `take`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Probe { + pub slots: u64, + pub quads: u64, + pub regions: u64, + pub slice_fallback: u64, + /// The largest value of each field, in the order of `FIELDS`. + pub fields: [u64; FIELDS.len()], +} + +#[cfg(not(target_arch = "wasm32"))] +thread_local! { + static PROBE: std::cell::Cell = std::cell::Cell::new(Probe::default()); +} + +#[inline] +pub fn hit(cap: Cap) { + #[cfg(not(target_arch = "wasm32"))] + PROBE.with(|p| { + let mut v = p.get(); + let n = match cap { + Cap::Slots => &mut v.slots, + Cap::Quads => &mut v.quads, + Cap::Regions => &mut v.regions, + Cap::SliceFallback => &mut v.slice_fallback, + }; + *n = n.saturating_add(1); + p.set(v); + }); + #[cfg(target_arch = "wasm32")] + let _ = cap; +} + +#[inline] +pub fn field(field: Field, value: usize) { + #[cfg(not(target_arch = "wasm32"))] + PROBE.with(|p| { + let mut v = p.get(); + v.fields[field as usize] = v.fields[field as usize].max(value as u64); + p.set(v); + }); + #[cfg(target_arch = "wasm32")] + let _ = (field, value); +} + +/// The counts since the last call, and a fresh start. +pub fn take() -> Probe { + #[cfg(not(target_arch = "wasm32"))] + return PROBE.with(|p| p.replace(Probe::default())); + #[cfg(target_arch = "wasm32")] + Probe::default() +} diff --git a/host/obc-ground-plan/src/sections.rs b/host/obc-ground-plan/src/sections.rs new file mode 100644 index 0000000000..0f11e6bbf0 --- /dev/null +++ b/host/obc-ground-plan/src/sections.rs @@ -0,0 +1,1095 @@ +//! The cross-section of each way and waterway, from the rule tables of `data/trailview`, and the +//! reach table: every reach and chain of rules, bounded by `CHAIN_MAX_M`. +//! +//! A *finish* is what a way's top is made of, in the order of the mask's surface code (index + 1). + +use std::sync::OnceLock; + +use serde_json::{Map, Value}; + +use crate::frame::{CHAIN_MAX_M, MARGIN_M}; +use crate::tile::Tags; + +/// The widest half-width: the tiles' buffer holds the cone of a road up to 30 m wide. +pub const HALF_MAX_M: f64 = 15.0; +const HALF_MIN_M: f64 = 0.4; +/// A gauge narrower than this many mm is narrow. +const NARROW_MM: i64 = 1200; +const TRACKS: [&str; 4] = ["rail", "narrow_gauge", "light_rail", "funicular"]; +const MAIN: [&str; 7] = ["motorway", "trunk", "primary", "secondary", "motorway_link", "trunk_link", "primary_link"]; +const PAVED: [&str; 6] = ["asphalt", "paved", "concrete", "paving_stones", "sett", "chipseal"]; +const GRAVEL: [&str; 4] = ["gravel", "compacted", "fine_gravel", "pebblestone"]; +const DIRT: [&str; 6] = ["dirt", "ground", "earth", "mud", "unpaved", "sand"]; +const GRASS: [&str; 2] = ["grass", "grass_paver"]; +/// The path classes that a town paves where they have no `surface` tag. +const TOWN_PATHS: [&str; 4] = ["footway", "pedestrian", "cycleway", "steps"]; +/// The path classes whose untagged finish is a path's: a cycleway is paved. +const PATHS: [&str; 6] = ["path", "footway", "bridleway", "steps", "pedestrian", "via_ferrata"]; +const ONEWAY: [&str; 7] = ["yes", "true", "1", "-1", "reverse", "reversible", "alternating"]; +const CLASS_FIELDS: [&str; 9] = + ["half_m", "shoulder_m", "sidewalk_m", "kerb_m", "kerb_top_m", "cut", "fill", "reach", "widen_m"]; +const WATER_FIELDS: [&str; 4] = ["width_m", "cut", "fill", "reach"]; +/// The fields of a water line's faces and bank: none is an option of the feature step. `depth_m` is the +/// bed's, which the look reads. +const WATER_BANK_FIELDS: [&str; 6] = + ["depth_m", "bank_slope", "bank_reach_m", "bank_steepest", "freeboard_m", "bank_m"]; +/// The feature kinds of line water. +pub const WATER_KINDS: [&str; 2] = ["river", "stream"]; +/// The fields of the way graph. The feature step's options hold them for the levels that it bakes. +pub const GRAPH_FIELDS: [&str; 10] = [ + "snap_m", + "snap_height_m", + "sag_plan_m", + "sag_height_m", + "clearance_m", + "clearance_least_m", + "bore_m", + "bore_least_m", + "deck_least_m", + "roof_least_m", +]; +/// The numeric fields of the faces: none is an option of the feature step. +const FACE_FIELDS: [&str; 7] = + ["inner_radius_m", "verge_m", "return_grade", "corner_radius_m", "corner_radius_walk_m", "fill_max", "cut_max"]; +pub const WATER_GRAPH_FIELDS: [&str; 11] = [ + "culvert_max_m", + "culvert_width_m", + "pipe_width_m", + "stones_width_m", + "clearance_m", + "clearance_least_m", + "sag_plan_m", + "sag_height_m", + "curve_turn_max_deg", + "curve_off_max_m", + "underground_m", +]; +/// The culvert chain's read along the water: a longer `culvert_max_m` would pass the graph's reach. +pub const CULVERT_MAX_M: f64 = 60.0; +/// Under this angle a way runs along the water or another way: the overlay of the faces decides, and +/// neither the graph nor the bake makes a crossing there. +pub const GRAZE_DEG: f64 = 20.0; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Finish { + Main, + Road, + Gravel, + Dirt, + Grass, + Path, + Oneway, + Paving, + Rail, + Narrow, + Rack, + NarrowRack, +} + +impl Finish { + pub const ALL: [Finish; 12] = [ + Finish::Main, + Finish::Road, + Finish::Gravel, + Finish::Dirt, + Finish::Grass, + Finish::Path, + Finish::Oneway, + Finish::Paving, + Finish::Rail, + Finish::Narrow, + Finish::Rack, + Finish::NarrowRack, + ]; + const NAMES: [&str; 12] = [ + "main", + "road", + "gravel", + "dirt", + "grass", + "path", + "oneway", + "paving", + "rail", + "narrow", + "rack", + "narrow-rack", + ]; + + pub fn name(self) -> &'static str { + Self::NAMES[self as usize] + } + + /// The mask's surface code. + pub fn code(self) -> u8 { + self as u8 + 1 + } + + /// The finish of a way: the port of `surfaceOf` and `trackSurface` of `terrain/bins.ts`. `town` + /// where buildings are near. + pub fn of(tags: &Tags, town: bool) -> Finish { + let tag = |key: &str| tags.get(key).map_or("", String::as_str); + if is_track(tags) { + let narrow = match leading_integer(tag("gauge")) { + Some(gauge) => gauge < NARROW_MM, + None => matches!(tag("railway"), "narrow_gauge" | "funicular"), + }; + return match (narrow, is_rack(tags)) { + (true, true) => Finish::NarrowRack, + (true, false) => Finish::Narrow, + (false, true) => Finish::Rack, + (false, false) => Finish::Rail, + }; + } + let (highway, surface) = (tag("highway"), tag("surface")); + let oneway = match tag("oneway") { + "" => matches!(highway, "motorway" | "motorway_link") || tag("junction") == "roundabout", + value => ONEWAY.contains(&value), + }; + let main = if oneway { Finish::Oneway } else { Finish::Main }; + if PAVED.contains(&surface) { + return if MAIN[..4].contains(&highway) { main } else { Finish::Road }; + } + if GRAVEL.contains(&surface) { + return Finish::Gravel; + } + if DIRT.contains(&surface) { + return Finish::Dirt; + } + if GRASS.contains(&surface) { + return Finish::Grass; + } + if town && TOWN_PATHS.contains(&highway) { + return Finish::Paving; + } + if PATHS.contains(&highway) { + return Finish::Path; + } + if highway == "track" { + return match tag("tracktype") { + "grade1" => Finish::Road, + "grade2" => Finish::Gravel, + "grade3" => Finish::Dirt, + _ => Finish::Grass, + }; + } + if MAIN.contains(&highway) { + main + } else { + Finish::Road + } + } +} + +/// The classes of road that wear lines on a paved top, and those of them that look as motorways: as +/// `MOTORWAYS` and `MAINS` of the viewer's `terrain/bins.ts`. +const MOTORWAYS: [&str; 4] = ["motorway", "motorway_link", "trunk", "trunk_link"]; +const MAINS: [&str; 6] = ["primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link"]; +const SETTS: [&str; 4] = ["sett", "cobblestone", "unhewn_cobblestone", "stone"]; + +/// What a way's paved top is made of where its OSM `surface` or its class says more than its finish: +/// the port of `lookOf` of the viewer's `roads/section.ts`. `Finish` leaves it to the finish. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Material { + Finish = 0, + Sett = 1, + Pavers = 2, + Concrete = 3, + /// A track's two concrete strips. + Strips = 4, +} + +impl Material { + pub fn of(tags: &Tags) -> Material { + let surface = tags.get("surface").map_or("", String::as_str); + let class = class_of(tags); + if is_track(tags) { + Material::Finish + } else if SETTS.contains(&surface) { + Material::Sett + } else if surface == "paving_stones" || class == "pedestrian" { + Material::Pavers + } else if surface.starts_with("concrete") { + if class == "track" { + Material::Strips + } else { + Material::Concrete + } + } else { + Material::Finish + } + } +} + +/// Whether a way wears lines, as `marked` of the viewer's `terrain/bins.ts`: a class of `MOTORWAYS` or +/// `MAINS` on a paved road's finish, of its finish's material. And whether it looks as a motorway. +pub fn marked(tags: &Tags, finish: Finish) -> (bool, bool) { + let class = class_of(tags); + let lines = (MOTORWAYS.contains(&class) || MAINS.contains(&class)) + && matches!(finish, Finish::Main | Finish::Road | Finish::Oneway) + && Material::of(tags) == Material::Finish; + (lines, lines && MOTORWAYS.contains(&class)) +} + +/// Whether a way is a track: a `railway` of the tracks and no `highway`. +pub fn is_track(tags: &Tags) -> bool { + tags.get("railway").is_some_and(|r| TRACKS.contains(&r.as_str())) && !tags.contains_key("highway") +} + +fn is_rack(tags: &Tags) -> bool { + tags.get("rack").is_some_and(|rack| rack != "no") +} + +/// The class of a way: `rack` for a rack railway, else the `railway` of a track or its `highway`. +pub fn class_of(tags: &Tags) -> &str { + if is_track(tags) { + return if is_rack(tags) { "rack" } else { &tags["railway"] }; + } + tags.get("highway").map_or("", String::as_str) +} + +/// The text without the white space that JavaScript trims before a number. +fn trim_space(text: &str) -> &str { + text.trim_start_matches(|c: char| c.is_whitespace() && c != '\u{85}' || c == '\u{feff}') +} + +/// The number at the start of a tag, as JavaScript's `parseFloat` reads it: "8 m" is 8. None where +/// it is not finite. +pub fn leading_number(text: &str) -> Option { + let text = trim_space(text); + let span = text.find(|c: char| !matches!(c, '0'..='9' | '+' | '-' | '.' | 'e' | 'E')).unwrap_or(text.len()); + (1..=span).rev().find_map(|end| text[..end].parse::().ok()).filter(|v| v.is_finite()) +} + +/// The integer at the start of a tag, as JavaScript's `parseInt(text, 10)` reads it: "1435;1000" is +/// 1435. It saturates past `i64`. +pub fn leading_integer(text: &str) -> Option { + let text = trim_space(text); + let (sign, digits) = match text.as_bytes().first() { + Some(b'-') => (-1, &text[1..]), + Some(b'+') => (1, &text[1..]), + _ => (1, text), + }; + let digits = &digits[..digits.find(|c: char| !c.is_ascii_digit()).unwrap_or(digits.len())]; + if digits.is_empty() { + return None; + } + Some(digits.bytes().fold(0i64, |n, d| n.saturating_mul(10).saturating_add(i64::from(d - b'0'))) * sign) +} + +/// The width of a waterway: the number at the start of its `width` where it is above 0, else +/// `width_m` of its row. +pub fn water_width_m(tags: &Tags, width_m: f64) -> f64 { + tags.get("width").and_then(|w| leading_number(w)).filter(|&w| w > 0.0).unwrap_or(width_m) +} + +/// The widths of one class row of `roads.json`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ClassWidths { + pub half_m: f64, + pub shoulder_m: f64, + pub sidewalk_m: f64, +} + +/// One row of `finishes.json`: a number caps the class's value, None keeps it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FinishWidths { + pub half_m: Option, + pub shoulder_m: Option, +} + +/// The widths of one way. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Widths { + /// The class's row in `roads.json`, from the most important down. + pub rank: usize, + pub finish: Finish, + pub half_m: f64, + pub shoulder_m: f64, + pub sidewalk_m: f64, +} + +impl Widths { + /// The outer half-width of the outermost band: the shoulder or the sidewalk, the wider. + pub fn outer_m(&self) -> f64 { + self.half_m + self.shoulder_m.max(self.sidewalk_m) + } +} + +/// The width rule of the ways, a pure function of its rows. The crate builds it from the embedded +/// tables, the feature bake from its step options, so both give one width per way. +#[derive(Clone, Debug, PartialEq)] +pub struct WidthRules { + classes: Vec<(String, ClassWidths)>, + road: usize, + path: usize, + /// Per finish in code order. + finishes: [FinishWidths; 12], +} + +impl WidthRules { + /// The rules, or an error that names the row and the field that break one. + pub fn new(classes: Vec<(String, ClassWidths)>, finishes: Vec<(String, FinishWidths)>) -> Result { + for (name, row) in &classes { + if !(HALF_MIN_M..=HALF_MAX_M).contains(&row.half_m) { + return Err(format!( + "roads.json {name:?}.half_m: {} is not from {HALF_MIN_M} to {HALF_MAX_M}", + row.half_m + )); + } + for (field, value) in [("shoulder_m", row.shoulder_m), ("sidewalk_m", row.sidewalk_m)] { + if !(0.0..).contains(&value) { + return Err(format!("roads.json {name:?}.{field}: {value} is not a number of 0 or more")); + } + } + } + let row = |fallback: &str| { + classes + .iter() + .position(|(name, _)| name == fallback) + .ok_or(format!("roads.json: no row {fallback:?}, the row of a class that the table lacks")) + }; + let (road, path) = (row("road")?, row("path")?); + let names: Vec<&str> = finishes.iter().map(|(name, _)| name.as_str()).collect(); + if names != Finish::NAMES { + return Err(format!("finishes.json: the finishes are {names:?}, not {:?} in code order", Finish::NAMES)); + } + for (name, row) in &finishes { + if row.half_m.is_some_and(|h| !(HALF_MIN_M..=HALF_MAX_M).contains(&h)) { + return Err(format!("finishes.json {name:?}.half_m: not from {HALF_MIN_M} to {HALF_MAX_M}")); + } + if row.shoulder_m.is_some_and(|s| !(0.0..).contains(&s)) { + return Err(format!("finishes.json {name:?}.shoulder_m: not a number of 0 or more")); + } + } + let finishes = std::array::from_fn(|at| finishes[at].1); + Ok(WidthRules { classes, road, path, finishes }) + } + + /// The widths of a way of a feature kind. A class that the table lacks takes the row `path` for + /// the kind `path`, else the row `road`. A track reads no `width`, as the viewer. + pub fn way(&self, kind: &str, tags: &Tags, town: bool) -> Widths { + let class = class_of(tags); + let fallback = if kind == "path" { self.path } else { self.road }; + let rank = self.classes.iter().position(|(name, _)| name == class).unwrap_or(fallback); + let row = self.classes[rank].1; + let finish = Finish::of(tags, town); + let caps = self.finishes[finish as usize]; + let width = (!is_track(tags)).then(|| tags.get("width").and_then(|w| leading_number(w))).flatten(); + let half_m = match width { + Some(width) => (width / 2.0).max(HALF_MIN_M), + None => caps.half_m.map_or(row.half_m, |cap| row.half_m.min(cap)), + }; + Widths { + rank, + finish, + half_m: half_m.min(HALF_MAX_M), + shoulder_m: caps.shoulder_m.map_or(row.shoulder_m, |cap| row.shoulder_m.min(cap)), + sidewalk_m: row.sidewalk_m, + } + } +} + +/// The cross-section of a way. Metres, and rise per metre for `cut` and `fill`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WaySection<'a> { + pub class: &'a str, + /// The class's row in `roads.json`, from the most important down. + pub rank: usize, + /// None for water, which has no finish. + pub finish: Option, + /// The material of its top past the finish, whether it wears lines, and whether it looks as a motorway. + pub material: Material, + pub marked: bool, + pub motorway: bool, + /// The carriageway's half-width. + pub half_m: f64, + /// The flat strip past the edge where no sidewalk is. + pub shoulder_m: f64, + /// A sidewalk's width where `walk` puts one. + pub sidewalk_m: f64, + /// The kerb's rise over the carriageway's edge, and the width of its top. + pub kerb_m: f64, + pub kerb_top_m: f64, + pub cut: f64, + pub fill: f64, + /// How far past the edge the slopes reach. + pub reach_m: f64, + /// An end within this of a carriageway's edge and `snap_height_m` of its height joins it. + pub snap_m: f64, + pub snap_height_m: f64, + /// The most that a sample chord may leave the curve at the outer edge, and in height. + pub sag_plan_m: f64, + pub sag_height_m: f64, + /// The height that this way needs under a deck, and the least opening that still reads as one. + pub clearance_m: f64, + pub clearance_least_m: f64, + /// The height of this way's tunnel bore, and the least one. + pub bore_m: f64, + pub bore_least_m: f64, + /// The thinnest deck of this way, and the thinnest roof plate over its bore. + pub deck_least_m: f64, + pub roof_least_m: f64, + /// The class group of the junction pair rules of `plan.json`. + pub group: &'a str, + /// A way of a path class (`group` path or steps): its dirt or grass wears a trail's tread, as + /// `lookOf` of the viewer's `roads/section.ts`. + pub path: bool, + /// A deck of this class has a railing on its free outline, not a parapet (`group` path, steps, track or rail). + pub railing: bool, + /// The least radius of an inward corner's inner edge; 0: no round at the way's turns and corners. + pub inner_radius_m: f64, + /// The radius of a junction corner, and of one with a sidewalk on its side; a corner takes the + /// lesser of its two arms' values. 0: a sharp corner. + pub corner_radius_m: f64, + pub corner_radius_walk_m: f64, + pub shoulder_paved: bool, + /// The band past the shoulder, before the slope. + pub verge_m: f64, + /// The grade at which a guest's return ramp climbs back to its own heights. + pub return_grade: f64, + /// The steepest fill and cut, rise per metre, before the rest of a height difference is a wall. + pub fill_max: f64, + pub cut_max: f64, + /// The most that a bend's alignment widens the half-width. + pub widen_m: f64, + /// Whether the way splits into legs (`faces::legs`) where it passes beside itself at heights a + /// step apart, and a wall stands between them. Else it stays one line, whose heights blend its + /// parts into one bank. + pub leg_wall: bool, + /// A water line (`Sections::water_way`): its fill cone starts `rise_m` over the water and `crest_m` + /// past the waterline. Both are 0 for a way. + pub water: bool, + pub rise_m: f64, + pub crest_m: f64, +} + +impl WaySection<'_> { + /// The outer half-width of the bands up to the verge: the shoulder or the sidewalk, the wider. + pub fn outer_m(&self) -> f64 { + self.half_m + self.shoulder_m.max(self.sidewalk_m) + } +} + +/// The fields of a class row that the faces' rules check. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ClassFaces<'a> { + pub group: &'a str, + pub shoulder_m: f64, + pub reach_m: f64, + pub verge_m: f64, + pub return_grade: f64, + pub inner_radius_m: f64, + pub corner_radius_m: f64, + pub corner_radius_walk_m: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WaterSection { + /// The row's index in `waterways.json`. + pub rank: usize, + /// The width: `width`, else `width_m` of the row; and half of it, at most `HALF_MAX_M`. + pub width_m: f64, + pub half_m: f64, + pub cut: f64, + pub fill: f64, + pub reach_m: f64, + pub culvert_max_m: f64, + /// The widest water that an untagged road, track or railway crosses on a culvert. + pub culvert_width_m: f64, + /// An untagged path crosses water up to this width on a pipe in stones, then on stepping stones. + pub pipe_width_m: f64, + pub stones_width_m: f64, + /// The height over the water that a deck needs, and the least that still reads as an opening. + pub clearance_m: f64, + pub clearance_least_m: f64, + /// The most that a sample chord may leave the curve at the bank, and in height. + pub sag_plan_m: f64, + pub sag_height_m: f64, + /// A vertex where the water turns by more than this is a corner: its two spans are chords. + pub curve_turn_max_deg: f64, + /// A span whose curve leaves its mapped chord by more than this is its chord: the bake reads the + /// terrain for the water's level within the half-width and 2 m of the mapped line. + pub curve_off_max_m: f64, + /// Water more than this under the terrain is underground: the ground plan draws none there. + pub underground_m: f64, +} + +/// One row of the reach table: a reach, or a chain whose value is the sum of its terms. +#[derive(Clone, Debug, PartialEq)] +pub struct Reach { + pub name: String, + /// The module of the crate that owns the row, such as `sections`. + pub owner: &'static str, + pub chain: bool, + /// (what, metres). + pub terms: Vec<(String, f64)>, +} + +impl Reach { + pub fn metres(&self) -> f64 { + self.terms.iter().map(|(_, m)| m).sum() + } +} + +/// The fields of a class row besides its widths. +#[derive(Clone, Debug, PartialEq)] +struct Row { + name: String, + kerb_m: f64, + kerb_top_m: f64, + cut: f64, + fill: f64, + reach_m: f64, + /// The most that a bend's alignment widens the half-width. + widen_m: f64, + /// `GRAPH_FIELDS`. + graph: [f64; 10], + group: String, + shoulder_paved: bool, + leg_wall: bool, + /// `FACE_FIELDS`. + face: [f64; 7], +} + +#[derive(Clone, Debug, PartialEq)] +struct WaterRow { + name: String, + width_m: f64, + cut: f64, + fill: f64, + reach_m: f64, + /// `WATER_GRAPH_FIELDS`. + graph: [f64; 11], + /// `WATER_BANK_FIELDS`. + bank: [f64; 6], +} + +/// The rule tables of the cross-sections. +#[derive(Clone, Debug, PartialEq)] +pub struct Sections { + classes: Vec, + widths: WidthRules, + waters: Vec, + reaches: Vec, +} + +fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map, String> { + value.as_object().ok_or_else(|| format!("{what}: not an object")) +} + +/// A field that is a number, or an error that names the row and the field. +fn number(row: &Map, table: &str, name: &str, field: &str) -> Result { + match row.get(field) { + Some(Value::Object(_)) => Err(format!("{table} {name:?}.{field}: a value by place is not read yet")), + Some(value) => value.as_f64().ok_or_else(|| format!("{table} {name:?}.{field}: not a number")), + None => Err(format!("{table} {name:?}: no field {field}")), + } +} + +/// The fields of a row, each a number of 0 or more. +fn fields( + row: &Map, + table: &str, + name: &str, + names: [&str; N], +) -> Result<[f64; N], String> { + let mut out = [0.0; N]; + for (value, field) in out.iter_mut().zip(names) { + *value = number(row, table, name, field)?; + if *value < 0.0 { + return Err(format!("{table} {name:?}.{field}: below 0")); + } + } + Ok(out) +} + +fn nullable(row: &Map, name: &str, field: &str) -> Result, String> { + match row.get(field) { + Some(Value::Null) => Ok(None), + _ => number(row, "finishes.json", name, field).map(Some), + } +} + +impl Sections { + /// The committed tables, parsed once. It panics on an invalid table; a test parses them. + pub fn embedded() -> &'static Sections { + static SECTIONS: OnceLock = OnceLock::new(); + SECTIONS.get_or_init(|| { + Sections::parse( + include_str!("../../../data/trailview/roads.json"), + include_str!("../../../data/trailview/finishes.json"), + include_str!("../../../data/trailview/waterways.json"), + ) + .unwrap_or_else(|e| panic!("data/trailview: {e}")) + }) + } + + /// The tables, or an error that names the row and the field that break a rule. + pub fn parse(roads: &str, finishes: &str, waterways: &str) -> Result { + let json = |text: &str, table: &str| serde_json::from_str::(text).map_err(|e| format!("{table}: {e}")); + let (mut classes, mut widths) = (Vec::new(), Vec::new()); + for (name, row) in object(&json(roads, "roads.json")?, "roads.json")? { + let row = object(row, &format!("roads.json {name:?}"))?; + let [half_m, shoulder_m, sidewalk_m, kerb_m, kerb_top_m, cut, fill, reach_m, widen_m] = + CLASS_FIELDS.map(|field| number(row, "roads.json", name, field)); + let class = ClassWidths { half_m: half_m?, shoulder_m: shoulder_m?, sidewalk_m: sidewalk_m? }; + let row = Row { + name: name.clone(), + kerb_m: kerb_m?, + kerb_top_m: kerb_top_m?, + cut: cut?, + fill: fill?, + reach_m: reach_m?, + widen_m: widen_m?, + graph: fields(row, "roads.json", name, GRAPH_FIELDS)?, + group: (row.get("group").and_then(Value::as_str)) + .ok_or_else(|| format!("roads.json {name:?}.group: not a name"))? + .to_string(), + shoulder_paved: (row.get("shoulder_paved").and_then(Value::as_bool)) + .ok_or_else(|| format!("roads.json {name:?}.shoulder_paved: not true or false"))?, + leg_wall: (row.get("leg_wall").and_then(Value::as_bool)) + .ok_or_else(|| format!("roads.json {name:?}.leg_wall: not true or false"))?, + face: fields(row, "roads.json", name, FACE_FIELDS)?, + }; + let fields = [row.kerb_m, row.kerb_top_m, row.cut, row.fill, row.reach_m, row.widen_m]; + if let Some(at) = fields.iter().position(|&v| v < 0.0) { + return Err(format!("roads.json {name:?}.{}: below 0", CLASS_FIELDS[at + 3])); + } + let walk = class.sidewalk_m > 0.0; + if (row.kerb_m > 0.0) != walk || (row.kerb_top_m > 0.0) != walk { + return Err(format!( + "roads.json {name:?}: kerb_m and kerb_top_m are over 0 exactly where sidewalk_m is" + )); + } + if HALF_MAX_M + row.widen_m + row.graph[0] > crate::graph::SNAP_REACH_M { + return Err(format!( + "roads.json {name:?}: HALF_MAX_M + widen_m + snap_m is over the graph's SNAP_REACH_M" + )); + } + classes.push(row); + widths.push((name.clone(), class)); + } + let mut finish_rows = Vec::new(); + for (name, row) in object(&json(finishes, "finishes.json")?, "finishes.json")? { + let row = object(row, &format!("finishes.json {name:?}"))?; + if let Some(field) = row.keys().find(|f| !["half_m", "shoulder_m"].contains(&f.as_str())) { + return Err(format!("finishes.json {name:?}: an unknown field {field}")); + } + let caps = + FinishWidths { half_m: nullable(row, name, "half_m")?, shoulder_m: nullable(row, name, "shoulder_m")? }; + finish_rows.push((name.clone(), caps)); + } + let widths = WidthRules::new(widths, finish_rows)?; + let mut waters = Vec::new(); + for (name, row) in object(&json(waterways, "waterways.json")?, "waterways.json")? { + let row = object(row, &format!("waterways.json {name:?}"))?; + let [width_m, cut, fill, reach_m] = WATER_FIELDS.map(|field| number(row, "waterways.json", name, field)); + let graph = fields(row, "waterways.json", name, WATER_GRAPH_FIELDS)?; + let bank = fields(row, "waterways.json", name, WATER_BANK_FIELDS)?; + let row = WaterRow { + name: name.clone(), + width_m: width_m?, + cut: cut?, + fill: fill?, + reach_m: reach_m?, + graph, + bank, + }; + if row.width_m <= 0.0 || [row.cut, row.fill, row.reach_m].iter().any(|&v| v < 0.0) { + return Err(format!("waterways.json {name:?}: a width over 0, slopes and reach of 0 or more")); + } + // The bank rises at `bank_slope` to the rise, which the crest holds; both lie within the bank's + // reach, and that within the row's reach. + let [_, slope, reach, _, rise, crest] = row.bank; + if slope <= 0.0 || crest < rise / slope || rise / slope >= reach || reach > row.reach_m { + return Err(format!( + "waterways.json {name:?}: bank_slope over 0, bank_m at least freeboard_m / bank_slope, \ + which is under bank_reach_m, and that at most reach" + )); + } + if row.graph[0] > CULVERT_MAX_M { + return Err(format!("waterways.json {name:?}.culvert_max_m: over {CULVERT_MAX_M}, the graph's read")); + } + waters.push(row); + } + for fallback in ["river", "stream"] { + if !waters.iter().any(|row| row.name == fallback) { + return Err(format!("waterways.json: no row {fallback:?}")); + } + } + let mut reaches = reach_rows(&classes, &widths, &waters); + let culvert_m = waters.iter().map(|row| row.graph[0]).fold(0.0, f64::max); + reaches.extend(crate::graph::reach_rows(culvert_m)); + let bank_m = waters.iter().map(|row| row.bank[2]).fold(0.0, f64::max); + reaches.extend(crate::faces::culverts::reach_rows(bank_m, culvert_m)); + for row in reaches.iter().filter(|row| row.chain) { + if row.metres() > CHAIN_MAX_M { + let terms: Vec = row.terms.iter().map(|(what, m)| format!("{what} {m} m")).collect(); + return Err(format!( + "the chain {:?} of {} is {} m = {}, over CHAIN_MAX_M {CHAIN_MAX_M} m", + row.name, + row.owner, + row.metres(), + terms.join(" + ") + )); + } + } + Ok(Sections { classes, widths, waters, reaches }) + } + + /// The cross-section of a way of a feature kind. A class that the table lacks takes the row + /// `path` for the kind `path`, else the row `road`. + /// A kind of line water (`WATER_KINDS`) takes its water section (`water_way`). + pub fn way(&self, kind: &str, tags: &Tags, town: bool) -> WaySection<'_> { + if WATER_KINDS.contains(&kind) { + return self.water_way(kind, tags); + } + let Widths { rank, finish, half_m, shoulder_m, sidewalk_m } = self.widths.way(kind, tags, town); + let row = &self.classes[rank]; + let (marked, motorway) = marked(tags, finish); + WaySection { + class: &row.name, + rank, + finish: Some(finish), + material: Material::of(tags), + marked, + motorway, + half_m, + shoulder_m, + sidewalk_m, + kerb_m: row.kerb_m, + kerb_top_m: row.kerb_top_m, + cut: row.cut, + fill: row.fill, + reach_m: row.reach_m, + snap_m: row.graph[0], + snap_height_m: row.graph[1], + sag_plan_m: row.graph[2], + sag_height_m: row.graph[3], + clearance_m: row.graph[4], + clearance_least_m: row.graph[5], + bore_m: row.graph[6], + bore_least_m: row.graph[7], + deck_least_m: row.graph[8], + roof_least_m: row.graph[9], + group: &row.group, + path: matches!(row.group.as_str(), "path" | "steps"), + railing: matches!(row.group.as_str(), "path" | "steps" | "track" | "rail"), + inner_radius_m: row.face[0], + corner_radius_m: row.face[3], + corner_radius_walk_m: row.face[4], + shoulder_paved: row.shoulder_paved, + leg_wall: row.leg_wall, + widen_m: row.widen_m, + verge_m: row.face[1], + return_grade: row.face[2], + fill_max: row.face[5], + cut_max: row.face[6], + water: false, + rise_m: 0.0, + crest_m: 0.0, + } + } + + /// The faces' section of a line water way: its half-width, no shoulder and no verge, the bank's + /// slopes, reach, rise and crest, no wall and no legs, and no corner rounds (a confluence keeps its + /// wedge). Its class follows every way class, so the + /// painter and the candidates put water after every way; its group is `water`. + pub fn water_way(&self, kind: &str, tags: &Tags) -> WaySection<'_> { + let w = self.water(kind, tags); + let row = &self.waters[w.rank]; + let [_, bank_slope, bank_reach_m, bank_steepest, rise_m, crest_m] = row.bank; + WaySection { + class: &row.name, + rank: self.classes.len() + w.rank, + finish: None, + material: Material::Finish, + marked: false, + motorway: false, + half_m: w.half_m, + shoulder_m: 0.0, + sidewalk_m: 0.0, + kerb_m: 0.0, + kerb_top_m: 0.0, + cut: bank_slope, + fill: w.fill, + reach_m: bank_reach_m, + snap_m: 0.0, + snap_height_m: 0.0, + sag_plan_m: w.sag_plan_m, + sag_height_m: w.sag_height_m, + clearance_m: w.clearance_m, + clearance_least_m: w.clearance_least_m, + bore_m: 0.0, + bore_least_m: 0.0, + deck_least_m: 0.0, + roof_least_m: 0.0, + group: "water", + path: false, + railing: false, + inner_radius_m: 0.0, + corner_radius_m: 0.0, + corner_radius_walk_m: 0.0, + shoulder_paved: false, + verge_m: 0.0, + return_grade: 0.0, + fill_max: bank_steepest, + cut_max: bank_steepest, + widen_m: 0.0, + leg_wall: false, + water: true, + rise_m, + crest_m, + } + } + + /// The width rule of the ways. + pub fn widths(&self) -> &WidthRules { + &self.widths + } + + /// The cross-section of a waterway: the row of its `waterway` value, else `river` for the kind + /// `river`, else `stream`. + pub fn water(&self, kind: &str, tags: &Tags) -> WaterSection { + let value = tags.get("waterway").map_or("", String::as_str); + let fallback = if kind == "river" { "river" } else { "stream" }; + let rank = (self.waters.iter().position(|row| row.name == value)) + .or_else(|| self.waters.iter().position(|row| row.name == fallback)) + .expect("parse keeps the rows river and stream"); + let row = &self.waters[rank]; + let width = water_width_m(tags, row.width_m); + let [culvert_max_m, culvert_width_m, pipe_width_m, stones_width_m, clearance_m, clearance_least_m, sag_plan_m, sag_height_m, curve_turn_max_deg, curve_off_max_m, underground_m] = + row.graph; + WaterSection { + rank, + width_m: width, + half_m: (width / 2.0).min(HALF_MAX_M), + cut: row.cut, + fill: row.fill, + reach_m: row.reach_m, + culvert_max_m, + culvert_width_m, + pipe_width_m, + stones_width_m, + clearance_m, + clearance_least_m, + sag_plan_m, + sag_height_m, + curve_turn_max_deg, + curve_off_max_m, + underground_m, + } + } + + /// The class row of a rank as the faces' rules check it; None past the table. + pub fn class_faces(&self, rank: usize) -> Option> { + self.classes.get(rank).map(|row| ClassFaces { + group: &row.group, + shoulder_m: self.widths.classes[rank].1.shoulder_m, + reach_m: row.reach_m, + verge_m: row.face[1], + return_grade: row.face[2], + inner_radius_m: row.face[0], + corner_radius_m: row.face[3], + corner_radius_walk_m: row.face[4], + }) + } + + /// The bank reach of each water row. + pub fn bank_reaches(&self) -> impl Iterator + '_ { + self.waters.iter().map(|row| row.bank[2]) + } + + /// The name of the class of a rank, or of the water kind of a water rank. + pub fn rank_name(&self, water: bool, rank: usize) -> &str { + if water { + &self.waters[rank].name + } else { + &self.classes[rank].name + } + } + + /// Every reach and chain of rules. + pub fn reaches(&self) -> &[Reach] { + &self.reaches + } +} + +/// The rows of this module in the reach table. +fn reach_rows(classes: &[Row], widths: &WidthRules, waters: &[WaterRow]) -> Vec { + let term = |what: &str, metres: f64| (what.to_string(), metres); + let reach = |name: &str, metres: f64| Reach { + name: name.into(), + owner: "sections", + chain: false, + terms: vec![term(name, metres)], + }; + let widest = |values: &mut dyn Iterator| { + values.fold((String::new(), 0.0), |best, (name, m)| if m > best.1 { (name, m) } else { best }) + }; + let road_reach = widest(&mut classes.iter().map(|row| (row.name.clone(), row.reach_m))); + let water_reach = widest(&mut waters.iter().map(|row| (row.name.clone(), row.reach_m))); + let slope = widest(&mut classes.iter().zip(&widths.classes).map(|(row, (_, w))| { + (row.name.clone(), row.widen_m + w.shoulder_m.max(w.sidewalk_m) + row.face[1] + row.reach_m) + })); + vec![ + reach("MARGIN_M", MARGIN_M), + reach("HALF_MAX_M", HALF_MAX_M), + reach(&format!("reach of roads.json {:?}", road_reach.0), road_reach.1), + reach(&format!("reach of waterways.json {:?}", water_reach.0), water_reach.1), + Reach { + name: "way slope".into(), + owner: "sections", + chain: true, + terms: vec![ + term("HALF_MAX_M", HALF_MAX_M), + term(&format!("widen_m + max(shoulder_m, sidewalk_m) + verge_m + reach of {:?}", slope.0), slope.1), + ], + }, + Reach { + name: "water bank".into(), + owner: "sections", + chain: true, + terms: vec![term("HALF_MAX_M", HALF_MAX_M), term(&format!("reach of {:?}", water_reach.0), water_reach.1)], + }, + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tags(pairs: &[(&str, &str)]) -> Tags { + pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() + } + + const ROADS: &str = include_str!("../../../data/trailview/roads.json"); + const FINISHES: &str = include_str!("../../../data/trailview/finishes.json"); + const WATERWAYS: &str = include_str!("../../../data/trailview/waterways.json"); + + #[test] + fn the_committed_tables_give_the_viewers_widths() { + let s = Sections::embedded(); + let way = |kind: &str, pairs: &[(&str, &str)], town: bool| { + let w = s.way(kind, &tags(pairs), town); + (w.finish.expect("a way has a finish"), w.half_m, w.shoulder_m) + }; + // Golden values of halfWidth, surfaceOf and SHOULDER_M of terrain/bins.ts. + assert_eq!(way("main-road", &[("highway", "primary")], false), (Finish::Main, 4.0, 0.6)); + assert_eq!( + way("main-road", &[("highway", "primary"), ("surface", "gravel")], false), + (Finish::Gravel, 1.75, 0.3) + ); + assert_eq!(way("road", &[("highway", "residential"), ("width", "3 m")], false), (Finish::Road, 1.5, 0.4)); + assert_eq!(way("road", &[("highway", "track")], false), (Finish::Grass, 1.25, 0.2)); + assert_eq!(way("road", &[("highway", "track"), ("tracktype", "grade1")], false), (Finish::Road, 3.0, 0.4)); + assert_eq!(way("path", &[("highway", "path"), ("surface", "gravel")], false), (Finish::Gravel, 1.0, 0.0)); + assert_eq!(way("path", &[("highway", "pedestrian")], true), (Finish::Paving, 1.25, 0.0)); + assert_eq!(way("path", &[("highway", "cycleway")], false), (Finish::Road, 1.5, 0.0)); + assert_eq!(way("railway", &[("railway", "rail"), ("gauge", "1000")], false), (Finish::Narrow, 1.5, 0.35)); + assert_eq!(way("railway", &[("railway", "rail"), ("rack", "yes")], false), (Finish::Rack, 1.9, 0.35)); + assert_eq!( + way("railway", &[("railway", "rail"), ("gauge", "1435;1000"), ("width", "9")], false), + (Finish::Rail, 1.9, 0.35) + ); + assert_eq!(way("road", &[("highway", "raceway")], false), (Finish::Road, 3.0, 0.4)); + assert_eq!(way("main-road", &[("highway", "motorway_link")], false), (Finish::Oneway, 4.5, 0.6)); + assert_eq!( + way("main-road", &[("highway", "primary_link"), ("surface", "asphalt")], false), + (Finish::Road, 3.0, 0.4) + ); + assert_eq!(s.way("railway", &tags(&[("railway", "rail"), ("rack", "yes")]), false).class, "rack"); + assert_eq!(s.way("path", &tags(&[("highway", "steps")]), false).rank, 25); + let main = s.way("main-road", &tags(&[("highway", "secondary")]), false); + assert_eq!((main.sidewalk_m, main.kerb_m, main.kerb_top_m, main.reach_m), (2.0, 0.12, 0.16, 10.0)); + } + + #[test] + fn odd_widths_follow_parse_float() { + let s = Sections::embedded(); + let half = |width: &str| s.way("road", &tags(&[("highway", "residential"), ("width", width)]), false).half_m; + assert_eq!( + [half("60"), half("1e9"), half("3,5"), half("-2"), half("0"), half(" 4.5m")], + [15.0, 15.0, 1.5, 0.4, 0.4, 2.25] + ); + assert_eq!([half("~4"), half("nan"), half("")], [2.5; 3]); + let n = leading_number; + assert_eq!((n(" -2.5e1x"), n("1e"), n("1e+"), n("5-3")), (Some(-25.0), Some(1.0), Some(1.0), Some(5.0))); + assert_eq!((n("m8"), n("."), n(""), n("+-5"), n("inf")), (None, None, None, None, None)); + assert_eq!((n("1e309"), n("\u{feff}2"), n("\u{85}2")), (None, Some(2.0), None)); + assert_eq!( + [leading_integer("1435;1000"), leading_integer(" -5x"), leading_integer("x5")], + [Some(1435), Some(-5), None] + ); + let water = |kind: &str, pairs: &[(&str, &str)]| s.water(kind, &tags(pairs)).half_m; + assert_eq!(water("stream", &[("waterway", "stream")]), 0.5); + assert_eq!(water("river", &[("waterway", "canal"), ("width", "0")]), 5.0); + assert_eq!(water("river", &[("waterway", "brook"), ("width", "40")]), 15.0); + } + + #[test] + fn a_broken_table_names_its_row_and_field() { + let fails = |roads: &str, finishes: &str| Sections::parse(roads, finishes, WATERWAYS).unwrap_err(); + let kerb = ROADS.replacen(r#""kerb_m": 0,"#, r#""kerb_m": 0.1,"#, 1); + assert!(fails(&kerb, FINISHES).contains(r#""rail": kerb_m and kerb_top_m"#)); + let missing = ROADS.replacen(r#", "kerb_top_m": 0"#, "", 1); + assert!(fails(&missing, FINISHES).contains(r#"roads.json "rail": no field kerb_top_m"#)); + let missing = ROADS.replacen(r#", "snap_m": 1"#, "", 1); + assert!(fails(&missing, FINISHES).contains(r#"roads.json "rail": no field snap_m"#)); + let long = WATERWAYS.replacen(r#""culvert_max_m": 60"#, r#""culvert_max_m": 61"#, 1); + let message = Sections::parse(ROADS, FINISHES, &long).unwrap_err(); + assert!(message.contains(r#"waterways.json "river".culvert_max_m: over 60"#), "{message}"); + let by_place = ROADS.replacen(r#""half_m": 1.9"#, r#""half_m": {"CH": 1.9}"#, 1); + assert!(fails(&by_place, FINISHES).contains("a value by place")); + let order = FINISHES.replacen(r#""main""#, r#""tmp""#, 1).replacen(r#""road""#, r#""main""#, 1).replacen( + r#""tmp""#, + r#""road""#, + 1, + ); + assert!(fails(ROADS, &order).contains("in code order")); + let far = ROADS.replacen(r#""reach": 10"#, r#""reach": 180"#, 1); + let message = fails(&far, FINISHES); + assert!(message.contains(r#"the chain "way slope" of sections is 195.3"#), "{message}"); + assert!( + message.contains(r#"reach of "rail" 180.3"#) && message.contains("over CHAIN_MAX_M 191 m"), + "{message}" + ); + } + + #[test] + fn the_width_rule_checks_its_rows_and_a_water_width_falls_back_to_its_row() { + let class = |half_m: f64| ClassWidths { half_m, shoulder_m: 0.4, sidewalk_m: 0.0 }; + let finishes: Vec<(String, FinishWidths)> = Finish::ALL + .iter() + .map(|f| (f.name().to_string(), FinishWidths { half_m: None, shoulder_m: None })) + .collect(); + let rules = |rows: &[(&str, f64)], finishes: &[(String, FinishWidths)]| { + WidthRules::new(rows.iter().map(|&(n, h)| (n.to_string(), class(h))).collect(), finishes.to_vec()) + }; + assert!(rules(&[("road", 3.0), ("path", 1.0)], &finishes).is_ok()); + assert!(rules(&[("path", 1.0)], &finishes).unwrap_err().contains(r#"no row "road""#)); + assert!(rules(&[("road", 0.3), ("path", 1.0)], &finishes).unwrap_err().contains(r#""road".half_m"#)); + let mut swapped = finishes.clone(); + swapped.swap(0, 1); + assert!(rules(&[("road", 3.0), ("path", 1.0)], &swapped).unwrap_err().contains("in code order")); + let width = |w: Option<&str>| water_width_m(&w.map_or_else(Tags::new, |w| tags(&[("width", w)])), 1.0); + assert_eq!( + [width(Some("0")), width(Some("-1")), width(Some("wide")), width(None), width(Some("2.5 m"))], + [1.0, 1.0, 1.0, 1.0, 2.5] + ); + let primary = Sections::embedded().widths().way("main-road", &tags(&[("highway", "primary")]), false); + assert_eq!((primary.half_m, primary.outer_m()), (4.0, 6.0)); + } + + #[test] + fn the_reach_table_holds_gp1s_rows() { + let rows: Vec<(String, bool, f64)> = + Sections::embedded().reaches().iter().map(|r| (r.name.clone(), r.chain, r.metres())).collect(); + assert!(rows.contains(&("way slope".into(), true, 29.0)), "{rows:?}"); + assert!(rows.contains(&("water bank".into(), true, 30.0)), "{rows:?}"); + assert!(rows.contains(&("MARGIN_M".into(), false, 192.0)), "{rows:?}"); + assert!(rows.contains(&("graph synthetic deck".into(), true, 80.0)), "{rows:?}"); + } +} diff --git a/host/obc-ground-plan/src/terrain.rs b/host/obc-ground-plan/src/terrain.rs new file mode 100644 index 0000000000..fa5cba098c --- /dev/null +++ b/host/obc-ground-plan/src/terrain.rs @@ -0,0 +1,292 @@ +//! The terrain heights of a cell: the Catmull-Rom of `terrain/pages.wgsl` over the stored pages' +//! own 16-bit codes, at level 14 and then 13. +//! +//! The crate leaves out the 16-bit step of the viewer's synthesized pages (under 1 mm for 100 m of +//! relief over a level-18 node). It stops at level 13: where a zoom-12 tile knows no height, the +//! viewer goes on to coarser levels and the crate answers None. + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::frame::{CellKey, GlobalPoint, CELL_UNITS, FRAME_BITS}; + +/// Texels along a page edge. +pub const PAGE: usize = 256; +/// The code of an unknown height. +pub const UNKNOWN: u16 = 0xffff; +/// The levels of the stored pages, finest first: zoom-13 and zoom-12 tiles. +const LEVELS: [u8; 2] = [14, 13]; + +/// One stored page: 256 × 256 codes, row by row from north, as the viewer's `PageData` holds them. +/// A height is `offset + code × scale` in `f32`. +#[derive(Clone, Debug, PartialEq)] +pub struct StoredPage { + pub level: u8, + pub x: u32, + pub y: u32, + pub offset: f32, + pub scale: f32, + pub codes: Vec, +} + +/// The terrain node of a page. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct PageKey { + pub level: u8, + pub x: u32, + pub y: u32, +} + +impl PageKey { + /// The stored tile (z, x, y) that holds the page, and its quadrant: 0 north-west, 1 north-east, + /// 2 south-west, 3 south-east. + pub fn tile(self) -> (u32, u32, u32, usize) { + (u32::from(self.level) - 1, self.x >> 1, self.y >> 1, ((self.x & 1) | (self.y & 1) << 1) as usize) + } +} + +/// The height of pixel `p` of a Terrarium tile's RGBA bytes: unknown unless it is opaque. +fn terrarium(rgba: &[u8], p: usize) -> Option { + let [r, g, b, a] = [rgba[p], rgba[p + 1], rgba[p + 2], rgba[p + 3]]; + (a == 255).then(|| f32::from(r) * 256.0 + f32::from(g) + f32::from(b) / 256.0 - 32768.0) +} + +/// The pages of the four quadrants of a 512 px Terrarium tile z/x/y: the port of `tilePages` and +/// `pageData` of `stream/heights.ts`. A quadrant without a known height has no page. +pub fn pages_from_terrarium( + rgba: &[u8], + size: usize, + z: u32, + x: u32, + y: u32, +) -> Result<[Option; 4], String> { + if size != 2 * PAGE || rgba.len() != 4 * size * size { + return Err(format!("a terrain tile has {size} px and {} bytes, not {} px", rgba.len(), 2 * PAGE)); + } + let heights: Vec = (0..size * size).map(|p| terrarium(rgba, 4 * p).unwrap_or(f32::NAN)).collect(); + Ok(pages_from_heights(&heights, z, x, y)) +} + +/// `pages_from_terrarium` of the tile's heights, row by row from north, NaN where unknown. +pub fn pages_from_heights(heights: &[f32], z: u32, x: u32, y: u32) -> [Option; 4] { + let size = 2 * PAGE; + std::array::from_fn(|q| { + // A height is exact in f32: 15 bits of metres and 8 of fraction. + let heights: Vec> = (0..PAGE * PAGE) + .map(|t| heights[(t / PAGE + (q >> 1) * PAGE) * size + t % PAGE + (q & 1) * PAGE]) + .map(|h| (!h.is_nan()).then_some(h)) + .collect(); + let known = heights.iter().flatten(); + let min = known.clone().copied().reduce(f32::min)?; + let max = known.copied().reduce(f32::max)?; + let scale = ((f64::from(max) - f64::from(min)) / f64::from(UNKNOWN - 1)).max(1e-4); + let codes = heights + .iter() + .map(|h| h.map_or(UNKNOWN, |h| ((f64::from(h) - f64::from(min)) / scale).round() as u16)) + .collect(); + let (dx, dy) = ((q & 1) as u32, (q >> 1) as u32); + Some(StoredPage { level: (z + 1) as u8, x: 2 * x + dx, y: 2 * y + dy, offset: min, scale: scale as f32, codes }) + }) +} + +/// The stored pages of a cell. +#[derive(Clone, Debug, Default)] +pub struct Terrain { + pages: BTreeMap, +} + +/// Catmull-Rom weights of the four texels about a part t, as `spline` of `pages.wgsl`. +fn spline(t: f64) -> [f64; 4] { + let (t2, t3) = (t * t, t * t * t); + [0.5 * (-t + 2.0 * t2 - t3), 0.5 * (2.0 - 5.0 * t2 + 3.0 * t3), 0.5 * (t + 4.0 * t2 - 3.0 * t3), 0.5 * (-t2 + t3)] +} + +impl Terrain { + /// The terrain of a cell from the pages that `wanted(key)` lists; it drops any other page, so + /// the heights depend on the cell alone, whatever more a caller gives. + pub fn new(key: CellKey, pages: Vec) -> Terrain { + let wanted: BTreeSet = Terrain::wanted(key).into_iter().collect(); + let pages = pages.into_iter().map(|page| (PageKey { level: page.level, x: page.x, y: page.y }, page)); + Terrain { pages: pages.filter(|(key, _)| wanted.contains(key)).collect() } + } + + /// The pages that a cell reads: per level, each page that holds a texel of the cell grown by its + /// margin and 2 texels, the reach of the bicubic. A caller gives each of them that exists. + pub fn wanted(key: CellKey) -> Vec { + let (o, m) = (key.origin(), key.margin()); + let mut out = Vec::new(); + for level in LEVELS { + let texel = 1i64 << texel_shift(level); + let (lo, hi) = (|v: i64| v - m - 2 * texel, |v: i64| v + CELL_UNITS + m + 2 * texel); + let shift = texel_shift(level) + 8; + let last = (1i64 << level) - 1; + let span = |v: i64| (lo(v) >> shift).max(0)..=(hi(v) >> shift).min(last); + for y in span(o.y) { + out.extend(span(o.x).map(|x| PageKey { level, x: x as u32, y: y as u32 })); + } + } + out + } + + /// The height in metres at a point: the bicubic of the finest stored level whose 16 texels about + /// the point are known. It steps where the level changes, as the GPU's does. + pub fn height(&self, p: GlobalPoint) -> Option { + LEVELS.iter().find_map(|&level| self.bicubic(level, p)) + } + + fn bicubic(&self, level: u8, p: GlobalPoint) -> Option { + let s = texel_shift(level); + let (vx, vy) = (p.x - (1 << (s - 1)), p.y - (1 << (s - 1))); + let mask = (1i64 << s) - 1; + let size = (1i64 << s) as f64; + let (wx, wy) = (spline((vx & mask) as f64 / size), spline((vy & mask) as f64 / size)); + let (tx, ty) = (vx >> s, vy >> s); + let mut page: Option<&StoredPage> = None; + let mut sum = 0.0; + for (j, wy) in wy.iter().enumerate() { + for (i, wx) in wx.iter().enumerate() { + let (x, y) = (tx + i as i64 - 1, ty + j as i64 - 1); + if x < 0 || y < 0 { + return None; + } + let key = PageKey { level, x: (x >> 8) as u32, y: (y >> 8) as u32 }; + let held = match page { + Some(held) if held.x == key.x && held.y == key.y => held, + _ => *page.insert(self.pages.get(&key)?), + }; + let code = held.codes[(y & 255) as usize * PAGE + (x & 255) as usize]; + if code == UNKNOWN { + return None; + } + let h = f64::from(held.offset + f32::from(code) * held.scale); + sum += h * wx * wy; + } + } + Some(sum) + } +} + +/// log2 of frame units per texel at a level: a texel is 2^(22 − level) world units. +fn texel_shift(level: u8) -> u32 { + FRAME_BITS - 8 - u32::from(level) +} + +#[cfg(test)] +mod tests { + use super::*; + + const LEVEL: u8 = 14; + const TEXEL: i64 = 1 << 12; + + /// A quadratic surface in texels of level 14 from (px, py) of page (0, 0) of the area. + fn quadratic(x: f64, y: f64) -> f64 { + 1000.0 + 0.8 * x - 0.3 * y + 0.002 * x * x + 0.001 * x * y - 0.0015 * y * y + } + + /// The pages of a level from `first` that hold `surface` at their texel centres. + fn pages(level: u8, first: (u32, u32), count: u32, surface: impl Fn(f64, f64) -> f64) -> Vec { + let mut out = Vec::new(); + for py in first.1..first.1 + count { + for px in first.0..first.0 + count { + let heights: Vec = (0..PAGE * PAGE) + .map(|t| { + let (x, y) = + ((px - first.0) as usize * PAGE + t % PAGE, (py - first.1) as usize * PAGE + t / PAGE); + surface(x as f64, y as f64) as f32 + }) + .collect(); + let min = heights.iter().copied().reduce(f32::min).unwrap(); + let max = heights.iter().copied().reduce(f32::max).unwrap(); + let scale = ((f64::from(max) - f64::from(min)) / 65534.0).max(1e-4); + let codes = heights.iter().map(|&h| ((f64::from(h) - f64::from(min)) / scale).round() as u16).collect(); + out.push(StoredPage { level, x: px, y: py, offset: min, scale: scale as f32, codes }); + } + } + out + } + + const FIRST: (u32, u32) = (8572, 5776); + /// The cell at the south-east corner of the first page: it wants the first 2 × 2 pages of level 14. + const CELL: CellKey = CellKey { x: 8572 * 4 + 3, y: 5776 * 4 + 3 }; + + /// The frame point at texel coordinates (x, y) of level 14 from the first page. + fn at(x: f64, y: f64) -> GlobalPoint { + let origin = |page: u32| i64::from(page) * 256 * TEXEL; + // Texel centres lie half a texel past the texel's corner. + GlobalPoint { + x: origin(FIRST.0) + ((x + 0.5) * TEXEL as f64) as i64, + y: origin(FIRST.1) + ((y + 0.5) * TEXEL as f64) as i64, + } + } + + #[test] + fn the_bicubic_of_a_quadratic_is_the_quadratic_also_across_pages() { + let terrain = Terrain::new(CELL, pages(LEVEL, FIRST, 2, quadratic)); + let step = 0.02; + // At a texel centre, the texel's value. + let centre = terrain.height(at(40.0, 70.0)).unwrap(); + assert!((centre - quadratic(40.0, 70.0)).abs() < step, "{centre}"); + // Between texels, and with the 16 texels across the page line at 256. + for (x, y) in [(40.3, 70.75), (255.4, 100.0), (255.6, 255.2), (300.1, 254.9)] { + let h = terrain.height(at(x, y)).unwrap(); + assert!((h - quadratic(x, y)).abs() < step, "({x}, {y}): {h} for {}", quadratic(x, y)); + } + } + + #[test] + fn an_unknown_texel_falls_back_a_level_and_none_past_level_13() { + let mut fine = pages(LEVEL, FIRST, 1, quadratic); + fine[0].codes[70 * PAGE + 40] = UNKNOWN; + // Level 13 holds a plane of 500 m over the same ground. + let coarse = pages(13, (FIRST.0 / 2, FIRST.1 / 2), 1, |_, _| 500.0); + let terrain = Terrain::new(CELL, [fine.clone(), coarse.clone()].concat()); + assert!((terrain.height(at(40.2, 70.2)).unwrap() - 500.0).abs() < 1e-3); + assert!((terrain.height(at(43.0, 70.0)).unwrap() - quadratic(43.0, 70.0)).abs() < 0.02); + assert_eq!(Terrain::new(CELL, fine).height(at(40.2, 70.2)), None); + assert_eq!(Terrain::new(CELL, Vec::new()).height(at(40.2, 70.2)), None); + // A page that the cell does not want is dropped. + let far = CellKey { x: CELL.x + 40, y: CELL.y }; + assert_eq!(Terrain::new(far, coarse).height(at(43.0, 70.0)), None); + } + + #[test] + fn terrarium_pages_are_those_of_heights_ts() { + let size = 512; + let mut rgba = vec![0u8; 4 * size * size]; + for j in 0..size { + for i in 0..size { + // 1000 m + i / 8 m + j / 256 m, in 1/256 m. + let code = (32768 + 1000) * 256 + 32 * i as u32 + j as u32; + let p = 4 * (j * size + i); + rgba[p..p + 4].copy_from_slice(&[(code >> 16) as u8, (code >> 8) as u8, code as u8, 255]); + } + } + rgba[3] = 0; + let pages = pages_from_terrarium(&rgba, size, 13, 4286, 2888).unwrap(); + let west = pages[0].as_ref().unwrap(); + assert_eq!((west.level, west.x, west.y), (14, 8572, 5776)); + // Pixel (0, 0) is transparent: the least known height is at (0, 1). + let (min, max): (f64, f64) = (1000.0 + 1.0 / 256.0, 1000.0 + 255.0 / 8.0 + 255.0 / 256.0); + assert_eq!(west.offset, min as f32); + let scale = (max - min) / 65534.0; + assert_eq!(west.scale, scale as f32); + assert_eq!(west.codes[0], UNKNOWN); + assert_eq!(west.codes[PAGE], 0); + assert_eq!(west.codes[PAGE * PAGE - 1], 65534); + assert_eq!(west.codes[PAGE + 3], ((1000.0 + 3.0 / 8.0 + 1.0 / 256.0 - min) / scale).round() as u16); + let south_east = pages[3].as_ref().unwrap(); + assert_eq!((south_east.x, south_east.y, south_east.offset), (8573, 5777, (1000.0 + 32.0 + 1.0) as f32)); + assert!(pages_from_terrarium(&rgba[..16], 2, 13, 0, 0).is_err()); + assert!(pages_from_terrarium(&vec![0; 4 * size * size], size, 13, 0, 0).unwrap().iter().all(Option::is_none)); + } + + #[test] + fn a_cell_at_a_page_corner_wants_the_pages_about_it() { + // Level-14 pages are 2^20 units, cells 2^18: this cell's origin is a corner of pages of both levels. + let key = CellKey { x: 8572 * 4, y: 5776 * 4 }; + let wanted = Terrain::wanted(key); + let of = |level: u8| wanted.iter().filter(|k| k.level == level).map(|k| (k.x, k.y)).collect::>(); + assert_eq!(of(14), [(8571, 5775), (8572, 5775), (8571, 5776), (8572, 5776)]); + assert_eq!(of(13), [(4285, 2887), (4286, 2887), (4285, 2888), (4286, 2888)]); + assert_eq!(PageKey { level: 14, x: 8573, y: 5776 }.tile(), (13, 4286, 2888, 1)); + } +} diff --git a/host/obc-ground-plan/src/tile.rs b/host/obc-ground-plan/src/tile.rs new file mode 100644 index 0000000000..3e0f789181 --- /dev/null +++ b/host/obc-ground-plan/src/tile.rs @@ -0,0 +1,541 @@ +//! The reader of the feature tiles of format 4 (`specs/trailview-features.md`): the raw codes of a +//! tile, its features in the frame, the owner of each element of a cell's tiles, and a decode cache. +//! +//! The tiles hold no OSM id. A segment's key is (kind, tags, its two global end points): the same in +//! every tile that holds it, because the cut keeps a segment whole. + +use std::collections::BTreeMap; +use std::fmt; +use std::sync::Arc; + +use core::f64::consts::TAU; + +use crate::frame::{tile_point, GlobalPoint, FEATURE_ZOOM, FRAME_BITS}; + +pub type Tags = BTreeMap; + +const TURN: i64 = 1024; +const GRADE: f64 = 250.0; +const BANK: f64 = 1000.0; +const TILE_UNITS: i64 = 1 << (FRAME_BITS - FEATURE_ZOOM); +/// The largest coordinate that a tile may hold, in its units or quarters: far past any cut end, and +/// small enough that every frame point and every difference of two stays far inside `i64`. +const COORDINATE_MAX: i64 = 1 << 40; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Geometry { + Point, + Line, + Area, +} + +/// What broke in a tile. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DecodeError { + /// A number or a string runs past the end. + End, + /// A varint of more than 10 bytes, or past 64 bits. + LongVarint, + /// A string index past the string table. + StringIndex(u64), + /// A geometry code other than 0, 1 and 2. + Geometry(u64), + InvalidUtf8, + /// A coordinate past `COORDINATE_MAX` tile units: no bake writes one. + Coordinate, + /// Bytes after the last feature: the count of them. + Trailing(usize), +} + +impl fmt::Display for DecodeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + DecodeError::End => write!(f, "a feature tile ends inside a number or a string"), + DecodeError::LongVarint => write!(f, "a feature tile has a varint past 64 bits"), + DecodeError::StringIndex(index) => write!(f, "a feature tile names string {index} past its table"), + DecodeError::Geometry(code) => write!(f, "a feature tile has the unknown geometry {code}"), + DecodeError::InvalidUtf8 => write!(f, "a feature tile has a string that is not UTF-8"), + DecodeError::Coordinate => write!(f, "a feature tile has a coordinate past 2^40 tile units"), + DecodeError::Trailing(count) => write!(f, "a feature tile has {count} bytes after its last feature"), + } + } +} + +impl std::error::Error for DecodeError {} + +/// A feature in the codes of the format. `fine` is `has_plan`: the coordinates are quarters of a +/// tile unit, also in a part without an alignment. +#[derive(Clone, Debug, PartialEq)] +pub struct RawFeature { + pub kind: String, + pub tags: Tags, + pub geometry: Geometry, + pub fine: bool, + pub parts: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct RawPart { + pub outer: bool, + pub xy: Vec<[i64; 2]>, + /// Centimetres per vertex, None where unknown; None for a feature without heights. + pub z: Option>>, + pub plan: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct RawPlan { + /// `along_code − 1`: 2 × decimetres along the stroke + 1 when it runs against its stroke. + pub along: u64, + /// 1/1024 of a turn, 0 to 1023. + pub tangent: Vec, + /// 1/250. + pub grade: Vec, + /// 1/1000. + pub bank: Vec, + /// Centimetres. + pub widen: Vec, + pub side: Vec, + pub walk: Vec, +} + +struct Reader<'a> { + data: &'a [u8], + at: usize, +} + +impl Reader<'_> { + fn varint(&mut self) -> Result { + let mut value = 0u64; + for shift in (0..70).step_by(7) { + let byte = *self.data.get(self.at).ok_or(DecodeError::End)?; + self.at += 1; + let bits = u64::from(byte & 0x7f); + if shift == 63 && bits > 1 { + return Err(DecodeError::LongVarint); + } + value |= bits << shift; + if byte < 0x80 { + return Ok(value); + } + } + Err(DecodeError::LongVarint) + } + + fn signed(&mut self) -> Result { + self.varint().map(zigzag) + } +} + +fn zigzag(value: u64) -> i64 { + (value >> 1) as i64 ^ -((value & 1) as i64) +} + +/// The features of a tile's bytes after gzip. +pub fn decode(bytes: &[u8]) -> Result, DecodeError> { + let mut r = Reader { data: bytes, at: 0 }; + let mut table = Vec::new(); + for _ in 0..r.varint()? { + let length = usize::try_from(r.varint()?).map_err(|_| DecodeError::End)?; + let end = r.at.checked_add(length).ok_or(DecodeError::End)?; + let text = bytes.get(r.at..end).ok_or(DecodeError::End)?; + table.push(std::str::from_utf8(text).map_err(|_| DecodeError::InvalidUtf8)?.to_string()); + r.at = end; + } + let text = |index: u64| { + usize::try_from(index).ok().and_then(|i| table.get(i)).cloned().ok_or(DecodeError::StringIndex(index)) + }; + let mut heads = Vec::new(); + for _ in 0..r.varint()? { + let kind = text(r.varint()?)?; + heads.push((kind, r.varint()?)); + } + let mut features = Vec::with_capacity(heads.len()); + for (kind, header) in &heads { + let mut tags = Tags::new(); + for _ in 0..r.varint()? { + let key = text(r.varint()?)?; + tags.insert(key, text(r.varint()?)?); + } + let geometry = match header & 3 { + 0 => Geometry::Point, + 1 => Geometry::Line, + 2 => Geometry::Area, + code => return Err(DecodeError::Geometry(code)), + }; + features.push(RawFeature { kind: kind.clone(), tags, geometry, fine: header & 8 != 0, parts: Vec::new() }); + } + // The vertex count of each part: the streams after this one do not name it. + let mut counts: Vec> = Vec::with_capacity(heads.len()); + for (feature, (_, header)) in features.iter_mut().zip(&heads) { + let solved = header & 4 != 0; + let mut sizes = Vec::new(); + for _ in 0..header >> 4 { + let code = r.varint()?; + sizes.push(code >> 1); + feature.parts.push(RawPart { outer: code & 1 == 1, xy: Vec::new(), z: solved.then(Vec::new), plan: None }); + } + counts.push(sizes); + } + for (feature, sizes) in features.iter_mut().zip(&counts) { + let (mut x, mut y, mut height) = (0i64, 0i64, 0i64); + for (part, &size) in feature.parts.iter_mut().zip(sizes) { + for _ in 0..size { + x = x.checked_add(r.signed()?).filter(|v| v.abs() <= COORDINATE_MAX).ok_or(DecodeError::Coordinate)?; + y = y.checked_add(r.signed()?).filter(|v| v.abs() <= COORDINATE_MAX).ok_or(DecodeError::Coordinate)?; + part.xy.push([x, y]); + if let Some(z) = &mut part.z { + let code = r.varint()?; + z.push((code != 0).then(|| { + height = height.wrapping_add(zigzag(code - 1)); + height + })); + } + } + } + } + // (feature, part, along_code) of each part with an alignment. + let mut aligned = Vec::new(); + for (f, (_, header)) in heads.iter().enumerate() { + if header & 8 == 0 { + continue; + } + for p in 0..counts[f].len() { + let code = r.varint()?; + if code != 0 { + aligned.push((f, p, code)); + } + } + } + let column = |r: &mut Reader| -> Result>, DecodeError> { + aligned.iter().map(|&(f, p, _)| (0..counts[f][p]).map(|_| r.varint()).collect()).collect() + }; + let (tangents, grades) = (column(&mut r)?, column(&mut r)?); + let (banks, words) = (column(&mut r)?, column(&mut r)?); + let running = |codes: &[u64]| -> Vec { + let mut sum = 0i64; + codes + .iter() + .map(|&code| { + sum = sum.wrapping_add(zigzag(code)); + sum + }) + .collect() + }; + for (n, &(f, p, code)) in aligned.iter().enumerate() { + features[f].parts[p].plan = Some(RawPlan { + along: code - 1, + tangent: running(&tangents[n]).iter().map(|turn| turn.rem_euclid(TURN)).collect(), + grade: running(&grades[n]), + bank: banks[n].iter().map(|&code| zigzag(code)).collect(), + widen: words[n].iter().map(|word| word >> 4).collect(), + side: words[n].iter().map(|word| (word & 3) as u8).collect(), + walk: words[n].iter().map(|word| (word >> 2 & 3) as u8).collect(), + }); + } + if r.at != bytes.len() { + return Err(DecodeError::Trailing(bytes.len() - r.at)); + } + Ok(features) +} + +/// A feature of a zoom-13 tile in the frame. +#[derive(Clone, Debug, PartialEq)] +pub struct Feature { + /// The feature's position in its tile. + pub index: u32, + pub kind: String, + pub tags: Tags, + pub geometry: Geometry, + pub parts: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub outer: bool, + /// The zoom-13 tile (column, row) that this copy comes from. + pub tile: (u32, u32), + /// Per segment (line), edge (ring, the last vertex to the first included) or point: whether this + /// copy's tile owns it. Empty until a cell sets it. + pub own: Vec, + pub points: Vec, + /// Metres per vertex, None where unknown; None for a feature without heights. + pub heights: Option>>, + pub plan: Option, +} + +/// The alignment of a part, per vertex in the direction of the part. +#[derive(Clone, Debug, PartialEq)] +pub struct Alignment { + /// Metres along the stroke at the first vertex. Two tiles round it differently by up to 10 cm. + pub along_m: f64, + /// The metres along fall along the part: it runs against its stroke. + pub backward: bool, + /// Radians from +x to +y (east to south), 0 to τ. + pub tangent: Vec, + /// Rise per metre. + pub grade: Vec, + /// Rise per metre to the left of the direction. + pub bank: Vec, + /// Metres that the half-width gains. + pub widen: Vec, + /// The ways out that leave the vertex's junction as a side: 1 back along the part, 2 on. + pub side: Vec, + /// The sides of the segment from the vertex on with a sidewalk: 1 left, 2 right. 0 at the last vertex. + pub walk: Vec, +} + +/// The features of a zoom-13 tile's bytes after gzip, in the tile's order, with no vertex changed. +pub fn features(bytes: &[u8], column: u32, row: u32) -> Result, DecodeError> { + let raw = decode(bytes)?; + Ok(raw + .into_iter() + .enumerate() + .map(|(index, feature)| { + let fine = feature.fine; + let parts = feature + .parts + .into_iter() + .map(|part| Part { + outer: part.outer, + tile: (column, row), + own: Vec::new(), + points: part.xy.iter().map(|&[x, y]| tile_point(FEATURE_ZOOM, column, row, fine, x, y)).collect(), + heights: part.z.map(|z| z.into_iter().map(|cm| cm.map(|cm| cm as f64 / 100.0)).collect()), + plan: part.plan.map(alignment), + }) + .collect(); + Feature { index: index as u32, kind: feature.kind, tags: feature.tags, geometry: feature.geometry, parts } + }) + .collect()) +} + +fn alignment(plan: RawPlan) -> Alignment { + let mut walk = plan.walk; + // No segment starts at the last vertex: the cut can leave its walk set. + if let Some(last) = walk.last_mut() { + *last = 0; + } + Alignment { + along_m: (plan.along >> 1) as f64 / 10.0, + backward: plan.along & 1 == 1, + tangent: plan.tangent.iter().map(|&code| code as f64 * TAU / TURN as f64).collect(), + grade: plan.grade.iter().map(|&code| code as f64 / GRADE).collect(), + bank: plan.bank.iter().map(|&code| code as f64 / BANK).collect(), + widen: plan.widen.iter().map(|&cm| cm as f64 / 100.0).collect(), + side: plan.side, + walk, + } +} + +/// The closed square [x0, y0, x1, y1] of a zoom-13 tile. +pub fn tile_square((column, row): (u32, u32)) -> [i64; 4] { + let (x, y) = (i64::from(column) * TILE_UNITS, i64::from(row) * TILE_UNITS); + [x, y, x + TILE_UNITS, y + TILE_UNITS] +} + +/// Whether the segment a–b meets the closed box [x0, y0, x1, y1]: separating axes, exact in `i128` +/// for coordinates within ±2^62, which holds every decoded point (`COORDINATE_MAX`). +pub fn segment_meets(a: GlobalPoint, b: GlobalPoint, [x0, y0, x1, y1]: [i64; 4]) -> bool { + if a.x.max(b.x) < x0 || a.x.min(b.x) > x1 || a.y.max(b.y) < y0 || a.y.min(b.y) > y1 { + return false; + } + let d = |p: i64, q: i64| i128::from(p) - i128::from(q); + let (dx, dy) = (d(b.x, a.x), d(b.y, a.y)); + let side = |x: i64, y: i64| (dx * d(y, a.y) - dy * d(x, a.x)).signum(); + let sides = [side(x0, y0), side(x1, y0), side(x0, y1), side(x1, y1)]; + !(sides.iter().all(|&s| s > 0) || sides.iter().all(|&s| s < 0)) +} + +/// The element `i` of a part: a point, a segment, or a ring edge from the last vertex to the first. +fn element(geometry: Geometry, points: &[GlobalPoint], i: usize) -> (GlobalPoint, GlobalPoint) { + match geometry { + Geometry::Point => (points[i], points[i]), + Geometry::Line => (points[i], points[i + 1]), + Geometry::Area => (points[i], points[(i + 1) % points.len()]), + } +} + +/// The elements of a part: its points, segments or ring edges. +pub fn element_count(geometry: Geometry, points: usize) -> usize { + match geometry { + Geometry::Point | Geometry::Area => points, + Geometry::Line => points.saturating_sub(1), + } +} + +/// The index in `tiles` of the owner of an element: the first tile whose square it meets. A point +/// meets the half-open square, so a point on a tile line belongs to the tile east or south of it; +/// a segment meets the closed square. +pub fn owner(tiles: &[(u32, u32)], a: GlobalPoint, b: GlobalPoint) -> Option { + tiles.iter().position(|&tile| { + let [x0, y0, x1, y1] = tile_square(tile); + if a == b { + (x0..x1).contains(&a.x) && (y0..y1).contains(&a.y) + } else { + segment_meets(a, b, [x0, y0, x1, y1]) + } + }) +} + +/// The owner flags of each element of a part of the tile at `tiles[at]`. +pub fn own(geometry: Geometry, points: &[GlobalPoint], tiles: &[(u32, u32)], at: usize) -> Vec { + (0..element_count(geometry, points.len())) + .map(|i| { + let (a, b) = element(geometry, points, i); + owner(tiles, a, b) == Some(at) + }) + .collect() +} + +/// A decoded tile and the clock of its last use. +type Cached = (Arc>, u64); + +/// The decoded features of the tiles used last, without `own`. A decode is pure, so the cache +/// changes no output byte. +pub struct TileCache { + capacity: usize, + clock: u64, + tiles: BTreeMap<(u32, u32), Cached>, +} + +impl TileCache { + pub fn new(capacity: usize) -> TileCache { + TileCache { capacity: capacity.max(1), clock: 0, tiles: BTreeMap::new() } + } + + /// Whether the cache holds tile (column, row); a held tile counts as used now. + pub fn touch(&mut self, column: u32, row: u32) -> bool { + self.clock += 1; + self.tiles.get_mut(&(column, row)).map(|(_, used)| *used = self.clock).is_some() + } + + /// The features of tile (column, row). `load` gives its bytes after gzip, or None where the + /// archive does not hold it: no features. + pub fn tile( + &mut self, + column: u32, + row: u32, + load: impl FnOnce() -> Option>, + ) -> Result>, DecodeError> { + self.clock += 1; + if let Some((features, used)) = self.tiles.get_mut(&(column, row)) { + *used = self.clock; + return Ok(features.clone()); + } + // An absent tile is not kept: a held tile is one that a caller gave. + let Some(bytes) = load() else { return Ok(Arc::new(Vec::new())) }; + let decoded = Arc::new(features(&bytes, column, row)?); + self.tiles.insert((column, row), (decoded.clone(), self.clock)); + if self.tiles.len() > self.capacity { + let oldest = self.tiles.iter().min_by_key(|(_, (_, used))| *used).map(|(&key, _)| key); + oldest.map(|key| self.tiles.remove(&key)); + } + Ok(decoded) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{json, Value}; + + fn vectors() -> std::path::PathBuf { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../specs/vectors") + } + + fn as_json(feature: &RawFeature) -> Value { + let geometry = ["point", "line", "area"][feature.geometry as usize]; + let parts: Vec = feature + .parts + .iter() + .map(|part| { + let mut out = json!({"outer": part.outer, "xy": part.xy}); + if let Some(z) = &part.z { + out["z"] = z.iter().map(|h| h.map_or(Value::Null, |cm| json!(cm as f64 / 100.0))).collect(); + } + if let Some(plan) = &part.plan { + out["along"] = json!(plan.along); + out["tangent"] = json!(plan.tangent); + out["grade"] = json!(plan.grade); + out["bank"] = json!(plan.bank); + out["widen"] = json!(plan.widen); + out["side"] = json!(plan.side); + out["walk"] = json!(plan.walk); + } + out + }) + .collect(); + json!({"kind": feature.kind, "tags": feature.tags, "geometry": geometry, "parts": parts}) + } + + #[test] + fn the_shared_vectors_decode() { + let decoded: Value = + serde_json::from_slice(&std::fs::read(vectors().join("trailview-features.json")).unwrap()).unwrap(); + let features = decode(&std::fs::read(vectors().join("trailview-features.bin")).unwrap()).unwrap(); + assert_eq!(Value::Array(features.iter().map(as_json).collect()), decoded); + assert!(decode(&[0, 0]).unwrap().is_empty()); + } + + #[test] + fn a_broken_tile_names_what_broke() { + let bytes = std::fs::read(vectors().join("trailview-features.bin")).unwrap(); + assert_eq!(decode(&bytes[..bytes.len() - 1]), Err(DecodeError::End)); + assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), Err(DecodeError::Trailing(1))); + // One string, one feature whose kind is string 5. + assert_eq!(decode(&[1, 1, b'a', 1, 5, 0x11]), Err(DecodeError::StringIndex(5))); + assert_eq!(decode(&[1, 1, b'a', 1, 0, 0x13, 0]), Err(DecodeError::Geometry(3))); + assert_eq!(decode(&[1, 1, 0xff, 0]), Err(DecodeError::InvalidUtf8)); + assert_eq!(decode(&[0x80; 11]), Err(DecodeError::LongVarint)); + // One line of two vertices whose first dx is i64::MAX: an error, not an overflow. + let far = [ + &[1, 1, b'a', 1, 0, 0x11, 0, 4][..], + &[0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01], + &[0, 0, 0], + ] + .concat(); + assert_eq!(decode(&far), Err(DecodeError::Coordinate)); + assert_eq!(features(&far, 4286, 2888), Err(DecodeError::Coordinate)); + } + + #[test] + fn a_quarter_and_a_whole_unit_give_one_point_and_the_last_walk_is_0() { + let bytes = std::fs::read(vectors().join("trailview-features.bin")).unwrap(); + let raw = decode(&bytes).unwrap(); + let framed = features(&bytes, 4286, 2888).unwrap(); + for (feature, raw) in framed.iter().zip(&raw) { + let (fine, origin) = (if raw.fine { 4 } else { 1 }, tile_point(13, 4286, 2888, false, 0, 0)); + for (part, raw) in feature.parts.iter().zip(&raw.parts) { + for (p, &[x, y]) in part.points.iter().zip(&raw.xy) { + assert_eq!(*p, GlobalPoint { x: origin.x + x * 128 / fine, y: origin.y + y * 128 / fine }); + } + if let Some(plan) = &part.plan { + assert_eq!(plan.walk.last(), Some(&0)); + assert_eq!( + &plan.walk[..plan.walk.len() - 1], + &raw.plan.as_ref().unwrap().walk[..plan.walk.len() - 1] + ); + } + } + } + // The tertiary road counts in quarters: its vertex -601 / 4 lies 150.25 units west of the tile. + let tertiary = &framed[2].parts[0]; + assert_eq!(tertiary.points[0].x - tile_point(13, 4286, 2888, false, 0, 0).x, -601 * 32); + assert_eq!(tile_point(13, 4286, 2888, true, 400, 8), tile_point(13, 4286, 2888, false, 100, 2)); + } + + #[test] + fn a_segment_meets_a_box_exactly() { + let p = |x, y| GlobalPoint { x, y }; + let square = [0, 0, 10, 10]; + assert!(segment_meets(p(-5, 5), p(15, 5), square)); + assert!(segment_meets(p(10, 10), p(20, 0), square), "a corner"); + assert!(!segment_meets(p(11, 10), p(20, 1), square), "past the corner"); + assert!(!segment_meets(p(-10, 9), p(9, 28), square), "a diagonal past the corner"); + // A point on a tile line belongs to the tile east of it. + let tiles = [(0, 0), (1, 0)]; + assert_eq!(owner(&tiles, p(TILE_UNITS, 5), p(TILE_UNITS, 5)), Some(1)); + assert_eq!(owner(&tiles, p(TILE_UNITS - 3, 5), p(TILE_UNITS + 3, 5)), Some(0)); + } +} diff --git a/host/obc-ground-plan/src/transport.rs b/host/obc-ground-plan/src/transport.rs new file mode 100644 index 0000000000..e0abaca64a --- /dev/null +++ b/host/obc-ground-plan/src/transport.rs @@ -0,0 +1,478 @@ +//! The bytes between a caller and `cell::build_cell`: the request of one cell, its flat plan, their +//! digests and the vocabulary of the codes. The bake, the WASM bridge and a later iOS library share +//! them, so every caller builds from the same bytes. +//! +//! A request, little-endian and 4-byte aligned: +//! +//! | Field | Type | +//! | --- | --- | +//! | magic | `b"OGPR"` | +//! | cell x, y | `u32`, `u32` (zoom 16) | +//! | tile count | `u32` | +//! | per tile | `column: u32`, `row: u32`, `length: u32`, the plain format-4 bytes, zero padding to 4 | +//! | page count | `u32` | +//! | per page | `level: u32`, `x: u32`, `y: u32`, `offset: f32`, `scale: f32`, 65,536 × `u16` codes | +//! +//! The encoding is canonical: the tiles come in the order of `CellKey::feature_tiles`, the pages by +//! (level, x, y), and `decode` refuses any other order. So equal inputs give equal bytes. + +use std::collections::BTreeMap; +use std::fmt::{self, Write as _}; + +use serde_json::{json, Value}; + +use crate::cell::{CellBuild, STAGES}; +use crate::debug; +use crate::faces::{FacePlan, HeightRule, Owner}; +use crate::frame::CellKey; +use crate::graph::{CrossingKind, Family, Level, Network, Source}; +use crate::terrain::{StoredPage, Terrain, PAGE}; +use crate::tile::TileCache; +use crate::CellInput; + +const REQUEST_MAGIC: &[u8; 4] = b"OGPR"; +const PLAN_MAGIC: &[u8; 4] = b"OGPP"; +const CODES: usize = PAGE * PAGE; + +/// The plain bytes of one zoom-13 feature tile. +#[derive(Clone, Debug, PartialEq)] +pub struct FeatureTile { + pub column: u32, + pub row: u32, + pub bytes: Vec, +} + +/// The inputs of one cell: its feature tiles that exist and its stored pages. +#[derive(Clone, Debug, PartialEq)] +pub struct Request { + pub key: CellKey, + pub tiles: Vec, + pub pages: Vec, +} + +struct Reader<'a> { + bytes: &'a [u8], + at: usize, +} + +impl Reader<'_> { + fn take(&mut self, n: usize) -> Result<&[u8], String> { + let end = self.at.checked_add(n).filter(|&end| end <= self.bytes.len()); + let end = end.ok_or_else(|| format!("a request ends at byte {} inside a field", self.bytes.len()))?; + let out = &self.bytes[self.at..end]; + self.at = end; + Ok(out) + } + + fn word(&mut self) -> Result { + Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap())) + } +} + +impl Request { + pub fn encode(&self) -> Vec { + let mut tiles: Vec<&FeatureTile> = self.tiles.iter().collect(); + tiles.sort_by_key(|t| (t.row, t.column)); + let mut pages: Vec<&StoredPage> = self.pages.iter().collect(); + pages.sort_by_key(|p| (p.level, p.x, p.y)); + let mut out = REQUEST_MAGIC.to_vec(); + let word = |out: &mut Vec, w: u32| out.extend_from_slice(&w.to_le_bytes()); + word(&mut out, self.key.x); + word(&mut out, self.key.y); + word(&mut out, tiles.len() as u32); + for t in tiles { + word(&mut out, t.column); + word(&mut out, t.row); + word(&mut out, t.bytes.len() as u32); + out.extend_from_slice(&t.bytes); + out.resize(out.len().next_multiple_of(4), 0); + } + word(&mut out, pages.len() as u32); + for p in pages { + for w in [u32::from(p.level), p.x, p.y, p.offset.to_bits(), p.scale.to_bits()] { + word(&mut out, w); + } + out.extend(p.codes.iter().flat_map(|c| c.to_le_bytes())); + } + out + } + + /// The request of canonical bytes; an error names what is wrong. + pub fn decode(bytes: &[u8]) -> Result { + let mut r = Reader { bytes, at: 0 }; + if r.take(4)? != REQUEST_MAGIC { + return Err("a request does not start with OGPR".into()); + } + let key = CellKey { x: r.word()?, y: r.word()? }; + let names = key.feature_tiles(); + let mut last_tile = None; + let mut tiles = Vec::new(); + for _ in 0..r.word()? { + let (column, row, length) = (r.word()?, r.word()?, r.word()? as usize); + let at = names.iter().position(|&t| t == (column, row)); + let at = at.ok_or_else(|| format!("cell {}/{} reads no tile 13/{column}/{row}", key.x, key.y))?; + if last_tile.is_some_and(|last| last >= at) { + return Err(format!("tile 13/{column}/{row} repeats or comes out of order")); + } + last_tile = Some(at); + let tile = r.take(length)?.to_vec(); + if r.take(length.next_multiple_of(4) - length)?.iter().any(|&b| b != 0) { + return Err(format!("tile 13/{column}/{row} has padding that is not zero")); + } + tiles.push(FeatureTile { column, row, bytes: tile }); + } + let wanted = Terrain::wanted(key); + let mut pages: Vec = Vec::new(); + for _ in 0..r.word()? { + let level = r.word()?; + let (x, y) = (r.word()?, r.word()?); + let (offset, scale) = (f32::from_bits(r.word()?), f32::from_bits(r.word()?)); + if !wanted.iter().any(|k| u32::from(k.level) == level && (k.x, k.y) == (x, y)) { + return Err(format!("cell {}/{} reads no page {level}/{x}/{y}", key.x, key.y)); + } + let level = level as u8; + if pages.last().is_some_and(|p| (p.level, p.x, p.y) >= (level, x, y)) { + return Err(format!("page {level}/{x}/{y} repeats or comes out of order")); + } + let codes = r.take(2 * CODES).map_err(|_| format!("page {level}/{x}/{y} has fewer than {CODES} codes"))?; + let codes = codes.as_chunks::<2>().0.iter().map(|&c| u16::from_le_bytes(c)).collect(); + pages.push(StoredPage { level, x, y, offset, scale, codes }); + } + if r.at != bytes.len() { + return Err(format!("a request has {} bytes after its last page", bytes.len() - r.at)); + } + Ok(Request { key, tiles, pages }) + } + + /// The cell input, as `CellInput::new` reads it, with the tiles that `cache` holds parsed. + pub fn input(self, cache: &mut TileCache) -> Result { + let mut tiles: BTreeMap<(u32, u32), Vec> = + self.tiles.into_iter().map(|t| ((t.column, t.row), t.bytes)).collect(); + CellInput::new(self.key, cache, |column, row| tiles.remove(&(column, row)), self.pages) + .map_err(|e| e.to_string()) + } +} + +/// FNV-1a 64: it finds a difference; it is no security hash. +#[derive(Clone, Copy)] +pub struct Fnv(u64); + +impl Default for Fnv { + fn default() -> Self { + Fnv(0xcbf2_9ce4_8422_2325) + } +} + +/// The hash of a `Debug` text that also notes a NaN: the text of a NaN drops its sign and payload, +/// which WASM does not fix, so a NaN would hide a difference between two builds. +#[derive(Default)] +struct DebugHash { + hash: Fnv, + nan: bool, +} + +impl fmt::Write for DebugHash { + fn write_str(&mut self, s: &str) -> fmt::Result { + // A float's Debug writes "NaN" in one piece, and the graph holds no text of its own. + self.nan |= s.contains("NaN"); + self.hash.write(s.as_bytes()); + Ok(()) + } +} + +impl Fnv { + pub fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); + } + } + + /// 16 hex digits. + pub fn hex(self) -> String { + format!("{:016x}", self.0) + } +} + +pub fn fnv(bytes: &[u8]) -> String { + let mut h = Fnv::default(); + h.write(bytes); + h.hex() +} + +/// Words per page of `wanted_words`: level, page x, page y, then the stored tile that holds it (z, x, y) +/// and its quadrant. +pub const WANTED_WORDS: usize = 7; + +/// The pages that a cell reads (`Terrain::wanted`), `WANTED_WORDS` per page. +pub fn wanted_words(key: CellKey) -> Vec { + (Terrain::wanted(key).into_iter()) + .flat_map(|page| { + let (z, x, y, quadrant) = page.tile(); + [u32::from(page.level), page.x, page.y, z, x, y, quadrant as u32] + }) + .collect() +} + +/// Words of a way in `Flat::ways`: id, family, level, flags, first sample, sample count. +pub const WAY_WORDS: usize = 6; +/// `Flat::ways` flags. +pub const WAY_LINK: u32 = 1; +pub const WAY_SYNTHETIC_DECK: u32 = 2; +/// Words of a point in `Flat::points`: kind (`POINTS`), network, x, y, owned. +pub const POINT_WORDS: usize = 5; +const POINTS: [&str; 3] = ["junction", "joint", "end"]; +/// Words of a crossing in `Flat::crossings`: x, y, kind, source, owned. +pub const CROSSING_WORDS: usize = 5; + +/// Words of a face in `FaceWords::faces`: id, owner (kind, id), surface, level (`i8` as `i32` bits), +/// height rule, material and crossing (`u32::MAX` for none), rank, inside, `reach_m` (`f32` bits), the legs +/// of material and crossing (bits 0–7, 8–15), first ring, ring count. +pub const FACE_WORDS: usize = 14; +/// Words of a ring in `FaceWords::rings`: first index into `ring_vertices`, count. +pub const RING_WORDS: usize = 2; +/// Words of an edge in `FaceWords::edges`: a, b, left, right, kind, flags. +pub const EDGE_WORDS: usize = 6; +/// Words of a corner arc in `FaceWords::corners`: owner (kind, id), centre x, y, `radius_m` (`f64` bits, +/// low word first), `t_a` x, y, `t_b` x, y, first point in `corner_points`, point count. +pub const CORNER_WORDS: usize = 12; +/// Owner kinds; the id of `terrain` is `u32::MAX`. +const OWNERS: [&str; 4] = ["terrain", "way", "junction", "platform"]; +const RULES: [(HeightRule, &str); 5] = [ + (HeightRule::Terrain, "terrain"), + (HeightRule::Slope, "slope"), + (HeightRule::Owner, "owner"), + (HeightRule::Blend, "blend"), + (HeightRule::KerbOffset, "kerb_offset"), +]; +const NONE: u32 = u32::MAX; + +fn owner(o: Owner) -> [u32; 2] { + match o { + Owner::Terrain => [0, NONE], + Owner::Way(id) => [1, id], + Owner::Junction(id) => [2, id], + Owner::Platform(id) => [3, id], + } +} + +/// The faces of one level as flat words: every field of `FacePlan`, its floats as their bits. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct FaceWords { + /// x, y of every vertex. + pub vertices: Vec, + pub faces: Vec, + /// A face's first ring is its outer ring; the others are holes. + pub rings: Vec, + /// Indices into the vertices. + pub ring_vertices: Vec, + pub edges: Vec, + pub corners: Vec, + /// x, y of the points of the corners' arcs. + pub corner_points: Vec, +} + +impl FaceWords { + pub fn of(plan: &FacePlan) -> FaceWords { + let mut w = FaceWords { vertices: plan.vertices.iter().flatten().copied().collect(), ..FaceWords::default() }; + for f in &plan.faces { + let first = (w.rings.len() / RING_WORDS) as u32; + for ring in &f.rings { + w.rings.extend([w.ring_vertices.len() as u32, ring.len() as u32]); + w.ring_vertices.extend(ring); + } + let [kind, id] = owner(f.owner); + w.faces.extend([ + f.id, + kind, + id, + f.surface as u32, + i32::from(f.level) as u32, + code(&RULES, f.rule), + f.material.unwrap_or(NONE), + f.crossing.unwrap_or(NONE), + u32::from(f.rank), + u32::from(f.inside), + f.reach_m.to_bits(), + u32::from(f.legs[0]) | u32::from(f.legs[1]) << 8, + first, + f.rings.len() as u32, + ]); + } + w.edges = + (plan.edges.iter()).flat_map(|e| [e.a, e.b, e.left, e.right, e.kind as u32, u32::from(e.flags)]).collect(); + for c in &plan.corners { + let [kind, id] = owner(c.owner); + let r = c.radius_m.to_bits(); + let first = (w.corner_points.len() / 2) as u32; + w.corners.extend([kind, id, c.centre[0] as u32, c.centre[1] as u32, r as u32, (r >> 32) as u32]); + w.corners.extend([c.t_a[0], c.t_a[1], c.t_b[0], c.t_b[1]].map(|v| v as u32)); + w.corners.extend([first, c.arc.len() as u32]); + w.corner_points.extend(c.arc.iter().flatten()); + } + w + } +} + +const LEVELS: [(Level, &str); 3] = [(Level::Ground, "ground"), (Level::Deck, "deck"), (Level::Tunnel, "tunnel")]; +const NETWORKS: [(Network, &str); 3] = [(Network::Way, "way"), (Network::Rail, "rail"), (Network::Water, "water")]; +const SOURCES: [(Source, &str); 4] = [ + (Source::Tag, "tag"), + (Source::SharedVertex, "shared_vertex"), + (Source::Rule, "rule"), + (Source::Fallback, "fallback"), +]; + +fn code(table: &[(T, U)], value: T) -> u32 { + table.iter().position(|(t, _)| *t == value).expect("every value has a code") as u32 +} + +fn family(f: Family) -> u32 { + debug::FAMILIES.iter().position(|e| e.0 == f).expect("every family has a code") as u32 +} + +fn crossing(k: CrossingKind) -> u32 { + code(&debug::CROSSINGS, k) +} + +/// The plan of a cell as flat integer arrays, in the frame of the cell (frame units from its origin), +/// and its stats. The codes index the lists of `vocabulary`. +#[derive(Clone, Debug, PartialEq)] +pub struct Flat { + pub key: CellKey, + /// x, y of every sample of the graph. + pub samples: Vec, + pub ways: Vec, + pub points: Vec, + pub crossings: Vec, + /// The faces of level 0. + pub faces: FaceWords, + pub stats: String, +} + +impl Flat { + pub fn of(build: &CellBuild) -> Flat { + let g = &build.graph; + let samples = g.samples.iter().flat_map(|s| s.pos).collect(); + let synthetic: Vec = g.decks.iter().filter(|d| d.synthetic).flat_map(|d| d.ways.iter().copied()).collect(); + let mut ways = Vec::with_capacity(WAY_WORDS * g.ways.len()); + for w in &g.ways { + let flags = + u32::from(w.link.is_some()) * WAY_LINK + u32::from(synthetic.contains(&w.id)) * WAY_SYNTHETIC_DECK; + ways.extend([ + w.id, + family(w.family), + code(&LEVELS, w.level), + flags, + w.samples.start, + w.samples.len() as u32, + ]); + } + let mut points = Vec::new(); + let mut point = |kind: u32, network: Network, pos: [i32; 2], owned: bool| { + points.extend([kind, code(&NETWORKS, network), pos[0] as u32, pos[1] as u32, u32::from(owned)]); + }; + g.junctions.iter().for_each(|j| point(0, j.network, j.pos, j.owned)); + g.joints.iter().for_each(|j| point(1, j.network, j.pos, j.owned)); + g.ends.iter().for_each(|e| point(2, e.network, e.pos, e.owned)); + let crossings = (g.crossings.iter()) + .flat_map(|c| { + [c.pos[0] as u32, c.pos[1] as u32, crossing(c.kind), code(&SOURCES, c.source), u32::from(c.owned)] + }) + .collect(); + let mut counters: serde_json::Map = + g.stats.counters().iter().map(|&(name, n)| (name.to_string(), json!(n))).collect(); + let types: serde_json::Map = (g.stats.crossings.iter()) + .map(|(&(kind, source), &n)| (format!("{kind:?} {}", SOURCES[code(&SOURCES, source) as usize].1), json!(n))) + .collect(); + counters.insert("crossing_types".into(), Value::Object(types)); + let faces: serde_json::Map = + build.faces.stats.counters().iter().map(|&(name, n)| (name.to_string(), json!(n))).collect(); + let stats = json!({ + "graph": counters, + "faces": faces, + "inputs": {"tiles": build.tiles, "pages": build.pages, "request": build.request}, + }) + .to_string(); + Flat { key: build.key, samples, ways, points, crossings, faces: FaceWords::of(&build.faces), stats } + } + + /// The digest of the canonical bytes and of every field of the graph, its floats in round-trip + /// form; an error where the graph holds a NaN. It costs about as much as the build of the graph, + /// so a caller asks for it when needed. + pub fn digest(&self, build: &CellBuild) -> Result { + let mut h = DebugHash::default(); + h.hash.write(&self.canonical_bytes()); + write!(h, "{:?}", build.graph).expect("a hash takes any text"); + if h.nan { + return Err(format!("the graph of cell {}/{} holds a NaN", build.key.x, build.key.y)); + } + Ok(h.hash.hex()) + } + + /// `b"OGPP"`, the cell, each array with its `u32` length, then the stats. No time is in it. A + /// later stage writes its floats here as `to_bits` words, so the digest sees every bit of them. + pub fn canonical_bytes(&self) -> Vec { + let mut out = PLAN_MAGIC.to_vec(); + let words = |out: &mut Vec, words: &mut dyn Iterator| { + let at = out.len(); + out.extend([0; 4]); + let mut n = 0u32; + for w in words { + out.extend(w.to_le_bytes()); + n += 1; + } + out[at..at + 4].copy_from_slice(&n.to_le_bytes()); + }; + words(&mut out, &mut [self.key.x, self.key.y].into_iter()); + words(&mut out, &mut self.samples.iter().map(|&v| v as u32)); + words(&mut out, &mut self.ways.iter().copied()); + words(&mut out, &mut self.points.iter().copied()); + words(&mut out, &mut self.crossings.iter().copied()); + let f = &self.faces; + words(&mut out, &mut f.vertices.iter().map(|&v| v as u32)); + words(&mut out, &mut f.faces.iter().copied()); + words(&mut out, &mut f.rings.iter().copied()); + words(&mut out, &mut f.ring_vertices.iter().copied()); + words(&mut out, &mut f.edges.iter().copied()); + words(&mut out, &mut f.corners.iter().copied()); + words(&mut out, &mut f.corner_points.iter().map(|&v| v as u32)); + out.extend((self.stats.len() as u32).to_le_bytes()); + out.extend(self.stats.as_bytes()); + out + } +} + +/// The names and colours of the codes of `Flat`, in code order, and the stages of `times`, as JSON. +pub fn vocabulary() -> String { + fn names(table: &[(T, &'static str)]) -> Vec<&'static str> { + table.iter().map(|(_, n)| *n).collect() + } + json!({ + "stages": STAGES, + "words": { + "wanted": WANTED_WORDS, "way": WAY_WORDS, "point": POINT_WORDS, "crossing": CROSSING_WORDS, + "face": FACE_WORDS, "ring": RING_WORDS, "edge": EDGE_WORDS, "corner": CORNER_WORDS, + }, + "way_flags": {"link": WAY_LINK, "synthetic_deck": WAY_SYNTHETIC_DECK}, + "families": debug::FAMILIES.iter().map(|(_, name, rgb)| json!({"name": name, "colour": debug::hex(*rgb)})).collect::>(), + "levels": names(&LEVELS), + "networks": names(&NETWORKS), + "points": POINTS, + "crossings": debug::CROSSINGS.iter().map(|(kind, letter)| json!({"name": format!("{kind:?}"), "letter": letter.to_string()})).collect::>(), + "sources": names(&SOURCES), + "owners": OWNERS, + "surfaces": debug::SURFACES.iter().map(|(_, name, fill)| json!({"name": name, "fill": fill.map(debug::hex_alpha)})).collect::>(), + "junction_surfaces": debug::JUNCTION_SURFACES.iter().map(|(s, fill)| json!({"surface": *s as u8, "fill": debug::hex_alpha(*fill)})).collect::>(), + "rules": names(&RULES), + "edges": debug::EDGES.iter().map(|(_, name, rgb)| json!({"name": name, "colour": debug::hex(*rgb)})).collect::>(), + "colours": { + "link": debug::hex(debug::LINK), + "synthetic_deck": debug::hex(debug::SYNTHETIC_DECK), + "junction": debug::hex(debug::JUNCTION), + "joint": debug::hex(debug::JOINT), + "end": debug::hex(debug::END), + "crossing": debug::hex(debug::CROSSING), + }, + }) + .to_string() +} diff --git a/host/obc-ground-plan/tests/faces.rs b/host/obc-ground-plan/tests/faces.rs new file mode 100644 index 0000000000..25ce08a722 --- /dev/null +++ b/host/obc-ground-plan/tests/faces.rs @@ -0,0 +1,111 @@ +//! The face plans over every cell of the TrailView fixture: the planar partition (check 1), the same +//! borders in two neighbouring cells (check 2) and the same bytes twice (check 4); and the land +//! between the legs of a hairpin of the fixture. + +#[path = "fixture/mod.rs"] +mod fixture; + +use std::collections::BTreeMap; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::faces::check::{artefacts, feature_names, neighbours, partition}; +use obc_ground_plan::faces::{self, window, FacePlan, Rules, Surface}; +use obc_ground_plan::frame::{from_lon_lat, CellKey}; +use obc_ground_plan::graph::{self, WayGraph}; + +#[test] +fn every_fixture_cell_is_a_planar_partition_that_its_neighbours_agree_with() { + let mut fixture = Fixture::open(&default_dir()); + let dir = default_dir(); + let rules = Rules::embedded(); + let cells: Vec = (fixture.cells().into_iter()) + .filter(|k| k.feature_tiles().iter().all(|&(c, r)| fixture::feature_tile(&dir, c, r).is_some())) + .collect(); + assert!(cells.len() > 100, "{} cells", cells.len()); + let start = std::time::Instant::now(); + let built = fixture.map(&cells, |key, input| { + let graph = graph::build(key, &input, &rules.sections); + let plan = faces::build(&graph, &input, rules, key, 0, true); + let faults: Vec = + partition(&plan, window(key, 0.0)).into_iter().map(|f| format!("{key:?} 1: {}", f.what)).collect(); + let thin = artefacts(&plan, &graph).len(); + (key, plan, graph, feature_names(&input), faults, thin) + }); + let mut plans: BTreeMap)> = BTreeMap::new(); + let mut faults = Vec::new(); + let mut thin = 0; + for (key, plan, graph, names, found, n) in built { + faults.extend(found); + thin += n; + plans.insert(key, (plan, graph, names)); + } + println!("{} cells in {:.1} s, {thin} artefacts", cells.len(), start.elapsed().as_secs_f64()); + let mut borders = 0; + for (&key, a) in &plans { + for (east, other) in [(true, CellKey { x: key.x + 1, y: key.y }), (false, CellKey { x: key.x, y: key.y + 1 })] { + if let Some(b) = plans.get(&other) { + borders += 1; + let found = neighbours((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), east); + faults.extend(found.into_iter().map(|f| format!("{key:?}|{other:?} 2: {}", f.what))); + } + } + } + println!("{borders} borders"); + let again: Vec = cells.iter().step_by(17).copied().collect(); + let differ = fixture.map(&again, |key, input| { + let graph = graph::build(key, &input, &rules.sections); + (format!("{:?}", faces::build(&graph, &input, rules, key, 0, true)) != format!("{:?}", plans[&key].0)) + .then(|| format!("{key:?} 4: a second build differs")) + }); + faults.extend(differ.into_iter().flatten()); + for check in [" 1: ", " 2: ", " 4: "] { + let of: Vec<&String> = faults.iter().filter(|f| f.contains(check)).collect(); + println!("check{check}{} faults", of.len()); + for f in of.iter().take(8) { + println!(" {f}"); + } + } + assert!(faults.is_empty(), "{} faults", faults.len()); +} + +/// The surface of a plan at a global point. +fn surface_at(plan: &FacePlan, lat: f64, lon: f64) -> Surface { + let g = from_lon_lat(lon, lat); + let o = plan.cell.origin(); + let q = [2 * (g.x - o.x), 2 * (g.y - o.y)]; + let inside = |ring: &[u32]| { + let mut w = 0; + for i in 0..ring.len() { + let a = plan.vertices[ring[i] as usize].map(|v| 2 * i64::from(v)); + let b = plan.vertices[ring[(i + 1) % ring.len()] as usize].map(|v| 2 * i64::from(v)); + let side = + i128::from(b[0] - a[0]) * i128::from(q[1] - a[1]) - i128::from(q[0] - a[0]) * i128::from(b[1] - a[1]); + if a[1] <= q[1] && b[1] > q[1] && side > 0 { + w += 1; + } else if a[1] > q[1] && b[1] <= q[1] && side < 0 { + w -= 1; + } + } + w + }; + let face = plan.faces.iter().find(|f| f.rings.iter().map(|r| inside(r)).sum::() != 0); + face.map_or(Surface::Terrain, |f| f.surface) +} + +#[test] +fn the_land_between_the_legs_of_the_i07_hairpin_stays_land_past_its_turn() { + let mut fixture = Fixture::open(&default_dir()); + let rules = Rules::embedded(); + // Between the legs of its two hairpins, past their turns, and the lower turn itself. + let between = [(46.8217509, 8.4048884), (46.8217678, 8.4050035)]; + let turn = (46.8216499, 8.4049561); + let key = CellKey::of(from_lon_lat(turn.1, turn.0)); + let input = fixture.cell(key); + let graph = graph::build(key, &input, &rules.sections); + let plan = faces::build(&graph, &input, rules, key, 0, true); + for (lat, lon) in between { + let s = surface_at(&plan, lat, lon); + assert!(!matches!(s, Surface::Carriageway | Surface::Crossing), "{s:?} at {lat}, {lon}"); + } + assert_eq!(surface_at(&plan, turn.0, turn.1), Surface::Carriageway); +} diff --git a/host/obc-ground-plan/tests/fixture.rs b/host/obc-ground-plan/tests/fixture.rs new file mode 100644 index 0000000000..a3e0364133 --- /dev/null +++ b/host/obc-ground-plan/tests/fixture.rs @@ -0,0 +1,188 @@ +//! The crate's base over the TrailView fixture: its tiles decode and agree where they overlap, each +//! element of a cell has one owner, and the terrain is known everywhere. + +#[path = "fixture/mod.rs"] +mod fixture; + +use std::collections::{BTreeMap, BTreeSet}; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::frame::{metres_per_unit, CellKey, GlobalPoint, CELL_UNITS}; +use obc_ground_plan::tile::{element_count, features, segment_meets, tile_square, Feature, Geometry, Part}; + +const COLUMNS: std::ops::RangeInclusive = 4286..=4288; +const ROWS: std::ops::RangeInclusive = 2887..=2889; + +/// (kind, tags, the two end points): a segment's key, the same in every tile that holds it. +type Key = (String, String, [i64; 4]); + +fn ends(geometry: Geometry, points: &[GlobalPoint], i: usize) -> (GlobalPoint, GlobalPoint) { + match geometry { + Geometry::Point => (points[i], points[i]), + Geometry::Line => (points[i], points[i + 1]), + Geometry::Area => (points[i], points[(i + 1) % points.len()]), + } +} + +fn key(feature: &Feature, (a, b): (GlobalPoint, GlobalPoint)) -> Key { + (feature.kind.clone(), format!("{:?}", feature.tags), [a.x, a.y, b.x, b.y]) +} + +/// Each element of each part with its index: (feature, part, element). +fn elements(features: &[Feature]) -> impl Iterator { + features.iter().flat_map(|f| { + f.parts.iter().flat_map(move |p| (0..element_count(f.geometry, p.points.len())).map(move |i| (f, p, i))) + }) +} + +fn tiles() -> BTreeMap<(u32, u32), Vec> { + let dir = default_dir(); + let mut out = BTreeMap::new(); + for column in COLUMNS { + for row in ROWS { + let bytes = fixture::feature_tile(&dir, column, row).expect("a fixture tile"); + out.insert((column, row), features(&bytes, column, row).unwrap_or_else(|e| panic!("{column}/{row}: {e}"))); + } + } + out +} + +/// What two tiles must agree on at a vertex: the height and the alignment but `along_m`, with the +/// tangent as its code. +fn vertex(part: &Part, v: usize) -> String { + let height = part.heights.as_ref().map(|h| h[v]); + let plan = part.plan.as_ref().map(|p| { + let turn = (p.tangent[v] * 1024.0 / std::f64::consts::TAU).round() as i64 % 1024; + (turn, p.grade[v], p.bank[v], p.widen[v], p.side[v]) + }); + format!("{height:?} {plan:?}") +} + +/// The values of an element: those of its end vertices, and the walk of a segment. +fn values(feature: &Feature, part: &Part, i: usize) -> String { + let next = if feature.geometry == Geometry::Area { + (i + 1) % part.points.len() + } else { + (i + 1).min(part.points.len() - 1) + }; + let walk = (feature.geometry == Geometry::Line).then(|| part.plan.as_ref().map(|p| p.walk[i])); + format!("{} | {} | {walk:?}", vertex(part, i), vertex(part, next)) +} + +/// Whether an element meets a closed square. +fn meets(feature: &Feature, part: &Part, i: usize, square: [i64; 4]) -> bool { + let (a, b) = ends(feature.geometry, &part.points, i); + segment_meets(a, b, square) +} + +#[test] +fn every_fixture_tile_decodes() { + for ((column, row), features) in tiles() { + let mut kinds: BTreeMap<(&str, Geometry), (usize, usize, usize)> = BTreeMap::new(); + for f in &features { + let count = kinds.entry((f.kind.as_str(), f.geometry)).or_default(); + count.0 += 1; + count.1 += f.parts.len(); + count.2 += f.parts.iter().map(|p| p.points.len()).sum::(); + } + println!("13/{column}/{row}: {} features", features.len()); + for ((kind, geometry), (features, parts, vertices)) in kinds { + println!(" {kind} {geometry:?}: {features} features, {parts} parts, {vertices} vertices"); + } + assert!(!features.is_empty()); + } +} + +#[test] +fn neighbour_tiles_agree_where_both_own() { + let tiles = tiles(); + let mut compared = 0; + for (&a, features_a) in &tiles { + for (&b, features_b) in &tiles { + let (dx, dy) = (i64::from(b.0) - i64::from(a.0), i64::from(b.1) - i64::from(a.1)); + if a == b || dx.abs() > 1 || dy.abs() > 1 { + continue; + } + let held: BTreeMap> = elements(features_b).fold(BTreeMap::new(), |mut map, (f, p, i)| { + map.entry(key(f, ends(f.geometry, &p.points, i))).or_default().push(values(f, p, i)); + map + }); + for (f, p, i) in elements(features_a) { + // A ring's join of the cut lies outside its tile's buffered square: only its edges at + // its own square are the ring's. + if !meets(f, p, i, tile_square(b)) || f.geometry == Geometry::Area && !meets(f, p, i, tile_square(a)) { + continue; + } + let k = key(f, ends(f.geometry, &p.points, i)); + let copies = held.get(&k).unwrap_or_else(|| panic!("{a:?} holds {k:?}, {b:?} does not")); + assert!(copies.contains(&values(f, p, i)), "{k:?}: {a:?} {} and {b:?} {copies:?}", values(f, p, i)); + compared += 1; + } + } + } + println!("{compared} elements compared"); + assert!(compared > 1000); +} + +#[test] +fn each_element_has_one_owner() { + let tiles = tiles(); + let mut fixture = Fixture::open(&default_dir()); + let inside = |key: CellKey| key.feature_tiles().iter().all(|t| tiles.contains_key(t)); + let cells: Vec = fixture.cells().into_iter().filter(|&k| inside(k)).collect(); + assert!(cells.len() > 100); + for key in cells { + let cell = fixture.cell(key); + let mut owners: BTreeMap> = BTreeMap::new(); + for (f, p, i) in elements(&cell.features) { + if p.own[i] { + // An owned element lies in its own tile's square: half-open for a point, so no join of a cut is owned. + let (a, b) = ends(f.geometry, &p.points, i); + let [x0, y0, x1, y1] = tile_square(p.tile); + let held = if a == b { + (x0..x1).contains(&a.x) && (y0..y1).contains(&a.y) + } else { + segment_meets(a, b, [x0, y0, x1, y1]) + }; + assert!(held, "{key:?}: {:?} owns {:?} outside its square", p.tile, key_of(f, p, i)); + owners.entry(key_of(f, p, i)).or_default().insert(p.tile); + } + } + if let Some((k, from)) = owners.iter().find(|(_, from)| from.len() > 1) { + panic!("{key:?}: tiles {from:?} each own {k:?}"); + } + let grown = key.grown(); + for &t in &key.feature_tiles() { + for (f, p, i) in elements(&tiles[&t]) { + let real = f.geometry != Geometry::Area || meets(f, p, i, tile_square(t)); + if real && meets(f, p, i, grown) { + assert!( + owners.contains_key(&key_of(f, p, i)), + "{key:?}: no tile owns {:?} of {t:?}", + key_of(f, p, i) + ); + } + } + } + } +} + +fn key_of(f: &Feature, p: &Part, i: usize) -> Key { + key(f, ends(f.geometry, &p.points, i)) +} + +#[test] +fn the_fixture_terrain_is_known_in_every_cell() { + let mut fixture = Fixture::open(&default_dir()); + for key in fixture.cells() { + let cell = fixture.cell(key); + let step = (10.0 / metres_per_unit(key.origin().y)) as i64; + let o = key.origin(); + for y in (o.y..o.y + CELL_UNITS).step_by(step as usize) { + for x in (o.x..o.x + CELL_UNITS).step_by(step as usize) { + let h = cell.terrain.height(GlobalPoint { x, y }); + assert!(h.is_some_and(|h| (500.0..3500.0).contains(&h)), "{key:?} at ({x}, {y}): {h:?}"); + } + } + } +} diff --git a/host/obc-ground-plan/tests/fixture/mod.rs b/host/obc-ground-plan/tests/fixture/mod.rs new file mode 100644 index 0000000000..c6cf1ddf51 --- /dev/null +++ b/host/obc-ground-plan/tests/fixture/mod.rs @@ -0,0 +1,313 @@ +//! The TrailView fixture as cell inputs: its zoom-13 feature tiles (gzip) and its Terrarium WebP +//! terrain tiles. The fixture tests, the debug tool and the census of `obc-trailview-features` share it. + +// Each of its users reads a part of it. +#![allow(dead_code)] + +use std::collections::BTreeMap; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use obc_ground_plan::frame::{from_lon_lat, CellKey}; +use obc_ground_plan::terrain::{pages_from_terrarium, PageKey, StoredPage, Terrain}; +use obc_ground_plan::tile::{DecodeError, TileCache}; +use obc_ground_plan::transport::{FeatureTile, Request}; +use obc_ground_plan::CellInput; + +/// The workers of `Fixture::map`. +const THREADS: usize = 4; + +/// The decoded pages of a terrain tile z/x/y; None where the fixture lacks the tile. +type Pages = Option<[Option; 4]>; + +pub struct Fixture { + dir: PathBuf, + /// West, south, east, north in degrees. + pub bounds: [f64; 4], + pub cache: TileCache, + terrain: BTreeMap<(u32, u32, u32), Pages>, +} + +/// The fixture of `builder/web`. +pub fn default_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../builder/web/tests/browser/trailview/fixture") +} + +/// The bytes after gzip of feature tile 13/column/row, or None where the fixture lacks it. +pub fn feature_tile(dir: &Path, column: u32, row: u32) -> Option> { + let gzip = std::fs::read(dir.join(format!("features/13/{column}/{row}.bin"))).ok()?; + let mut bytes = Vec::new(); + flate2::read::GzDecoder::new(&gzip[..]).read_to_end(&mut bytes).expect("a fixture tile is gzip"); + Some(bytes) +} + +impl Fixture { + pub fn open(dir: &Path) -> Fixture { + let config: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join("config.json")).expect("the fixture's config.json")) + .unwrap(); + let bounds = std::array::from_fn(|i| config["bounds"][i].as_f64().expect("bounds")); + Fixture { dir: dir.to_path_buf(), bounds, cache: TileCache::new(16), terrain: BTreeMap::new() } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + pub fn tile(&self, column: u32, row: u32) -> Option> { + feature_tile(&self.dir, column, row) + } + + /// The pages of `keys` that the fixture holds. Each WebP decodes once. + pub fn pages(&mut self, keys: &[PageKey]) -> Vec { + keys.iter() + .filter_map(|&key| { + let (z, x, y, quadrant) = key.tile(); + let path = self.dir.join(format!("terrain/{z}/{x}/{y}.webp")); + let pages = self.terrain.entry((z, x, y)).or_insert_with(|| { + let bytes = std::fs::read(path).ok()?; + let rgba = image::load_from_memory_with_format(&bytes, image::ImageFormat::WebP) + .expect("a fixture terrain tile is WebP") + .to_rgba8(); + Some(pages_from_terrarium(rgba.as_raw(), rgba.width() as usize, z, x, y).expect("512 px")) + }); + pages.as_ref()?[quadrant].clone() + }) + .collect() + } + + pub fn try_cell(&mut self, key: CellKey) -> Result { + let pages = self.pages(&Terrain::wanted(key)); + let dir = self.dir.clone(); + CellInput::new(key, &mut self.cache, |column, row| feature_tile(&dir, column, row), pages) + } + + /// The request of a cell: each of its feature tiles that the fixture holds, and its pages. + pub fn request(&mut self, key: CellKey) -> Request { + let tiles = (key.feature_tiles().into_iter()) + .filter_map(|(column, row)| Some(FeatureTile { column, row, bytes: self.tile(column, row)? })) + .collect(); + Request { key, tiles, pages: self.pages(&Terrain::wanted(key)) } + } + + pub fn cell(&mut self, key: CellKey) -> CellInput { + self.try_cell(key).expect("the fixture's tiles decode") + } + + /// `f` of each cell and its input on `THREADS` workers, in the order of `cells`. The workers take + /// the next cell as they finish one; the inputs read one at a time. + pub fn map(&mut self, cells: &[CellKey], f: impl Fn(CellKey, CellInput) -> T + Sync) -> Vec { + let (next, fixture) = (AtomicUsize::new(0), Mutex::new(self)); + let mut done: Vec<(usize, T)> = std::thread::scope(|s| { + let worker = || { + let mut done = Vec::new(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(&key) = cells.get(i) else { break done }; + let input = fixture.lock().unwrap().cell(key); + done.push((i, f(key, input))); + } + }; + let workers: Vec<_> = (0..THREADS).map(|_| s.spawn(worker)).collect(); + workers.into_iter().flat_map(|w| w.join().unwrap()).collect() + }); + done.sort_by_key(|d| d.0); + done.into_iter().map(|d| d.1).collect() + } + + /// The cells whose squares lie inside the bounds. + pub fn cells(&self) -> Vec { + let [west, south, east, north] = self.bounds; + let (a, b) = (CellKey::of(from_lon_lat(west, north)), CellKey::of(from_lon_lat(east, south))); + (a.y + 1..b.y).flat_map(|y| (a.x + 1..b.x).map(move |x| CellKey { x, y })).collect() + } +} + +/// Longitude and latitude of a global point, for tables only: no byte of a plan depends on it. +#[allow(clippy::disallowed_methods)] +pub fn lon_lat(x: f64, y: f64) -> [f64; 2] { + let square = (1u64 << obc_ground_plan::frame::FRAME_BITS) as f64; + let lat = (core::f64::consts::PI * (1.0 - 2.0 * y / square)).sinh().atan(); + [x / square * 360.0 - 180.0, lat.to_degrees()] +} + +/// The levels that a cell owns, for the census tables: each crossing with a ladder, each run of a +/// way with a state (from its middle sample's cell), each end line; places in degrees, classes as +/// rows of `roads.json`; and the counts. +pub fn levels_detail(g: &obc_ground_plan::graph::WayGraph, terrain: &Terrain) -> serde_json::Value { + use serde_json::json; + let o = g.cell.origin(); + let at = |p: [i32; 2]| [o.x as f64 + f64::from(p[0]), o.y as f64 + f64::from(p[1])]; + let owned = |p: [f64; 2]| g.cell.contains(obc_ground_plan::frame::GlobalPoint { x: p[0] as i64, y: p[1] as i64 }); + let way = |w: u32| { + let way = &g.ways[w as usize]; + json!([format!("{:?}", way.family), way.class, format!("{:?}", way.level), w]) + }; + let z = |st: &obc_ground_plan::graph::Station| { + obc_ground_plan::graph::point(&g.parts[st.part as usize], st.span as usize, st.u).z_m + }; + let crossings: Vec<_> = (g.crossings.iter()) + .filter(|c| c.owned) + .filter_map(|c| { + let l = c.ladder.as_ref()?; + let p = at(c.pos); + Some(json!({"at": lon_lat(p[0], p[1]), "kind": format!("{:?}", c.kind), "upper": way(l.upper), + "lower": way(l.lower), "room_m": (l.room_m * 100.0).round() / 100.0, + "centre_dz_m": ((z(&c.over) - z(&c.under)) * 100.0).round() / 100.0, "full_m": l.full_m, + "least_m": l.least_m, "step": format!("{:?}", l.step), "ends": l.ends.map(way)})) + }) + .collect(); + let mut runs = Vec::new(); + for r in &g.levels.runs { + let w = &g.ways[r.way as usize]; + let inside: Vec<[f64; 2]> = (g.samples[w.samples.start as usize..w.samples.end as usize].iter()) + .filter(|s| (s.span, s.u) >= (r.from.span, r.from.u) && (s.span, s.u) <= (r.to.span, r.to.u)) + .map(|s| at(s.pos)) + .collect(); + let Some(mid) = inside.get(inside.len() / 2) else { continue }; + if owned(*mid) { + let ends = [inside[0], inside[inside.len() - 1]].map(|p| lon_lat(p[0], p[1])); + runs.push(json!({"way": way(r.way), "state": format!("{:?}", r.state), "samples": inside.len(), "from": ends[0], "to": ends[1]})); + } + } + let lines: Vec<_> = (g.levels.end_lines.iter()) + .filter_map(|l| { + let (a, b) = (at(l.ends[0]), at(l.ends[1])); + let c = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]; + owned(c).then(|| json!({"at": lon_lat(c[0], c[1]), "kind": format!("{:?}", l.kind), "way": l.way})) + }) + .collect(); + json!({"crossings": crossings, "runs": runs, "end_lines": lines, "counts": levels_counts(g, terrain)}) +} + +/// The census counts of the levels of the elements that a cell owns, so that a sum over cells counts +/// each once. Classes are rows of `roads.json` by number. +#[allow(clippy::disallowed_methods)] +pub fn levels_counts(g: &obc_ground_plan::graph::WayGraph, terrain: &Terrain) -> BTreeMap { + use obc_ground_plan::frame::{metres_per_unit, GlobalPoint}; + use obc_ground_plan::graph::{CrossingKind, Family, Level, State}; + let o = g.cell.origin(); + let at = |p: [i32; 2]| [o.x + i64::from(p[0]), o.y + i64::from(p[1])]; + let owned = |p: [i64; 2]| g.cell.contains(GlobalPoint { x: p[0], y: p[1] }); + let mut c = BTreeMap::new(); + let mut add = |name: String, n: u32| *c.entry(name).or_insert(0) += n; + let tunnel = |w: u32| g.ways[w as usize].level == Level::Tunnel && g.ways[w as usize].family != Family::Water; + let family = |w: u32| format!("{:?}", g.ways[w as usize].family).to_lowercase(); + let class = |w: u32| match g.ways[w as usize].family { + Family::Water => "water".to_string(), + _ => g.ways[w as usize].class.to_string(), + }; + for x in g.crossings.iter().filter(|x| x.owned) { + let Some(l) = &x.ladder else { + if x.kind == CrossingKind::Bore { + add("bore under water (free ground)".into(), 1); + } + continue; + }; + let kind = if x.kind == CrossingKind::LevelCrossing { + "level_crossing".to_string() + } else if tunnel(l.lower) { + format!("bore_{}_under_{}", family(l.lower), family(l.upper)) + } else { + format!("deck_over_{}", family(l.lower)) + }; + add(format!("ladder {kind} {:?}", l.step), 1); + add(format!("ladder all {:?}", l.step), 1); + if let Some(e) = l.ends { + let stay = if e == l.upper { l.lower } else { l.upper }; + add(format!("closed {} over {} ends {}", class(l.upper), class(l.lower), class(e)), 1); + if tunnel(e) && g.ways[e as usize].family == Family::Rail { + add(format!("rail tunnel closed: (a) hidden, (b) open and class {} ends", class(stay)), 1); + } + } + } + let mut decimetres = BTreeMap::::new(); + let samples_of = |w: u32| { + let way = &g.ways[w as usize]; + &g.samples[way.samples.start as usize..way.samples.end as usize] + }; + for r in &g.levels.runs { + let way = &g.ways[r.way as usize]; + let inside = |s: &obc_ground_plan::graph::Sample| { + (s.span, s.u) >= (r.from.span, r.from.u) && (s.span, s.u) <= (r.to.span, r.to.u) + }; + let tagged = + if tunnel(r.way) || g.parts[way.part as usize].level == Level::Deck { "tagged" } else { "untagged" }; + let kept: Vec<_> = samples_of(r.way).iter().filter(|s| inside(s)).collect(); + if let Some(mid) = kept.get(kept.len() / 2) { + if owned(at(mid.pos)) && r.state == State::Hidden && tunnel(r.way) { + add("tunnel hidden runs".into(), 1); + add("tunnel hidden runs of one sample".into(), u32::from(kept.len() == 1)); + } + } + for pair in kept.windows(2) { + let (a, b) = (at(pair[0].pos), at(pair[1].pos)); + let mid = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]; + if !owned(mid) { + continue; + } + let d = (((b[0] - a[0]) as f64).powi(2) + ((b[1] - a[1]) as f64).powi(2)).sqrt() * metres_per_unit(mid[1]); + *decimetres.entry(format!("decimetres {tagged} {:?}", r.state)).or_default() += d * 10.0; + if r.state == State::Hidden && tunnel(r.way) && way.family == Family::Rail { + *decimetres.entry("decimetres rail tunnel hidden".into()).or_default() += d * 10.0; + } + } + } + for (k, v) in decimetres { + add(k, v.round() as u32); + } + for l in &g.levels.end_lines { + let p = at([(l.ends[0][0] + l.ends[1][0]) / 2, (l.ends[0][1] + l.ends[1][1]) / 2]); + if owned(p) { + add(format!("end lines {:?}", l.kind), 1); + } + } + // T15: a DECK run at a way end that goes on as a tunnel way whose first samples lie over the + // terrain, and the metres along it until the terrain rises over its floor. + let arms = || (g.junctions.iter().map(|j| j.arms.as_slice())).chain(g.joints.iter().map(|j| j.arms.as_slice())); + for set in arms() { + for d in set.iter().filter(|a| g.levels.runs.iter().any(|r| r.way == a.way && r.state == State::Deck)) { + let near = (g.levels.runs.iter().filter(|r| r.way == d.way && r.state != State::Open)).min_by(|x, y| { + let k = |r: &&obc_ground_plan::graph::Run| if d.dir > 0 { r.from } else { r.to }; + let dist = |r: &&obc_ground_plan::graph::Run| { + ((k(r).span as f64 + k(r).u) - (d.at.span as f64 + d.at.u)).abs() + }; + dist(x).total_cmp(&dist(y)) + }); + if near.is_none_or(|r| r.state != State::Deck) { + continue; + } + for t in set.iter().filter(|a| tunnel(a.way)) { + let ss = samples_of(t.way); + let seq: Vec<_> = if t.dir > 0 { ss.iter().collect() } else { ss.iter().rev().collect() }; + let under = |s: &&obc_ground_plan::graph::Sample| { + terrain.height(GlobalPoint { x: at(s.pos)[0], y: at(s.pos)[1] }).is_some_and(|h| s.z_m <= h) + }; + if seq.first().is_none_or(under) || !owned(at(seq[0].pos)) { + continue; + } + let first = seq.iter().position(under); + let m = first.map(|k| { + (1..=k) + .map(|i| { + let (a, b) = (at(seq[i - 1].pos), at(seq[i].pos)); + (((b[0] - a[0]) as f64).powi(2) + ((b[1] - a[1]) as f64).powi(2)).sqrt() + * metres_per_unit(a[1]) + }) + .sum::() + }); + let bin = match m { + None => "the tunnel way ends first", + Some(x) if x <= 10.0 => "0-10 m", + Some(x) if x <= 30.0 => "10-30 m", + Some(x) if x <= 100.0 => "30-100 m", + _ => "over 100 m", + }; + add(format!("t15 deck into a tunnel over the terrain: {bin}"), 1); + } + } + } + c +} diff --git a/host/obc-ground-plan/tests/graph.rs b/host/obc-ground-plan/tests/graph.rs new file mode 100644 index 0000000000..10736ca42a --- /dev/null +++ b/host/obc-ground-plan/tests/graph.rs @@ -0,0 +1,293 @@ +//! The way graph over every cell of the TrailView fixture: the invariants G1 to G4 of `check` and G7 +//! to G9 of `check_levels`, equal graphs and levels near the border of two neighbouring cells (G5), +//! the same bytes twice (G6), and the levels that the tiles carry. + +#[path = "fixture/mod.rs"] +mod fixture; + +use std::collections::{BTreeMap, BTreeSet}; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::faces::Rules; +use obc_ground_plan::frame::{metres_per_unit, CellKey, CELL_UNITS}; +use obc_ground_plan::graph::{ + build, build_levelled, check, check_levels, level_tags, levels, s_at, Arm, Level, Sample, State, Station, WayGraph, +}; +use obc_ground_plan::sections::Sections; +use obc_ground_plan::tile::Tags; +use obc_ground_plan::CellInput; + +/// The band on each side of a shared border where two cells must agree. +const BAND_M: f64 = 100.0; + +/// The fixture's cells whose feature tiles the fixture holds, built, with their levels. +fn graphs() -> BTreeMap { + let mut fixture = Fixture::open(&default_dir()); + let dir = default_dir(); + let cells: Vec = (fixture.cells().into_iter()) + .filter(|k| k.feature_tiles().iter().all(|&(c, r)| fixture::feature_tile(&dir, c, r).is_some())) + .collect(); + assert!(cells.len() > 100, "{} cells", cells.len()); + cells.into_iter().map(|key| (key, built(key, &fixture.cell(key)))).collect() +} + +fn built(key: CellKey, input: &CellInput) -> WayGraph { + let mut g = build(key, input, Sections::embedded()); + levels(&mut g, input, Sections::embedded(), &Rules::embedded().structures); + g +} + +#[test] +fn every_fixture_cell_holds_g1_to_g4_and_g6() { + let mut fixture = Fixture::open(&default_dir()); + let graphs = graphs(); + let mut faults = Vec::new(); + let (mut junctions, mut crossings) = (0, 0); + for (key, graph) in &graphs { + let input = fixture.cell(*key); + let lv = check_levels(graph, &input, Sections::embedded(), &Rules::embedded().structures); + faults.extend(check(graph).into_iter().chain(lv).map(|f| format!("{key:?} {}: {}", f.check, f.what))); + junctions += graph.junctions.iter().filter(|j| j.owned).count(); + crossings += graph.crossings.iter().filter(|c| c.owned).count(); + } + println!("{} cells, {junctions} owned junctions, {crossings} owned crossings", graphs.len()); + assert!(faults.is_empty(), "{} faults:\n{}", faults.len(), faults[..faults.len().min(40)].join("\n")); + for key in graphs.keys().step_by(7) { + let again = built(*key, &fixture.cell(*key)); + assert_eq!(format!("{again:?}"), format!("{:?}", graphs[key]), "G6: {key:?} builds twice the same"); + } + assert!(junctions > 100 && crossings > 10); +} + +/// What two cells must agree on near a border, keyed by global position, as text. +fn band(graph: &WayGraph, near: &dyn Fn([i64; 2]) -> bool) -> BTreeSet { + let o = graph.cell.origin(); + let global = |p: [i32; 2]| [o.x + i64::from(p[0]), o.y + i64::from(p[1])]; + let mut out = BTreeSet::new(); + for way in &graph.ways { + let part = &graph.parts[way.part as usize]; + for s in &graph.samples[way.samples.start as usize..way.samples.end as usize] { + if near(global(s.pos)) { + let span = s.span as usize; + let start = part.vertices[span].pos; + let end = part.vertices.get(span + 1).map(|v| v.pos); + out.insert(format!( + "sample {start:?} {end:?} {:?} {:?} u {} z {} t {:?} g {} b {} w {} walk {} {:?}", + s.s_m.to_bits(), + global(s.pos), + s.u, + s.z_m, + s.tangent, + s.grade, + s.bank, + s.widen_m, + s.walk, + s.kind + )); + } + } + if graph.decks.iter().any(|d| d.synthetic && d.ways.contains(&way.id)) { + let first = &graph.samples[way.samples.start as usize]; + let last = &graph.samples[way.samples.end as usize - 1]; + if near(global(first.pos)) || near(global(last.pos)) { + out.insert(format!("stretch {:?} {:?}", global(first.pos), global(last.pos))); + } + } + } + let arms = |arms: &[Arm]| -> Vec { + arms.iter() + .map(|a| { + format!("{} {} {:?} {} {}", a.dir, a.host, a.level, a.room_m, graph.ways[a.way as usize].family as u8) + }) + .collect() + }; + for j in graph.junctions.iter().filter(|j| near(global(j.pos))) { + out.insert(format!( + "junction {:?} {:?} {:?} {} {:?}", + global(j.pos), + j.network, + j.host_rule, + j.implicit, + arms(&j.arms) + )); + } + for j in graph.joints.iter().filter(|j| near(global(j.pos))) { + out.insert(format!( + "joint {:?} {:?} {} {} {:?}", + global(j.pos), + j.network, + j.turn_rad, + j.stroke, + arms(&j.arms) + )); + } + for e in graph.ends.iter().filter(|e| near(global(e.pos))) { + out.insert(format!("end {:?} {:?} {:?}", global(e.pos), e.network, arms(std::slice::from_ref(&e.arm)))); + } + for c in graph.crossings.iter().filter(|c| near(global(c.pos))) { + // The step and whether the upper way is the one that ends. + let step = c.ladder.as_ref().map(|l| (l.step, l.ends.map(|e| e == l.upper))); + out.insert(format!("crossing {:?} {:?} {:?} {} {step:?}", global(c.pos), c.kind, c.source, c.angle_rad)); + } + // The levels: the state at each sample of a way with a state, and the end lines. + for r in &graph.levels.runs { + let way = &graph.ways[r.way as usize]; + let inside = |s: &&Sample| (s.span, s.u) >= (r.from.span, r.from.u) && (s.span, s.u) <= (r.to.span, r.to.u); + for s in graph.samples[way.samples.start as usize..way.samples.end as usize].iter().filter(inside) { + if near(global(s.pos)) { + out.insert(format!("state {:?} {:?}", global(s.pos), r.state)); + } + } + } + for l in &graph.levels.end_lines { + let ends = [global(l.ends[0]), global(l.ends[1])]; + if near(ends[0]) || near(ends[1]) { + out.insert(format!("end line {:?} {ends:?}", l.kind)); + } + } + out +} + +#[test] +fn neighbouring_cells_agree_near_their_border_g5() { + let graphs = graphs(); + let (mut pairs, mut compared, mut faults) = (0, 0, Vec::new()); + for (&a, ga) in &graphs { + for b in [CellKey { x: a.x + 1, y: a.y }, CellKey { x: a.x, y: a.y + 1 }] { + let Some(gb) = graphs.get(&b) else { continue }; + let o = b.origin(); + let band_units = (BAND_M / metres_per_unit(o.y)) as i64; + let east = b.x != a.x; + // Within the band of the shared border line, along the border's length. + let near = |p: [i64; 2]| { + let (across, along, start) = if east { (p[0] - o.x, p[1], o.y) } else { (p[1] - o.y, p[0], o.x) }; + across.abs() <= band_units && (start - band_units..=start + CELL_UNITS + band_units).contains(&along) + }; + let (sa, sb) = (band(ga, &near), band(gb, &near)); + pairs += 1; + compared += sa.len(); + for only in sa.symmetric_difference(&sb).take(6) { + let side = if sa.contains(only) { "only in" } else { "not in" }; + faults.push(format!("{a:?} | {b:?}: {side} {a:?}: {only}")); + } + } + } + println!("{pairs} borders, {compared} elements compared"); + assert!(pairs > 100 && compared > 10_000); + assert!(faults.is_empty(), "{} differences:\n{}", faults.len(), faults[..faults.len().min(40)].join("\n")); +} + +/// The levels that the fixture's tiles carry are those that `levels` gives the cells: the tags of each feature are +/// those that the bake's merge (`level_tags::merge`) gives of what the cells find, storey and slab included; and the +/// graph of the storeys (`build_levelled`) gives every way inside a cell's square the level of its stretch's state, +/// with no way on a HIDDEN stretch, and cuts each bridge at its end lines. A change of the levels or of their rules takes a new bake of the fixture. +/// A cut of the storeys' graph lies this near its end line (metres): `level_tags::split` merges closer stations. +const CUT_M: f64 = 1e-6; + +#[test] +fn the_tiles_carry_the_levels_of_each_cell() { + let mut fixture = Fixture::open(&default_dir()); + let (mut faults, mut ways, mut ends) = (Vec::new(), 0, 0); + // A feature by its kind and tags, the same in each tile that holds it; and its level tags. + let (mut ids, mut carried_tags) = (BTreeMap::::new(), BTreeMap::::new()); + let (mut found, mut groups, mut over) = (BTreeMap::>::new(), Vec::new(), Vec::new()); + for (key, computed) in graphs() { + let input = fixture.cell(key); + let cell = level_tags::found(&computed, &input, Sections::embedded()); + let mut id = |[c, r, index]: [u32; 3]| { + let f = input.features.iter().find(|f| f.parts[0].tile == (c, r) && f.index == index).unwrap(); + let next = ids.len() as u32; + let id = *ids.entry(format!("{} {:?}", f.kind, f.tags)).or_insert(next); + let own = [level_tags::LEVELS, level_tags::STOREY, level_tags::SLAB]; + let tags = f.tags.iter().filter(|(k, _)| own.contains(&k.as_str())); + carried_tags.insert(id, tags.map(|(k, v)| (k.clone(), v.clone())).collect()); + id + }; + for (k, f) in cell.found { + found.entry(id(k)).or_default().push(f); + } + groups.extend(cell.groups.into_iter().map(|g| g.into_iter().map(&mut id).collect::>())); + over.extend(cell.over.into_iter().map(|(l, u)| (id(l), id(u)))); + // The graph of the storeys gives each stretch the level of its state, and holds no HIDDEN stretch. + let levelled = build_levelled(key, &input, Sections::embedded(), Rules::embedded().structures.edge_band_m); + let k = |st: &Station| (st.span, st.u); + let state = |st: &Station| { + let run = computed + .levels + .runs + .iter() + .find(|r| r.from.part == st.part && k(&r.from) <= k(st) && k(st) <= k(&r.to)); + run.map(|r| r.state) + }; + // A point strictly inside the way: an end sample lies on a run boundary, where rounding picks either run. + let middle = |g: &WayGraph, w: u32| { + let (a, b) = (g.ways[w as usize].from, g.ways[w as usize].to); + let u = if a.span == b.span { (a.u + b.u) / 2.0 } else { (a.u + 1.0) / 2.0 }; + Station { u, ..a } + }; + for w in (0..levelled.ways.len() as u32).filter(|&w| level_tags::inside(&levelled, w)) { + let way = &levelled.ways[w as usize]; + let part = &levelled.parts[way.part as usize]; + if part.level == Level::Tunnel || (way.level == Level::Deck && part.level != Level::Deck) { + continue; + } + let want = match state(&middle(&levelled, w)) { + Some(State::Deck) => Level::Deck, + Some(State::Open) => Level::Ground, + Some(State::Hidden) => { + faults.push(format!("{key:?} way {w}: it lies on a HIDDEN stretch")); + continue; + } + _ => continue, + }; + ways += 1; + if way.level != want { + faults.push(format!("{key:?} way {w}: on {:?}, its stretch's state gives {want:?}", way.level)); + } + } + // Each end line of a carried stretch cuts its way where the cell computes it: a way of the storeys' graph on + // its part ends there, within the merge's 1e-6 m. + let along = |g: &WayGraph, st: &Station| { + let part = &g.parts[st.part as usize]; + let span = &part.spans[st.span as usize]; + span.along0_m + if part.backward { -1.0 } else { 1.0 } * s_at(span, st.u) + }; + let cuts: Vec<(u32, f64)> = (levelled.ways.iter()) + .filter(|w| levelled.parts[w.part as usize].level == Level::Deck) + .flat_map(|w| [(w.part, along(&levelled, &w.from)), (w.part, along(&levelled, &w.to))]) + .collect(); + for l in computed.levels.end_lines.iter().filter(|l| level_tags::inside(&computed, l.way)) { + if computed.parts[l.at.part as usize].level != Level::Deck { + continue; + } + ends += 1; + let m = along(&computed, &l.at); + if !cuts.iter().any(|&(p, c)| p == l.at.part && (c - m).abs() <= CUT_M) { + faults + .push(format!("{key:?} way {}: no way of the storeys' graph ends at its end line ({m} m)", l.way)); + } + } + for r in + computed.levels.runs.iter().filter(|r| r.state == State::Hidden && level_tags::inside(&computed, r.way)) + { + let st = Station { part: r.from.part, span: (r.from.span + r.to.span) / 2, u: 0.5 }; + if k(&st) > k(&r.from) && k(&st) < k(&r.to) && levelled.way_at(&st, Level::Ground).is_some() { + faults.push(format!("{key:?} way {}: a way of the storeys' graph lies on its HIDDEN stretch", r.way)); + } + } + } + let merged = level_tags::merge(&found, &groups, &over); + let mut counts = BTreeMap::::new(); + for (id, carried) in &carried_tags { + let want = merged.get(id).cloned().unwrap_or_default(); + for k in want.keys() { + *counts.entry(k.clone()).or_default() += 1; + } + if want != *carried { + faults.push(format!("feature {id}: the cells give {want:?}, the tiles carry {carried:?}")); + } + } + println!("{ways} ways of the storeys' graph on a carried stretch, {ends} end lines; tags of the cells' features {counts:?}"); + assert!(ways > 10 && ends > 10, "the fixture's bridges and tunnels"); + assert!(faults.is_empty(), "{} faults:\n{}", faults.len(), faults[..faults.len().min(10)].join("\n")); +} diff --git a/host/obc-ground-plan/tests/heights_fixture.rs b/host/obc-ground-plan/tests/heights_fixture.rs new file mode 100644 index 0000000000..d91f0bc6cb --- /dev/null +++ b/host/obc-ground-plan/tests/heights_fixture.rs @@ -0,0 +1,351 @@ +//! The heights over every cell of the TrailView fixture: steps inside faces, steps at label edges +//! with no rule and slopes steeper than a rock face do not grow, no cap acts, every paved face finds +//! its host, every deck end has its end face and the ground stays under every deck, and two cells give +//! a point on their shared line the same bits. The scan's steps with no rule and the ripple of the +//! carriageways are guidelines: printed, not gated. A fault within the reach of a tile's water vertex whose +//! level lies far off the terrain is the bake's: a level never rises downstream, so a dip upstream holds it +//! under the later terrain (a pit), and where the map's line runs on a slope beside the valley floor, the +//! level is the low ground across the line. Those faults are counted apart and gated apart: the reader +//! cannot move its own faults out of the gate. + +#[path = "fixture/mod.rs"] +mod fixture; + +use std::collections::BTreeMap; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::faces::heights::check::{ + at, border, deck_ends, edge_steps, held_over_cap, ripple, scan, slope_steps, under_decks, wall_steps, Class, + EDGE_GRID_M, RIPPLE_M, +}; +use obc_ground_plan::faces::heights::Step; +use obc_ground_plan::faces::records; +use obc_ground_plan::faces::Rules; +use obc_ground_plan::faces::Surface; +use obc_ground_plan::frame::{from_lon_lat, metres_per_unit, CellKey, GlobalPoint, CELL_UNITS, FRAME_BITS}; +use obc_ground_plan::graph; +use obc_ground_plan::sections::WATER_KINDS; +use obc_ground_plan::CellInput; + +/// The grid of the step scan, metres. +const GRID_M: f64 = 0.5; +/// Steps inside faces, measured on the revision 17 fixture with the slopes from the paved outline and line +/// water: the count must not grow. +const INSIDE_MAX: usize = 9; +/// Steps at label edges with no rule (`check::edge_steps`), measured on the revision 17 fixture with the +/// slopes from the outline pieces of `records::outline_edges` and the vertex values of `heights::groups` +/// (an end's cone over the fan of its turn only), walls up to the highest wall, faces past it as steep as +/// their need, line water and its culverts and fords: the count must not grow. +const EDGE_MAX: usize = 101; +/// Pairs of grid points on a slope steeper than a rock face where the terrain is not (`Scan::steep`), +/// measured on the revision 17 fixture with cones on their outward side, the outline pieces of +/// `records::outline_edges` and the vertex values of `heights::groups`, faces past the highest wall as steep +/// as their need, the faces' rings with a vertex at each tile line, and the banks of line water, whose cuts +/// climb as steep as the terrain asks beside a gorge, its culverts, the ground under the decks' ceilings, and a +/// paved outline that holds no water: the count must not grow. +const STEEP_MAX: usize = 2465; +/// Of those, the pairs steeper than 6 m/m, measured the same way: the bank of one way that crosses a gully +/// inside its ground band, which spans the terrain across the way's width. The count must not grow, and no pair +/// is steeper than 12 m/m: a near-vertical rim that the total hides must not come back. +const NEAR_VERTICAL_MAX: usize = 2; +/// A no-room wall's height that changes along it by more than this per metre is a step in its top +/// (`check::wall_steps`): pairs of points measured on the revision 17 fixture with the slope and the wall of +/// each point from the need at its foot (`heights::fit`) and line water: the count must not grow. +const WALL_STEP_GRADE: f64 = 0.5; +const WALL_STEPS_MAX: usize = 17; +/// The ground's grade along the rim that changes across a piece end by more than this is a shading band +/// (`check::slope_steps`), measured the same way, with the faces' rings with a vertex at each tile line (it +/// moves piece ends by a few units), the crease where a deck's ceiling takes the ground, and line water, whose +/// curved banks end many short pieces, its culverts, and a paved outline that holds no water: the count must not +/// grow. +const SLOPE_STEP_GRADE: f64 = 0.1; +const SLOPE_STEPS_MAX: usize = 12967; +/// A tile's water vertex whose level lies more than this off the terrain at the vertex has a level that +/// the bake holds away from its line (a pit, or the low ground beside it): the design keeps the water at +/// most `freeboard_m` (0.8 m) under its bank and `depth_m` (1 m) deep. +const LEVEL_OFF_M: f64 = 3.0; +/// The faults within this of such a vertex, or of a tile segment between two such vertices, are its: a +/// river's bank reach (15 m) and a half-width. +const LEVEL_REACH_M: f64 = 20.0; +/// The faults near such levels (steps, edge steps, steep pairs, wall-top steps, slope steps), measured on +/// the revision 17 fixture: the counts must not grow. +const LEVEL_MAX: [usize; 5] = [10, 85, 10882, 0, 1637]; +/// Steps that another line's cone holds higher than the paved side's wall cap (`check::held_over_cap`) between +/// two ways, measured the same way with a rail bed's fill counted past its wall cap: all at the edge of a class +/// without a wall, most where the two outlines leave no room for the steep face (the gap is printed): the count +/// must not grow. +const HELD_OVER_CAP_MAX: usize = 74; +/// Such steps where a side is line water, which has no wall (a way's fill that holds a bank over a waterline, or a +/// bank's fill over a way's edge), counted apart and measured the same way with a paved outline that holds no water +/// (where a way's edge meets the water, the bank's fill stands against it, and no round of the way's paving covers +/// the corner; 90 of them stand within 25 m of 46.82015, 8.3866, at the river's bank against two paths' edges): the +/// count must not grow. +const HELD_WATER_MAX: usize = 663; +/// The grid of the ground under the decks, metres. +const DECK_GRID_M: f64 = 0.5; +/// An end face may fall short of the deck's depth and the gap by this much, where its paved end's height is not +/// the way's own surface (a junction's blend face) or the two ways' frames tilt their banks apart. +const SHORT_M: f64 = 0.1; +/// End line points shorter than that, measured on the revision 17 fixture: the count must not grow. +const SHORT_MAX: usize = 22; +/// The places of the ripple report (latitude, longitude). +const PLACES: [(&str, f64, f64); 5] = [ + ("v17-sharp-corners", 46.821753, 8.404913), + ("i07-hairpin", 46.82177, 8.40497), + ("d-hairpin", 46.827088, 8.391039), + ("main-road-15m", 46.827847, 8.380036), + ("valley-junction", 46.828466, 8.378529), +]; +/// The side of a place's square, metres. +const PLACE_M: f64 = 64.0; + +struct Cell { + words: Vec, + input: CellInput, +} + +#[test] +fn every_fixture_cell_keeps_its_steps_on_face_edges_and_agrees_with_its_neighbours() { + let dir = default_dir(); + let mut fixture = Fixture::open(&dir); + let rules = Rules::embedded(); + let mut cells: Vec = (fixture.cells().into_iter()) + .filter(|k| k.feature_tiles().iter().all(|&(c, r)| fixture::feature_tile(&dir, c, r).is_some())) + .collect(); + assert!(cells.len() > 100, "{} cells", cells.len()); + // The cells of the places past the fixture's bounds: for their ripple only. + let mut places: Vec = PLACES.iter().flat_map(|&(_, lat, lon)| place_cells(lat, lon)).collect(); + places.retain(|k| !cells.contains(k)); + places.sort(); + places.dedup(); + let scanned = cells.len(); + cells.extend(places); + let built = fixture.map(&cells, |key, input| { + let graph = graph::build(key, &input, &rules.sections); + let words = records::build(&graph, &input, rules, key, 0, true).near.words; + let ours = cells[..scanned].contains(&key); + let mut s = if ours { scan(&words, &input.terrain, key, GRID_M) } else { Default::default() }; + let mut e = if ours { edge_steps(&words, &input.terrain, key, EDGE_GRID_M) } else { Vec::new() }; + let mut w = if ours { wall_steps(&words, &input.terrain, key, WALL_STEP_GRADE) } else { Vec::new() }; + let mut g = if ours { slope_steps(&words, &input.terrain, key, SLOPE_STEP_GRADE) } else { Vec::new() }; + // The steps between water and a way (the ends that B's crossings close): count and greatest. + let water = |l: Option| l.is_some_and(|id| records::label(&words, id)[0] & 0xff == Surface::Water as u32); + let apart = (s.steps.iter()) + .filter(|st| st.class == Class::Named(Step::Unrelated) && water(st.labels[0]) != water(st.labels[1])) + .fold((0, 0.0f64), |(n, m), st| (n + 1, m.max(st.dh.abs()))); + // The faults of the bake's water levels, apart: steps, edge steps, steep pairs, wall-top and slope steps. + let off = off_level(&input, key); + let n = [s.steps.len(), e.len(), s.steep.len(), w.len(), g.len()]; + s.steps.retain(|st| !off(st.a)); + e.retain(|st| !off(st.a)); + s.steep.retain(|st| !off(st.0)); + w.retain(|st| !off(st.0)); + g.retain(|st| !off(st.0)); + let kept = [s.steps.len(), e.len(), s.steep.len(), w.len(), g.len()]; + let levels: [usize; 5] = std::array::from_fn(|k| n[k] - kept[k]); + let line = if ours { border(&words, &input.terrain, key, 512) } else { Vec::new() }; + let held = if ours { held_over_cap(&words, &input.terrain, key, EDGE_GRID_M) } else { Vec::new() }; + let decks = ours + .then(|| (deck_ends(&words, &input.terrain, key), under_decks(&words, &input.terrain, key, DECK_GRID_M))); + (key, s, [e.len(), w.len(), g.len()], line, levels, apart, (held, decks), Cell { words, input }) + }); + let (mut inside, mut unnamed, mut full, mut missing, mut water_off) = (0, 0, 0, 0, 0); + let [mut edges, mut walls, mut slopes] = [0; 3]; + let mut levels = [0; 5]; + let mut apart = (0, 0.0f64); + let mut steep = Vec::new(); + let mut lines: BTreeMap<_, Vec<_>> = BTreeMap::new(); + let mut by_key = BTreeMap::new(); + let (mut held, mut ends, mut points, mut under, mut faults) = (Vec::new(), 0, 0, [0; 4], Vec::new()); + let (mut uncovered, mut paved_beyond, mut short) = (0, 0, Vec::new()); + for (key, s, e, line, l, a, (h, decks), cell) in built { + apart = (apart.0 + a.0, apart.1.max(a.1)); + levels = std::array::from_fn(|k| levels[k] + l[k]); + held.extend(h.into_iter().map(|h| (key, h))); + if let Some((d, u)) = decks { + (ends, points) = (ends + d.ends, points + d.points); + under = [0, 1, 2, 3].map(|k| under[k] + u[k]); + faults.extend(d.over.iter().map(|(q, m)| format!("{key:?} {q:?}: ground {m:.3} m over the deck's bound"))); + let named = d.short.iter().filter(|s| s.3 != Step::EndFace); + faults.extend(named.map(|(q, m, drop, r)| format!("{key:?} {q:?}: end face {m:.3} m of {drop:.3}, {r:?}"))); + short.extend(d.short.iter().filter(|s| s.3 == Step::EndFace).map(|s| s.2 - s.1)); + (uncovered, paved_beyond) = (uncovered + d.uncovered.len(), paved_beyond + d.paved_beyond.len()); + } + inside += s.steps.iter().filter(|st| st.class == Class::Inside).count(); + (edges, walls, slopes) = (edges + e[0], walls + e[1], slopes + e[2]); + unnamed += s.steps.iter().filter(|st| st.class == Class::Unnamed).count(); + let o = key.origin(); + steep.extend(s.steep.iter().map(|st| ([o.x as f64 + st.0[0], o.y as f64 + st.0[1]], st.1))); + (full, missing) = (full + s.slots_full.len(), missing + s.host_missing.len()); + water_off += s.water_off.len(); + for (k, v) in line { + lines.entry(k).or_default().push(v); + } + by_key.insert(key, cell); + } + let over = |m: f64| steep.iter().filter(|c| c.1 > m).count(); + let (over_6, over_12) = (over(6.0), over(12.0)); + println!( + "inside {inside}, unnamed {unnamed}, edge steps {edges}, wall-top steps {walls}, slope steps {slopes}, steep {} (over 6 m/m {over_6}, over 12 m/m {over_12}), slots full {full}, host missing {missing}", + steep.len() + ); + println!( + "near water levels over {LEVEL_OFF_M} m off the terrain: steps {}, edge steps {}, steep {}, wall-top steps {}, slope steps {}", + levels[0], levels[1], levels[2], levels[3], levels[4] + ); + println!("steps between water and a way (not gated): {}, greatest {:.2} m", apart.0, apart.1); + // The five steepest places, each the steepest pair within `LEVEL_REACH_M` of it. + steep.sort_by(|a, b| b.1.total_cmp(&a.1)); + let mut worst: Vec<([f64; 2], f64)> = Vec::new(); + for &(g, climb) in &steep { + let near = |p: &([f64; 2], f64)| { + libm::hypot(p.0[0] - g[0], p.0[1] - g[1]) * metres_per_unit(g[1] as i64) < LEVEL_REACH_M + }; + if worst.len() < 5 && !worst.iter().any(near) { + worst.push((g, climb)); + } + } + for (g, climb) in worst { + let [lat, lon] = lat_lon(g); + println!("steep {climb:.1} m/m at {lat:.6},{lon:.6}"); + } + println!( + "deck ends {ends} ({points} end line points, {uncovered} under no deck, {paved_beyond} with a paved face beyond), {} faults, end faces short of the drop {} (over {SHORT_M} m {}, most {:.3} m); under the decks {} points, ground over {}, paved over {}, notches at deck joints {}; held over the cap {}", + faults.len(), + short.len(), + short.iter().filter(|&&m| m > SHORT_M).count(), + short.iter().copied().fold(0.0, f64::max), + under[0], + under[1], + under[2], + under[3], + held.len() + ); + let (wet, held): (Vec<_>, Vec<_>) = held.into_iter().partition(|(_, h)| h.water); + for (key, h) in &held { + println!(" held over the cap {key:?} {:?}: {:.2} m, gap {:.2} m, caps {:?}", h.at, h.height, h.gap, h.caps); + } + let mut heights: Vec = wet.iter().map(|(_, h)| h.height).collect(); + heights.sort_by(f64::total_cmp); + let share = |q: f64| heights.get(((heights.len() as f64 - 1.0) * q) as usize).copied().unwrap_or(0.0); + println!( + "held over the cap at line water {}: height p50 {:.2} m, p90 {:.2} m, max {:.2} m", + wet.len(), + share(0.5), + share(0.9), + share(1.0) + ); + assert!(inside <= INSIDE_MAX, "{inside} steps inside faces"); + assert!(edges <= EDGE_MAX, "{edges} steps at label edges with no rule"); + assert!(walls <= WALL_STEPS_MAX, "{walls} wall-top steps over {WALL_STEP_GRADE} m/m"); + assert!(slopes <= SLOPE_STEPS_MAX, "{slopes} slope steps over {SLOPE_STEP_GRADE} m/m"); + assert!(steep.len() <= STEEP_MAX, "{} slope pairs steeper than a rock face", steep.len()); + assert!( + over_6 <= NEAR_VERTICAL_MAX && over_12 == 0, + "{over_6} slope pairs steeper than 6 m/m, {over_12} than 12 m/m" + ); + assert!((0..5).all(|k| levels[k] <= LEVEL_MAX[k]), "{levels:?} faults near water levels off the terrain"); + assert_eq!((full, missing, water_off), (0, 0, 0), "slots full, host missing, water off its level"); + assert!(ends > 0, "no deck end in the fixture"); + assert!(faults.is_empty(), "{} deck end faults: {:#?}", faults.len(), &faults[..faults.len().min(10)]); + assert_eq!(under[1], 0, "ground points over a deck's bound"); + assert_eq!(under[3], 0, "points at a joint of two decks under no deck"); + assert!(short.iter().filter(|&&m| m > SHORT_M).count() <= SHORT_MAX, "end faces short by over {SHORT_M} m"); + assert!(held.len() <= HELD_OVER_CAP_MAX, "{} held steps over the cap", held.len()); + assert!(wet.len() <= HELD_WATER_MAX, "{} held steps over the cap at line water", wet.len()); + let shared: Vec<_> = lines.values().filter(|v| v.len() == 2).collect(); + assert!(shared.len() > 100_000, "{} shared points", shared.len()); + let differ: Vec<_> = shared.iter().filter(|v| v[0].h != v[1].h || v[0].t != v[1].t).collect(); + assert!( + differ.is_empty(), + "{} of {} border points differ: {:?}", + differ.len(), + shared.len(), + &differ[..differ.len().min(3)] + ); + for (name, lat, lon) in PLACES { + let [along, across] = place_ripple(&by_key, lat, lon); + println!("{name}: ripple p99 along {:.2} mm, across {:.2} mm", along * 1e3, across * 1e3); + } +} + +/// Whether a point of a cell (frame units) lies within `LEVEL_REACH_M` of a tile's ground water vertex +/// whose own level is more than `LEVEL_OFF_M` off the terrain there, or of a tile segment between two +/// such vertices. It reads the input only, never the reader's levels. +fn off_level(input: &CellInput, key: CellKey) -> impl Fn([f64; 2]) -> bool { + let o = key.origin(); + let reach = LEVEL_REACH_M / metres_per_unit(o.y + CELL_UNITS / 2); + let ground = |f: &&obc_ground_plan::tile::Feature| { + WATER_KINDS.contains(&f.kind.as_str()) && f.tags.get("tunnel").is_none_or(|t| t == "no") + }; + let mut off: Vec<[[f64; 2]; 2]> = Vec::new(); + for part in input.features.iter().filter(ground).flat_map(|f| &f.parts) { + let Some(heights) = &part.heights else { continue }; + let far: Vec = (part.points.iter().zip(heights)) + .map(|(&g, z)| z.zip(input.terrain.height(g)).is_some_and(|(z, t)| (z - t).abs() > LEVEL_OFF_M)) + .collect(); + let local = |i: usize| [(part.points[i].x - o.x) as f64, (part.points[i].y - o.y) as f64]; + for i in (0..far.len()).filter(|&i| far[i]) { + let next = if far.get(i + 1) == Some(&true) { i + 1 } else { i }; + off.push([local(i), local(next)]); + } + } + move |q| off.iter().any(|&[a, b]| distance(q, a, b) < reach) +} + +/// The distance of q from the segment ab. +fn distance(q: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 { + let d = [b[0] - a[0], b[1] - a[1]]; + let len2 = d[0] * d[0] + d[1] * d[1]; + let t = if len2 > 0.0 { (((q[0] - a[0]) * d[0] + (q[1] - a[1]) * d[1]) / len2).clamp(0.0, 1.0) } else { 0.0 }; + libm::hypot(a[0] + t * d[0] - q[0], a[1] + t * d[1] - q[1]) +} + +/// The latitude and longitude of a global point in frame units. +fn lat_lon(g: [f64; 2]) -> [f64; 2] { + let square = (1u64 << FRAME_BITS) as f64; + let lat = libm::atan(libm::sinh(std::f64::consts::PI * (1.0 - 2.0 * g[1] / square))).to_degrees(); + [lat, g[0] / square * 360.0 - 180.0] +} + +/// The cells of a place's square. +fn place_cells(lat: f64, lon: f64) -> Vec { + let centre = from_lon_lat(lon, lat); + let half = (PLACE_M / 2.0 / metres_per_unit(centre.y)) as i64; + let (a, b) = ( + CellKey::of(GlobalPoint { x: centre.x - half, y: centre.y - half }), + CellKey::of(GlobalPoint { x: centre.x + half, y: centre.y + half }), + ); + (a.y..=b.y).flat_map(|y| (a.x..=b.x).map(move |x| CellKey { x, y })).collect() +} + +/// The p99 of the carriageway's second differences along and across at a place, metres. +fn place_ripple(cells: &BTreeMap, lat: f64, lon: f64) -> [f64; 2] { + let centre = from_lon_lat(lon, lat); + let upm = 1.0 / metres_per_unit(centre.y); + let n = (PLACE_M / RIPPLE_M) as i64; + let mut d2: [Vec; 2] = [Vec::new(), Vec::new()]; + for j in 0..n { + for i in 0..n { + let g = [ + centre.x as f64 + ((i - n / 2) as f64 * RIPPLE_M) * upm, + centre.y as f64 + ((j - n / 2) as f64 * RIPPLE_M) * upm, + ]; + let key = CellKey::of(GlobalPoint { x: g[0].floor() as i64, y: g[1].floor() as i64 }); + let Some(c) = cells.get(&key) else { continue }; + let o = key.origin(); + let q = [g[0] - o.x as f64, g[1] - o.y as f64]; + let Some(h) = at(&c.words, &c.input.terrain, key, q) else { continue }; + if let Some(r) = ripple(&c.words, &c.input.terrain, key, q, h) { + for (k, v) in r.into_iter().enumerate().filter(|(_, v)| !v.is_nan()) { + d2[k].push(v.abs()); + } + } + } + } + d2.map(|mut v| { + assert!(v.len() > 500, "{} points", v.len()); + v.sort_by(f64::total_cmp); + v[v.len() * 99 / 100] + }) +} diff --git a/host/obc-ground-plan/tests/mesh.rs b/host/obc-ground-plan/tests/mesh.rs new file mode 100644 index 0000000000..34f2a9336b --- /dev/null +++ b/host/obc-ground-plan/tests/mesh.rs @@ -0,0 +1,92 @@ +//! The near mesh over every cell of the TrailView fixture: valid topology, the records' labels, the end +//! faces on the deck end lines with whole ground about them, and two neighbouring cells with the same +//! corners and heights on their shared line. + +#[path = "fixture/mod.rs"] +mod fixture; + +use std::collections::BTreeMap; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::faces::{records, Rules}; +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::graph; +use obc_ground_plan::mesh::{check, mesh_cell, Reads, Rim}; + +/// Ground triangles within `check::NEAR_END_M` of a deck end line steeper than a rock face where the terrain is not +/// (`check::deck_ends`), measured on the revision 16 fixture with line water: the rock-face fall of an outline edge's +/// cone past its end's normal at a paved end's corner, which the round slope end bares, and a water bank at its +/// steepest beside a deck end: the count must not grow. +const STEEP_NEAR_END_MAX: usize = 52; + +#[test] +fn every_fixture_cell_meshes_validly_with_the_records_labels_and_agrees_with_its_neighbours() { + let dir = default_dir(); + let mut fixture = Fixture::open(&dir); + let rules = Rules::embedded(); + let cells: Vec = (fixture.cells().into_iter()) + .filter(|k| k.feature_tiles().iter().all(|&(c, r)| fixture::feature_tile(&dir, c, r).is_some())) + .collect(); + let built = fixture.map(&cells, |key, input| { + let graph = graph::build(key, &input, &rules.sections); + let built = records::build(&graph, &input, rules, key, 0, true); + (key, Rim::of(&built.faces), built.faces, built.near.words, input.terrain) + }); + let rims: BTreeMap = built.iter().map(|b| (b.0, b.1.clone())).collect(); + let mut faults = Vec::new(); + let mut meshes = BTreeMap::new(); + let mut labels = check::Labels::default(); + let (mut end_faces, mut misses, mut steeps) = (0, 0, 0); + for (key, _, plan, words, terrain) in &built { + let around: Vec = (-1..=1i64) + .flat_map(|dy| { + (-1..=1i64).map(move |dx| CellKey { x: (key.x as i64 + dx) as u32, y: (key.y as i64 + dy) as u32 }) + }) + .filter_map(|k| rims.get(&k).cloned()) + .collect(); + let mesh = match mesh_cell(plan, words, &Reads::of(plan, &around), &mut || 0.0) { + Ok(m) => m, + Err(e) => { + faults.push(format!("{key:?}: {e:?}")); + continue; + } + }; + let s = &mesh.stats; + if s.outside_d + s.unlabelled + s.split_edges > 0 { + faults.push(format!("{key:?}: {s:?}")); + } + faults.extend(check::validity(&mesh).into_iter().map(|f| format!("{key:?}: {f}"))); + let (stray, missed, steep) = check::deck_ends(&mesh, words, terrain, *key); + end_faces += mesh.end_faces; + faults.extend(stray.into_iter().map(|f| format!("{key:?}: {f}"))); + (misses, steeps) = (misses + missed.len(), steeps + steep.len()); + let l = check::labels(&mesh, words); + labels.sharp_wrong += l.sharp_wrong; + labels.ground_wrong += l.ground_wrong; + labels.ground_other += l.ground_other; + labels.first.extend(l.first.into_iter().map(|f| format!("{key:?} {f}"))); + meshes.insert(*key, (mesh, words, terrain)); + } + let cell = |k: CellKey| { + let (mesh, words, terrain) = &meshes[&k]; + check::Cell { key: k, mesh, words, terrain } + }; + let (mut lines, mut sub_mm) = (0, 0); + for &key in meshes.keys() { + for (east, other) in [(true, CellKey { x: key.x + 1, y: key.y }), (false, CellKey { x: key.x, y: key.y + 1 })] { + if meshes.contains_key(&other) { + let (f, s) = check::border(&cell(key), &cell(other), east); + (lines, sub_mm) = (lines + 1, sub_mm + s); + faults.extend(f); + } + } + } + println!( + "{} cells meshed, {lines} shared lines ({sub_mm} points with a sub-mm step); labels {labels:?}; {end_faces} end face slots, {misses} slots on an end line not end faces, {steeps} steep ground triangles near an end line", + meshes.len() + ); + assert!(end_faces > 0, "no end face in the fixture"); + assert!(steeps <= STEEP_NEAR_END_MAX, "{steeps} steep ground triangles near a deck end line"); + assert!(faults.is_empty(), "{} faults: {:#?}", faults.len(), &faults[..faults.len().min(20)]); + assert_eq!(labels.ground_wrong, 0, "{:#?}", labels.first); +} diff --git a/host/obc-ground-plan/tests/records.rs b/host/obc-ground-plan/tests/records.rs new file mode 100644 index 0000000000..0957876525 --- /dev/null +++ b/host/obc-ground-plan/tests/records.rs @@ -0,0 +1,108 @@ +//! The records over every cell of the TrailView fixture: each sampled point gets its face's label, +//! the far level keeps every label but the band layers' and water's, the far block holds the near way lines +//! in reach and is the far-only build's, two neighbouring cells give one label on their shared line, an +//! outline end with a turn has one edge going on at its paved height, and a second build gives the same words. + +#[path = "fixture/mod.rs"] +mod fixture; + +use std::collections::BTreeMap; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::faces::check::feature_names; +use obc_ground_plan::faces::records; +use obc_ground_plan::faces::records::check::{ + agreement, border, far_agreement, far_matches_near, outline_border, outline_turns, Overlay, +}; +use obc_ground_plan::faces::Rules; +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::graph::{self, WayGraph}; + +/// Sample points per bin side. +const SAMPLES: i32 = 5; +/// A miss this near an edge between two labels is the slice's precision: `MERGE` (4 units) and +/// the snap rounding of the overlay. +const EDGE_UNITS: f64 = 8.0; + +/// A cell's near records, graph and feature names. +type Built = (Vec, WayGraph, Vec<[u32; 3]>); + +#[test] +fn every_fixture_cell_gives_its_points_the_faces_labels_alike_near_far_and_across_borders() { + let dir = default_dir(); + let mut fixture = Fixture::open(&dir); + let rules = Rules::embedded(); + let cells: Vec = (fixture.cells().into_iter()) + .filter(|k| k.feature_tiles().iter().all(|&(c, r)| fixture::feature_tile(&dir, c, r).is_some())) + .collect(); + assert!(cells.len() > 100, "{} cells", cells.len()); + let built = fixture.map(&cells, |key, input| { + let graph = graph::build(key, &input, &rules.sections); + let built = records::build(&graph, &input, rules, key, 0, true); + let (near, far, plan) = (built.near.words, built.far_records.words, built.faces); + // The viewer's cell-only pass gives the records' faces. + let alone = obc_ground_plan::faces::build(&graph, &input, rules, key, 0, true); + let same = alone.vertices == plan.vertices && alone.faces == plan.faces && alone.edges == plan.edges; + let a = agreement(&near, &plan, &Overlay::new(&graph, &input, rules, key, true), SAMPLES, EDGE_UNITS); + let f = far_agreement(&near, &far, SAMPLES); + let (mut lines, counts) = match &built.far_block { + Ok(block) => far_matches_near(&near, block, key), + Err(e) => (vec![e.clone()], BTreeMap::new()), + }; + if records::far_block(&graph, &input, rules, key) != built.far_block { + lines.push("the far-only build's far block differs".into()); + } + let names = feature_names(&input); + (key, near, graph, names, a, f, same, (lines, counts)) + }); + let (mut points, mut edge, mut arc, mut patch, mut faults) = (0, 0, 0, 0, Vec::new()); + let mut far = [0u64; 2]; + let mut blocks: BTreeMap<&str, usize> = BTreeMap::new(); + let mut cells_of: BTreeMap = BTreeMap::new(); + for (key, near, graph, names, a, f, same, (lines, counts)) in built { + if !same { + faults.push(format!("{key:?}: faces::build differs from the records' faces")); + } + faults.extend(lines.iter().map(|l| format!("{key:?} far block: {l}"))); + faults.extend(outline_turns(&near).iter().map(|l| format!("{key:?} outline {l}"))); + counts.into_iter().for_each(|(case, n)| *blocks.entry(case).or_default() += n); + (points, edge, arc, patch) = (points + a.points, edge + a.edge, arc + a.arc, patch + a.patch); + faults + .extend(a.area.iter().map(|m| format!("{key:?} at {:?}: face {:?}, records {:?}", m.q, m.face, m.records))); + far = [far[0] + f[0], far[1] + f[1]]; + cells_of.insert(key, (near, graph, names)); + } + println!("{points} points: {edge} near an edge, {arc} on an arc, {patch} by a patch rule; far {far:?}"); + println!("far blocks: {blocks:?}"); + let (mut borders, mut outline, mut past) = ((0, 0, 0), 0, Vec::new()); + for (&key, a) in &cells_of { + for (east, other) in [(true, CellKey { x: key.x + 1, y: key.y }), (false, CellKey { x: key.x, y: key.y + 1 })] { + let Some(b) = cells_of.get(&other) else { continue }; + let (n, blend, differ) = border((&a.0, &a.1, &a.2), (&b.0, &b.1, &b.2), east, 64); + borders = (borders.0 + 1, borders.1 + n, borders.2 + blend); + faults.extend(differ.iter().map(|d| format!("{key:?}|{other:?} at {}: {} | {}", d.0, d.1, d.2))); + let (n, [near, far]) = outline_border((&a.0, key), (&b.0, other)); + outline += n; + faults.extend(near.iter().map(|d| format!("{key:?}|{other:?} outline edge {d}"))); + past.extend(far); + } + } + println!("{} borders, {} points, {} with a blend edge near", borders.0, borders.1, borders.2); + // Past MARGIN_M the paved field at an outline edge's end is the neighbour's own only as far as this + // shows (`records::outline_m`). + println!( + "{outline} outline edges near a shared line, {} differ past MARGIN_M: {:?}", + past.len(), + &past[..past.len().min(3)] + ); + let again: Vec = cells.iter().step_by(17).copied().collect(); + let differ = fixture.map(&again, |key, input| { + let graph = graph::build(key, &input, &rules.sections); + (records::build(&graph, &input, rules, key, 0, true).near.words != cells_of[&key].0) + .then(|| format!("{key:?}: a second build differs")) + }); + faults.extend(differ.into_iter().flatten()); + assert_eq!(far[1], 0, "far labels differ on {} of {} points", far[1], far[0]); + assert!(edge * 1000 < points, "{edge} of {points} points near an edge"); + assert!(faults.is_empty(), "{} faults: {:?}", faults.len(), &faults[..faults.len().min(8)]); +} diff --git a/host/obc-ground-plan/tests/storeys.rs b/host/obc-ground-plan/tests/storeys.rs new file mode 100644 index 0000000000..a372833ceb --- /dev/null +++ b/host/obc-ground-plan/tests/storeys.rs @@ -0,0 +1,416 @@ +//! The storeys over the ground over every cell of the TrailView fixture: storey 0 reads the same with them, each +//! storey is a planar partition, each shell part closes, no parapet or railing stands in a paved face of its +//! storey or in a way of storey 0, no slot of a top is a wall between two deck ways, no bar stands on two decks, no +//! edge stands across the +//! mouth of a way that goes on at another level, something goes on past every open piece, a stub and its deck share +//! their points and heights on their end line, and two neighbouring cells give a storey the same corners and +//! heights on their shared line. +#![cfg(feature = "storeys")] + +#[path = "fixture/mod.rs"] +mod fixture; + +use std::collections::BTreeMap; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::cell::{build_request, build_storeys, CellBuild}; +use obc_ground_plan::faces::check::partition; +use obc_ground_plan::faces::heights::height_at; +use obc_ground_plan::faces::records::{self, find}; +use obc_ground_plan::faces::{window, EdgeKind, Rules, Surface}; +use obc_ground_plan::frame::{metres_per_unit, CellKey, CELL_UNITS}; +use obc_ground_plan::graph::Family; +use obc_ground_plan::mesh::shell::{border, closure, mesh_storeys, on_paved, StoreyMesh}; +use obc_ground_plan::mesh::{mesh_cell, CellMesh, Reads, Rim, NO_LABEL}; +use obc_ground_plan::tile::TileCache; + +/// Points per side of the grid at which storey 0 must read the same with the storeys' records. +const GRID: i32 = 32; +/// The probes of what lies past an open piece stand this far to each side of its middle (metres). +const PROBE_M: f64 = 0.3; +/// Storey 0 or another storey goes on past an open piece within this of its top's height (metres). +const GOES_ON_M: f64 = 0.1; +/// Open pieces with water or a bank on both sides (a deck's end whose stub begins past the bank), measured on the +/// fixture at the junction rule's build: the count must not grow. +const OPEN_MAX: usize = 24; + +/// The storey of label l's line: 0 for none and for a line of storey 0. +fn storey_of(w: &[u32], l: u32) -> i8 { + let line = records::label(w, l)[2]; + let f = if line == u32::MAX { 0 } else { w[w[6] as usize + records::LINE * line as usize + 1] }; + if f & records::STOREY != 0 { + (f >> records::LEG_SHIFT) as i8 + } else { + 0 + } +} + +/// The height of a storey mesh's top at its corners at point p, by their label's storey. +fn tops_at(m: &StoreyMesh, w: &[u32], p: [i32; 2]) -> Vec<(i8, f64)> { + (0..m.corners.len()) + .map(|k| m.corner(k)) + .filter(|&(q, l, off)| q == p && off == 0.0 && l != NO_LABEL) + .map(|(_, l, _)| (storey_of(w, l), height_at(w, [f64::from(p[0]), f64::from(p[1])], Some(l), f64::NAN).h)) + .collect() +} + +/// The open pieces off the cell lines past which nothing goes on: at neither side of the piece's middle does storey +/// 0 hold a paved face or shoulder within `GOES_ON_M` of the top (its records), or a stub's verge or slope, and at its +/// ends no top of another storey lies within `GOES_ON_M`. +fn open_without_ground(key: CellKey, m: &StoreyMesh, w: &[u32]) -> Vec { + let c = CELL_UNITS as i32; + let mpu = metres_per_unit(key.origin().y + CELL_UNITS / 2); + let on_cell_line = |[a, b]: &[[i32; 2]; 2]| (0..2).any(|k| a[k] == b[k] && (a[k] == 0 || a[k] == c)); + let mut out = Vec::new(); + for piece in m.open.iter().filter(|p| !on_cell_line(p)) { + let [a, b] = *piece; + let (ta, tb) = (tops_at(m, w, a), tops_at(m, w, b)); + let Some(&(storey, za)) = ta.iter().find(|t| t.0 > 0) else { continue }; + let zb = tb.iter().find(|t| t.0 == storey).map_or(za, |t| t.1); + let mid = [f64::from(a[0] + b[0]) / 2.0, f64::from(a[1] + b[1]) / 2.0]; + let d = [f64::from(b[0] - a[0]), f64::from(b[1] - a[1])]; + let len = libm::hypot(d[0], d[1]).max(1e-9); + let n = [-d[1] / len * PROBE_M / mpu, d[0] / len * PROBE_M / mpu]; + // A paved face or shoulder of storey 0 at the top's height, or its verge or slope (the stub's side, under a + // deck's band); no water, bank or bare terrain. + let z = (za + zb) / 2.0; + let ground = [1.0, -1.0].iter().any(|&side| { + let q = [mid[0] + side * n[0], mid[1] + side * n[1]]; + find(w, q).is_some_and(|g| { + let s = records::label(w, g)[0] & 0xff; + let paved = [Surface::Carriageway, Surface::Shoulder, Surface::RailBed, Surface::Crossing]; + let side = [Surface::Verge, Surface::Slope]; + (paved.iter().any(|&x| x as u32 == s) && (height_at(w, q, Some(g), f64::NAN).h - z).abs() <= GOES_ON_M) + || side.iter().any(|&x| x as u32 == s) + }) + }); + let other = |t: &[(i8, f64)], z: f64| t.iter().any(|&(k, h)| k != storey && (h - z).abs() <= GOES_ON_M); + if !ground && !(other(&ta, za) && other(&tb, zb)) { + out.push(format!("{key:?}: past the open piece {piece:?} of storey {storey} goes on nothing")); + } + } + out +} + +/// An edge face, parapet, railing or post of a storey stands in a paved face of storey 0 where that face lies within +/// this of the deck's top under it (metres): a parapet's height. +const STAND_M: f64 = 1.0; +/// Edge triangles over a stub where it meets its deck at a joint with a bend (the deck's end square to its own way, +/// the stub's to its), and over another way's ground stretch beside a deck (their strokes overlap): measured on the +/// fixture at the junction rule's build. The B6 seams and GP12.8 own them; the counts must not grow. +const JOINT_MAX: usize = 25; +const BESIDE_MAX: usize = 235; + +/// The edge faces, parapets, railings and posts of the storeys that stand in a carriageway, rail bed or crossing of +/// storey 0 (its records): a triangle's middle over such a face within `STAND_M` of its deck's top there. Returns +/// those on a way that meets the deck at a junction (none: a deck ends on its mouth's line there, `ground_junctions`), +/// and the counts of those on a stub at its joint and on a way that does not meet the deck. +fn edges_on_ground_ways(key: CellKey, m: &StoreyMesh, b: &CellBuild) -> (Vec, usize, usize) { + let (g, w) = (&b.graph, &b.records); + let paved = |l: u32| { + let s = records::label(w, l)[0] & 0xff; + [Surface::Carriageway, Surface::RailBed, Surface::Crossing].iter().any(|&x| x as u32 == s) + }; + let way = |l: u32| { + let line = records::label(w, l)[2]; + (line != u32::MAX).then(|| w[w[6] as usize + records::LINE * line as usize]) + }; + // Whether ways a and c meet at a junction (three arms or more), and at a joint. + let both = |arms: &[obc_ground_plan::graph::Arm], a: u32, c: u32| { + arms.iter().any(|x| x.way == a) && arms.iter().any(|x| x.way == c) + }; + let junction = |a: u32, c: u32| g.junctions.iter().any(|j| both(&j.arms, a, c)); + let joint = |a: u32, c: u32| g.joints.iter().any(|j| both(&j.arms, a, c)); + let (mut out, mut joints, mut beside) = (Vec::new(), 0, 0); + for k in 2..6 { + for t in m.part(k) { + let c = m.triangles[t].map(|i| m.corner(i as usize)); + let Some(&(_, deck, _)) = c.iter().find(|x| storey_of(w, x.1) > 0) else { continue }; + let q = [0, 1].map(|i| c.iter().map(|x| f64::from(x.0[i])).sum::() / 3.0); + let top = height_at(w, q, Some(deck), f64::NAN).h; + let Some(f) = find(w, q).filter(|&f| paved(f)) else { continue }; + if (height_at(w, q, Some(f), f64::NAN).h - top).abs() >= STAND_M { + continue; + } + match way(f).zip(way(deck)) { + Some((a, d)) if junction(a, d) => out.push(format!( + "{key:?}: a {} triangle at {q:.0?} stands in the mouth of way {a}", + shell_part(m, t) + )), + Some((a, d)) if joint(a, d) => joints += 1, + _ => beside += 1, + } + } + } + (out, joints, beside) +} + +/// A parapet's, railing's or post's corners on two labels differ in height by at most this (metres): a bar stands +/// on one deck. +const BAR_STEP_M: f64 = 0.05; + +/// The parapet, railing and post triangles whose corners stand on two labels of the storeys over the ground that lie +/// more than `BAR_STEP_M` apart. (A deck's end takes storey 0's labels: `stub_meets_deck`.) +fn bars_across_decks(key: CellKey, m: &StoreyMesh, w: &[u32]) -> Vec { + let mut out = Vec::new(); + for k in 3..6 { + for t in m.part(k) { + let c = m.triangles[t].map(|i| m.corner(i as usize)); + for (i, j) in [(0, 1), (1, 2), (0, 2)] { + let (p, la, lb) = (c[i].0, c[i].1, c[j].1); + if la == lb || storey_of(w, la) == 0 || storey_of(w, lb) == 0 { + continue; + } + let q = [f64::from(p[0]), f64::from(p[1])]; + let h = |l: u32| height_at(w, q, Some(l), f64::NAN).h; + if (h(la) - h(lb)).abs() > BAR_STEP_M { + out.push(format!( + "{key:?}: a {} triangle at {p:?} stands on labels {la} and {lb}", + shell_part(m, t) + )); + } + } + } + } + out +} + +/// Where a stub meets its deck (an end line of storey 0's plan, `EdgeKind::DeckEdge`), storey 0's cell mesh and the +/// paved part of the deck's top have the same points, and their heights there differ by less than `SEAM_M`: no paved +/// end point of a top on it is missing from the cell mesh or stands apart from it, and no cell mesh point on it lies +/// inside a paved open piece's span. +const SEAM_M: f64 = 0.001; +/// The seams of `stub_meets_deck`, measured on the fixture at the junction rule's build: a deck's end at a bend of its way +/// (its stub leaves at an angle past `records::FLAT_TURN_DEG`), a stub whose face at the end is no paved face or +/// shoulder, and stub points inside a deck's end piece. The count must not grow. +const SEAMS_MAX: usize = 14; + +fn stub_meets_deck(key: CellKey, ground: &CellMesh, m: &StoreyMesh, b: &CellBuild) -> Vec { + let w = &b.records; + let plan = &b.faces; + let ends: Vec<[[f64; 2]; 2]> = (plan.edges.iter().filter(|e| e.kind == EdgeKind::DeckEdge)) + .map(|e| [plan.vertices[e.a as usize], plan.vertices[e.b as usize]].map(|v| v.map(f64::from))) + .collect(); + // On an end line: within one unit of it, between its ends. + let on = |p: [i32; 2]| { + let q = p.map(f64::from); + ends.iter().any(|[a, c]| { + let d = [c[0] - a[0], c[1] - a[1]]; + let l2 = (d[0] * d[0] + d[1] * d[1]).max(1e-9); + let t = ((q[0] - a[0]) * d[0] + (q[1] - a[1]) * d[1]) / l2; + let off = ((q[0] - a[0]) * d[1] - (q[1] - a[1]) * d[0]).abs() / l2.sqrt(); + (0.0..=1.0).contains(&t) && off <= 1.0 + }) + }; + // Per point, the heights of its corners: the stub's face and those beside it on the line. + let mut cell: BTreeMap<[i32; 2], Vec> = BTreeMap::new(); + for k in 0..ground.corners.len() { + let (p, l, terrain) = ground.corner(k); + if !terrain && l != NO_LABEL && on(p) { + cell.entry(p).or_default().push(height_at(w, p.map(f64::from), Some(l), f64::NAN).h); + } + } + // The heights of a top's paved corners (a carriageway, rail bed, crossing or shoulder) at a point. + let paved_tops = |p: [i32; 2]| -> Vec { + (0..m.corners.len()) + .map(|k| m.corner(k)) + .filter(|&(q, l, off)| q == p && off == 0.0 && l != NO_LABEL) + .filter(|&(_, l, _)| { + let s = records::label(w, l)[0] & 0xff; + [Surface::Carriageway, Surface::Shoulder, Surface::RailBed, Surface::Crossing] + .iter() + .any(|&x| x as u32 == s) + }) + .map(|(_, l, _)| height_at(w, p.map(f64::from), Some(l), f64::NAN).h) + .collect() + }; + let mut out = Vec::new(); + let mut spans: Vec<[[i32; 2]; 2]> = Vec::new(); + for &[a, c] in m.open.iter().filter(|[a, c]| on(*a) && on(*c)) { + let (ta, tc) = (paved_tops(a), paved_tops(c)); + if !ta.is_empty() && !tc.is_empty() { + spans.push([a, c]); + } + for (p, tops) in [(a, ta), (c, tc)] { + match cell.get(&p) { + _ if tops.is_empty() => {} + None => out.push(format!("{key:?}: the deck's end point {p:?} is no point of storey 0's mesh")), + Some(h) if !tops.iter().any(|t| h.iter().any(|h| (h - t).abs() < SEAM_M)) => { + out.push(format!("{key:?}: at {p:?} storey 0 stands at {h:.4?} m, the deck at {tops:.4?} m")) + } + _ => {} + } + } + } + for &p in cell.keys() { + let inside = spans.iter().any(|[a, c]| { + let between = |i: usize| (a[i].min(c[i])..=a[i].max(c[i])).contains(&p[i]); + p != *a && p != *c && between(0) && between(1) + }); + if inside { + out.push(format!("{key:?}: storey 0's point {p:?} on an end line is no point of the deck's paved end")); + } + } + out +} + +/// A slot of a top between two deck ways stands no higher than a parapet and the cross-slope of a deck: higher, +/// each deck has its own edge (`mesh::shell`). +const DECK_STEP_M: f64 = 1.5; + +/// The slots of the tops between two deck ways higher than `DECK_STEP_M`, by the crate's height function. +fn walls_between_decks(key: CellKey, m: &StoreyMesh, b: &CellBuild) -> Vec { + let w = &b.records; + let deck = |l: u32| { + let line = records::label(w, l)[2]; + let way = (line != u32::MAX).then(|| w[w[6] as usize + records::LINE * line as usize]); + way.filter(|&x| b.storeys.way(x).is_some()) + }; + let h = |k: u32| { + let (p, l, _) = m.corner(k as usize); + height_at(w, [f64::from(p[0]), f64::from(p[1])], Some(l), 500.0).h + }; + (m.slots[..m.top_slots as usize].iter()) + .filter(|s| deck(m.corner(s[0] as usize).1).zip(deck(m.corner(s[3] as usize).1)).is_some_and(|(a, c)| a != c)) + .filter(|s| (h(s[0]) - h(s[3])).abs().max((h(s[1]) - h(s[2])).abs()) > DECK_STEP_M) + .map(|s| format!("{key:?}: the slot {s:?} is a wall between two deck ways")) + .collect() +} + +/// The edge faces, parapets, railings and posts of a storey across the mouth of an arm that goes on at another +/// level, at a junction or joint of one of its deck ways: the arm's centre line from the point out to its half-width +/// and `edge_band_m`. A deck ends open there; a corner round would stand across the arm. +fn edges_in_mouths(key: CellKey, m: &StoreyMesh, b: &CellBuild, band_m: f64) -> Vec { + let (g, w) = (&b.graph, &b.records); + let mpu = metres_per_unit(key.origin().y + CELL_UNITS / 2); + let storey = |x: u32| b.storeys.way(x).map_or(0, |d| d.storey); + let lines = || w[w[6] as usize..w[7] as usize].chunks(records::LINE); + let half_m = |x: u32| { + let ground = |l: &&[u32]| l[0] == x && l[1] & (records::STOREY | records::CEILING) == 0; + lines().find(ground).map(|l| f64::from(f32::from_bits(l[11]))) + }; + let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); + let meets = |p: [f64; 2], q: [f64; 2], a: [f64; 2], b: [f64; 2]| { + let (d1, d2) = (cross(p, q, a), cross(p, q, b)); + let (d3, d4) = (cross(a, b, p), cross(a, b, q)); + d1 * d2 <= 0.0 && d3 * d4 <= 0.0 && (d1 != 0.0 || d2 != 0.0) + }; + let shell: Vec = (2..6).flat_map(|k| m.part(k)).collect(); + let mut out = Vec::new(); + let points = g.junctions.iter().map(|j| (j.pos, &j.arms[..])).chain(g.joints.iter().map(|j| (j.pos, &j.arms[..]))); + for (pos, arms) in points { + for deck in arms.iter().map(|a| storey(a.way)).filter(|&k| k > 0) { + for a in arms.iter().filter(|a| g.ways[a.way as usize].family != Family::Water && storey(a.way) != deck) { + let Some(half) = half_m(a.way) else { continue }; + let len = libm::hypot(a.heading[0], a.heading[1]).max(1e-9); + let reach = (half + band_m) / mpu / len; + let p = pos.map(f64::from); + let q = [p[0] + a.heading[0] * reach, p[1] + a.heading[1] * reach]; + for &t in &shell { + let tri = m.triangles[t]; + let c = tri.map(|k| m.corner(k as usize).0.map(f64::from)); + if storey_of(w, m.corner(tri[0] as usize).1) == deck + && (0..3).any(|i| meets(p, q, c[i], c[(i + 1) % 3])) + { + let of: Vec<(u32, i8)> = arms.iter().map(|x| (x.way, storey(x.way))).collect(); + out.push(format!( + "{key:?}: a {} triangle of storey {deck} stands across way {} at {pos:?} (arms, storeys: {of:?})", + shell_part(m, t), + a.way + )); + } + } + } + } + } + out +} + +fn shell_part(m: &StoreyMesh, t: usize) -> &'static str { + (0..obc_ground_plan::mesh::shell::PARTS.len()) + .find(|&k| m.part(k).contains(&t)) + .map_or("?", |k| obc_ground_plan::mesh::shell::PARTS[k]) +} + +#[test] +fn the_storeys_close_stand_on_their_sheets_meet_their_neighbours_and_leave_storey_0_as_it_was() { + let mut fix = Fixture::open(&default_dir()); + let rules = Rules::embedded(); + let mut cache = TileCache::new(16); + let mut faults = Vec::new(); + let mut built: BTreeMap = BTreeMap::new(); + let (mut torn, mut seams, mut joints, mut beside, mut open_ends) = (0, Vec::new(), 0, 0, Vec::new()); + for key in fix.cells() { + let without = build_request(fix.request(key), &mut cache, rules, &mut || 0.0).unwrap(); + let with = build_storeys(fix.request(key), &mut cache, rules, &mut || 0.0).unwrap(); + assert_eq!(without.faces, with.faces, "{key:?}: storey 0's faces"); + assert_eq!(without.far, with.far, "{key:?}: the far block"); + if with.storeys.plans.is_empty() { + assert_eq!(without.records, with.records, "{key:?}: a cell with no deck has the records of storey 0 alone"); + continue; + } + // Storey 0 reads the same label and height at a grid of points. + let c = f64::from(CELL_UNITS as i32); + for j in 0..GRID { + for i in 0..GRID { + let q = [(f64::from(i) + 0.37) * c / f64::from(GRID), (f64::from(j) + 0.61) * c / f64::from(GRID)]; + let (a, b) = (find(&without.records, q), find(&with.records, q)); + let (ha, hb) = (height_at(&without.records, q, a, 500.0).h, height_at(&with.records, q, b, 500.0).h); + if a != b || ha.to_bits() != hb.to_bits() { + faults.push(format!( + "{key:?} at {q:?}: storey 0 reads {a:?} {ha} without and {b:?} {hb} with storeys" + )); + } + } + } + for plan in &with.storeys.plans { + faults.extend( + partition(plan, window(key, 0.0)).into_iter().map(|f| format!("{key:?} storey {}: {f:?}", plan.level)), + ); + } + let mesh = mesh_storeys(key, &with.storeys, &with.records, &rules.structures).unwrap(); + assert_eq!(mesh.stats.unlabelled, 0, "{key:?}: a sheet face has no label"); + faults.extend(closure(&mesh)); + faults.extend(on_paved(&mesh, &with.storeys, &with.records)); + faults.extend(walls_between_decks(key, &mesh, &with)); + faults.extend(edges_in_mouths(key, &mesh, &with, rules.structures.edge_band_m)); + open_ends.extend(open_without_ground(key, &mesh, &with.records)); + faults.extend(bars_across_decks(key, &mesh, &with.records)); + let (in_mouths, at_joints, by) = edges_on_ground_ways(key, &mesh, &with); + faults.extend(in_mouths); + (joints, beside) = (joints + at_joints, beside + by); + let rim = Rim::of(&with.faces); + match mesh_cell(&with.faces, &with.records, &Reads::of(&with.faces, &[rim]), &mut || 0.0) { + Ok(ground) => seams.extend(stub_meets_deck(key, &ground, &mesh, &with)), + Err(e) => faults.push(format!("{key:?}: storey 0's mesh: {e:?}")), + } + torn += mesh.stats.torn; + built.insert(key, (with, mesh)); + } + for (&key, (b, m)) in &built { + for (east, other) in [(true, CellKey { x: key.x + 1, y: key.y }), (false, CellKey { x: key.x, y: key.y + 1 })] { + if let Some((ob, om)) = built.get(&other) { + faults.extend(border((m, &b.records), (om, &ob.records), east)); + } + } + } + let triangles: u32 = built.values().map(|(_, m)| m.triangles.len() as u32).sum(); + for f in &faults { + println!("FAULT {f}"); + } + seams.sort(); + seams.dedup(); + println!( + "{} cells with storeys, {triangles} storey triangles, {torn} torn pieces, {} faults", + built.len(), + faults.len() + ); + println!("{} seams where a stub meets its deck: {seams:#?}", seams.len()); + println!("{joints} edge triangles on a stub at its joint, {beside} on a ground way beside a deck"); + println!("{} open pieces with nothing past them: {open_ends:#?}", open_ends.len()); + assert!(open_ends.len() <= OPEN_MAX, "{} open pieces with nothing past them", open_ends.len()); + assert!(joints <= JOINT_MAX && beside <= BESIDE_MAX, "{joints} and {beside} edge triangles on ground ways"); + assert!(seams.len() <= SEAMS_MAX, "{} seams where a stub meets its deck, more than {SEAMS_MAX}", seams.len()); + assert!(built.len() > 10, "the fixture's decks"); + assert!(faults.is_empty(), "{} faults: {:#?}", faults.len(), &faults[..faults.len().min(20)]); +} diff --git a/host/obc-ground-plan/tests/transport.rs b/host/obc-ground-plan/tests/transport.rs new file mode 100644 index 0000000000..251e70d57a --- /dev/null +++ b/host/obc-ground-plan/tests/transport.rs @@ -0,0 +1,304 @@ +//! The request codec, the flat plan and its digest over a cell of the TrailView fixture. + +#[path = "fixture/mod.rs"] +mod fixture; + +use fixture::{default_dir, Fixture}; +use obc_ground_plan::cell::{build_cell, build_cell_with, cell_graph, STAGES}; +use obc_ground_plan::faces::{records, Rules}; +use obc_ground_plan::faces::{CornerArc, Edge, EdgeKind, Face, FacePlan, FaceStats, HeightRule, Owner, Surface}; +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::tile::TileCache; +use obc_ground_plan::transport::{ + vocabulary, FaceWords, Flat, Request, CORNER_WORDS, CROSSING_WORDS, EDGE_WORDS, FACE_WORDS, POINT_WORDS, + RING_WORDS, WAY_WORDS, +}; + +/// A town cell with junctions and two terrain levels. +const CELL: CellKey = CellKey { x: 34296, y: 23098 }; + +fn request() -> Request { + Fixture::open(&default_dir()).request(CELL) +} + +#[test] +fn a_request_round_trips_and_its_bytes_do_not_depend_on_the_order_of_its_inputs() { + let request = request(); + assert!(request.pages.len() >= 2 && !request.tiles.is_empty()); + let bytes = request.encode(); + let mut shuffled = request.clone(); + shuffled.pages.reverse(); + shuffled.tiles.reverse(); + assert_eq!(shuffled.encode(), bytes); + let decoded = Request::decode(&bytes).unwrap(); + assert_eq!(decoded.encode(), bytes); + assert_eq!(decoded.pages.len(), request.pages.len()); +} + +#[test] +fn decode_refuses_every_malformed_request() { + let request = request(); + let bytes = request.encode(); + // Each case names a word of the error that it must give. + let refused = |bytes: &[u8], what: &str, word: &str| { + let error = Request::decode(bytes).expect_err(what); + assert!(error.contains(word), "{what}: {error}"); + }; + let mut magic = bytes.clone(); + magic[0] = b'X'; + refused(&magic, "a wrong magic", "OGPR"); + refused(&bytes[..bytes.len() - 2], "a truncation in the codes of a page", "fewer than"); + refused(&bytes[..10], "a truncation in the head", "inside a field"); + refused(&[bytes.as_slice(), &[0; 4]].concat(), "trailing bytes", "after its last page"); + let raw = |r: &Request| { + let mut one = r.clone(); + one.pages.truncate(1); + one.tiles.truncate(1); + one + }; + let mut repeated = raw(&request); + repeated.pages.push(repeated.pages[0].clone()); + refused(&repeated.encode(), "a repeated page", "repeats"); + let mut far = raw(&request); + far.pages[0].x += 40; + refused(&far.encode(), "a page that the cell does not want", "reads no page"); + let mut tile = raw(&request); + tile.tiles[0].column += 5; + refused(&tile.encode(), "a tile that the cell does not read", "reads no tile"); + let mut tiles = raw(&request); + tiles.tiles.push(tiles.tiles[0].clone()); + refused(&tiles.encode(), "a repeated tile", "repeats"); + let mut padded = raw(&request); + let length = padded.tiles[0].bytes.len() / 4 * 4 - 1; + padded.tiles[0].bytes.truncate(length); + let mut bytes = padded.encode(); + let end = 4 + 8 + 4 + 12 + padded.tiles[0].bytes.len(); + bytes[end] = 1; + refused(&bytes, "padding that is not zero", "padding"); + let mut garbled = raw(&request); + garbled.tiles[0].bytes.truncate(7); + assert!(build_cell(&garbled.encode(), Rules::embedded(), &mut || 0.0).is_err(), "a tile that does not decode"); +} + +#[test] +fn the_flat_plan_indexes_its_samples_and_its_digest_ignores_the_clock() { + let bytes = request().encode(); + let mut ticks = 0.0; + let mut clock = || { + ticks += 7.5; + ticks + }; + let (a, b) = ( + build_cell(&bytes, Rules::embedded(), &mut || 0.0).unwrap(), + build_cell(&bytes, Rules::embedded(), &mut clock).unwrap(), + ); + assert_eq!(a.times, [0.0; STAGES.len()]); + assert_eq!(b.times, [7.5; STAGES.len()]); + let flat = Flat::of(&a); + let digest = flat.digest(&a).unwrap(); + assert_eq!(digest, Flat::of(&b).digest(&b).unwrap()); + assert_eq!(digest.len(), 16); + let samples = flat.samples.len() / 2; + assert_eq!(samples, a.graph.samples.len()); + assert_eq!(flat.ways.len(), WAY_WORDS * a.graph.ways.len()); + for way in flat.ways.chunks(WAY_WORDS) { + assert!(way[5] >= 2 && (way[4] + way[5]) as usize <= samples); + } + let g = &a.graph; + assert!(!g.junctions.is_empty() && !g.crossings.is_empty()); + assert_eq!(flat.points.len(), POINT_WORDS * (g.junctions.len() + g.joints.len() + g.ends.len())); + assert_eq!(flat.crossings.len(), CROSSING_WORDS * g.crossings.len()); + let stats: serde_json::Value = serde_json::from_str(&flat.stats).unwrap(); + assert_eq!(stats["graph"]["junctions"].as_u64(), Some(u64::from(g.stats.junctions))); + assert_eq!(stats["inputs"]["request"].as_str(), a.request.as_deref()); + let f = &flat.faces; + assert!(!a.faces.faces.is_empty()); + assert_eq!(f.faces.len(), FACE_WORDS * a.faces.faces.len()); + let vertices = (f.vertices.len() / 2) as u32; + assert!( + f.ring_vertices.iter().all(|&v| v < vertices) && f.edges.chunks(EDGE_WORDS).all(|e| e[0].max(e[1]) < vertices) + ); + assert_eq!(stats["faces"]["faces"].as_u64(), Some(u64::from(a.faces.stats.faces))); + let mut faces = a.clone(); + faces.faces.vertices[0][0] += 1; + assert_ne!(Flat::of(&faces).digest(&faces).unwrap(), digest, "the digest sees the faces"); + // A changed sample changes the digest. + let mut moved = a.clone(); + moved.graph.samples[0].z_m += 1e-9; + assert_ne!(Flat::of(&moved).digest(&moved).unwrap(), digest); + // A NaN hides its bits in the text: the digest refuses it. + moved.graph.samples[0].z_m = f64::NAN; + assert!(Flat::of(&moved).digest(&moved).unwrap_err().contains("NaN")); +} + +#[test] +fn a_cell_build_gives_the_faces_and_near_records_of_the_whole_records_build_and_so_does_a_parsed_tile() { + let bytes = request().encode(); + let rules = Rules::embedded(); + let cell = build_cell(&bytes, rules, &mut || 0.0).unwrap(); + let input = Request::decode(&bytes).unwrap().input(&mut TileCache::new(1)).unwrap(); + let whole = records::build(&cell_graph(CELL, &input, rules), &input, rules, CELL, 0, true); + assert_eq!(cell.faces, whole.faces); + assert_eq!(cell.records, whole.near.words); + // The second build reads the tiles that the first parsed: a load of one would panic. + let request = Request::decode(&bytes).unwrap(); + let mut tiles = TileCache::new(request.tiles.len()); + for build in 0..2 { + let again = build_cell_with(&bytes, &mut tiles, rules, &mut || 0.0).unwrap(); + assert_eq!((again.faces, again.records), (cell.faces.clone(), cell.records.clone())); + if build == 0 { + for t in &request.tiles { + tiles.tile(t.column, t.row, || panic!("tile {} {} parses again", t.column, t.row)).unwrap(); + } + } + } +} + +#[test] +fn the_vocabulary_names_every_code_with_its_colour() { + let v: serde_json::Value = serde_json::from_str(&vocabulary()).unwrap(); + assert_eq!(v["stages"], serde_json::json!(STAGES)); + let families = v["families"].as_array().unwrap(); + assert_eq!(families.len(), 4); + let colour = |c: &serde_json::Value| c.as_str().is_some_and(|c| c.len() == 7 && c.starts_with('#')); + assert!(families.iter().all(|f| colour(&f["colour"]))); + assert!(v["colours"].as_object().unwrap().values().all(colour)); + assert_eq!(v["crossings"].as_array().unwrap().len(), 9); + let names = |key: &str| { + v[key].as_array().unwrap().iter().map(|e| e["name"].as_str().unwrap().to_string()).collect::>() + }; + assert_eq!(names("surfaces")[Surface::CornerFill as usize], "corner_fill"); + assert_eq!(names("surfaces").len(), Surface::DeckEdge as usize + 1); + assert_eq!(names("edges")[EdgeKind::CellBorder as usize], "cell_border"); + assert_eq!(v["surfaces"][0]["fill"], serde_json::Value::Null, "terrain has no fill"); + assert!(v["edges"].as_array().unwrap().iter().all(|e| colour(&e["colour"]))); +} + +/// The face plan back from its words. +fn plan_of(w: &FaceWords, cell: CellKey) -> FacePlan { + let pairs = |v: &[i32]| v.chunks(2).map(|p| [p[0], p[1]]).collect::>(); + let owner = + |kind: u32, id: u32| [Owner::Terrain, Owner::Way(id), Owner::Junction(id), Owner::Platform(id)][kind as usize]; + let option = |v: u32| (v != u32::MAX).then_some(v); + const SURFACES: [Surface; 9] = [ + Surface::Terrain, + Surface::Slope, + Surface::Carriageway, + Surface::Shoulder, + Surface::Verge, + Surface::CornerFill, + Surface::Crossing, + Surface::RailBed, + Surface::Platform, + ]; + const RULES: [HeightRule; 5] = + [HeightRule::Terrain, HeightRule::Slope, HeightRule::Owner, HeightRule::Blend, HeightRule::KerbOffset]; + const KINDS: [EdgeKind; 7] = [ + EdgeKind::Continuous, + EdgeKind::Kerb, + EdgeKind::Wall, + EdgeKind::Headwall, + EdgeKind::Portal, + EdgeKind::DeckEdge, + EdgeKind::CellBorder, + ]; + let faces = (w.faces.chunks(FACE_WORDS)) + .map(|f| Face { + id: f[0], + owner: owner(f[1], f[2]), + surface: SURFACES[f[3] as usize], + level: f[4] as i32 as i8, + rule: RULES[f[5] as usize], + material: option(f[6]), + crossing: option(f[7]), + rank: f[8] as u8, + inside: f[9] == 1, + reach_m: f32::from_bits(f[10]), + legs: [f[11] as u8, (f[11] >> 8) as u8], + rings: (f[12]..f[12] + f[13]) + .map(|r| { + let r = &w.rings[RING_WORDS * r as usize..][..RING_WORDS]; + w.ring_vertices[r[0] as usize..][..r[1] as usize].to_vec() + }) + .collect(), + }) + .collect(); + let edges = (w.edges.chunks(EDGE_WORDS)) + .map(|e| Edge { a: e[0], b: e[1], left: e[2], right: e[3], kind: KINDS[e[4] as usize], flags: e[5] as u8 }) + .collect(); + let corners = (w.corners.chunks(CORNER_WORDS)) + .map(|c| { + let i = |k: usize| c[k] as i32; + CornerArc { + owner: owner(c[0], c[1]), + centre: [i(2), i(3)], + radius_m: f64::from_bits(u64::from(c[4]) | u64::from(c[5]) << 32), + t_a: [i(6), i(7)], + t_b: [i(8), i(9)], + arc: pairs(&w.corner_points[2 * c[10] as usize..][..2 * c[11] as usize]), + } + }) + .collect(); + let mouths = Vec::new(); + FacePlan { + cell, + level: 0, + vertices: pairs(&w.vertices), + faces, + edges, + corners, + mouths, + stats: FaceStats::default(), + } +} + +#[test] +fn the_face_words_keep_every_field_of_the_plan() { + let cell = CellKey { x: 34288, y: 23104 }; + let face = |id: u32, owner: Owner, surface: Surface, rings: Vec>| Face { + id, + owner, + surface, + level: -1, + rule: HeightRule::Blend, + material: None, + crossing: None, + rank: 3, + inside: false, + reach_m: 0.0, + legs: [0, 0], + rings, + }; + let mut way = face(1, Owner::Way(7), Surface::Carriageway, vec![vec![0, 1, 2, 3], vec![4, 5, 6]]); + (way.material, way.crossing, way.rank, way.inside, way.reach_m, way.level) = (Some(7), Some(9), 0, true, 2.75, 2); + way.legs = [2, 1]; + let plan = FacePlan { + cell, + level: 0, + vertices: vec![[0, 0], [100, 0], [100, 100], [0, 100], [10, 10], [20, 10], [-5, 20]], + faces: vec![ + face(0, Owner::Terrain, Surface::Terrain, vec![vec![0, 1, 2]]), + way, + face(2, Owner::Junction(4), Surface::CornerFill, vec![vec![2, 3, 0]]), + face(3, Owner::Platform(11), Surface::Platform, vec![vec![4, 5, 6]]), + ], + edges: vec![ + Edge { a: 0, b: 1, left: 0, right: u32::MAX, kind: EdgeKind::CellBorder, flags: 0 }, + Edge { a: 1, b: 2, left: 1, right: 2, kind: EdgeKind::Kerb, flags: 7 }, + ], + corners: vec![ + CornerArc { + owner: Owner::Junction(4), + centre: [5, -6], + radius_m: 1.0 / 3.0, + t_a: [1, 2], + t_b: [3, -4], + arc: vec![[2, 3], [3, 3]], + }, + CornerArc { owner: Owner::Way(7), centre: [0, 0], radius_m: 0.0, t_a: [0, 0], t_b: [0, 0], arc: vec![] }, + ], + mouths: Vec::new(), + stats: FaceStats::default(), + }; + assert_eq!(plan_of(&FaceWords::of(&plan), cell), plan); +} diff --git a/host/obc-trailview-features/Cargo.toml b/host/obc-trailview-features/Cargo.toml index f515cc1a8c..e58bff7649 100644 --- a/host/obc-trailview-features/Cargo.toml +++ b/host/obc-trailview-features/Cargo.toml @@ -10,6 +10,11 @@ description = "The TrailView feature tiles of a region: the step planner/trailvi name = "trailview-features" path = "src/main.rs" +# Builds each ground-plan cell of a release or a fixture as the viewer does, and records each failure. +[[bin]] +name = "census" +path = "src/bin/census/main.rs" + [dependencies] # The sparse Cholesky factorization of the road solver's normal equations. faer = { version = "0.24", default-features = false, features = ["std", "sparse-linalg"] } @@ -23,7 +28,10 @@ rusqlite = { workspace = true, features = ["bundled"] } serde_json = { workspace = true, features = ["preserve_order", "float_roundtrip"] } # The request of the step and its function. obc-data = { workspace = true } +# The cross-section rules that the ground plan shares, and the reader of the tiles for the codec tests. +obc-ground-plan = { workspace = true } # The cut of the OSM of a bake. tempfile = { workspace = true } # The water polygons of the sea. zip = { workspace = true, features = ["deflate-flate2"] } + diff --git a/host/obc-trailview-features/README.md b/host/obc-trailview-features/README.md index a7eaac1f65..7203a254d2 100644 --- a/host/obc-trailview-features/README.md +++ b/host/obc-trailview-features/README.md @@ -25,6 +25,52 @@ target/release/trailview-features --osm OSM.pbf --terrain TERRAIN.mbtiles --boun | `OBC_OSMIUM` | The Osmium executable. The default is `osmium` on the path. | | `OBC_DATA_MEMORY_BYTES` | The road jobs that run at once fit in this memory. `obc data` sets it. | +## Census + +`census` builds each zoom-16 cell of a box as the TrailView viewer does: the ground plan of the cell +(`obc-ground-plan`), then its mesh with the rims of its eight neighbours. It reads a local release +of `obc data` (its feature and terrain map packs) or a fixture folder, and it writes nothing into +them. Run it under a memory cap. Each worker process gets its own cap (`--memory`, a user scope of +`systemd-run`): + +```sh +cargo build --locked --release -p obc-trailview-features --bin census +systemd-run --user --scope -p MemoryMax=1G -p MemorySwapMax=0 nice -n 19 target/release/census \ + (--release STORE [--id ID] | --fixture DIR) --out OUT [--workers 3] [--memory 2G|none] [--timeout-s 60] \ + [--grid-m 4] [--strip 10] [--rows 48] [--limit N] [--cells X/Y,...] [--bounds W,S,E,N] [--min-available-gb 2] +``` + +| Output | Holds | +| --- | --- | +| `OUT/census.jsonl` | One line per cell: the state (`ok`, `empty`, `error`, `mesh_error`, `panic`, `timeout`, `memory`, `crash`), the stage times, the heap, the counts, the caps of `obc_ground_plan::probe`, the crate's checks, and the checks with the west and north neighbours | +| `OUT/summary.json` | The counts per state and per cap, the checks, the border faults, each failed cell with its latitude and longitude, the slowest and largest cells | +| `OUT/workers.log` | The stderr of the workers | + +A release is the store folder of a target (`release.json`, `releases/`, `objects/`). Without `--id`, +the census reads the release that the target serves. A fixture has `features/13/C/R.bin` (gzip), +`terrain/Z/X/Y.webp`, `config.json` and an optional `cells.json`. + +A worker that panics, passes `--timeout-s` in one stage of a cell or is killed ends. The census +records that cell and gives the rest of the job to a new worker. It records `memory` only when the +worker's scope ended by the OOM killer, else `killed`. Three workers in a row that end before their +first cell stop the run: the source cannot be read. The census refuses to start when `--workers` × +`--memory` is more than the available memory less `--min-available-gb`, and it stops when the +available memory falls under `--min-available-gb`. One driver at a time writes an `OUT` folder. + +A run continues from its `census.jsonl`. The first line holds the source and the options, and a +resume with other ones stops. A resume builds again, once, each cell that a `timeout`, `memory`, +`killed` or `crash` stopped (`attempt` 2); a `panic` stays. + +Limits: + +- The mesh check of a shared line needs both meshes in one worker. It leaves out the lines between + two strips of `--strip` columns and two runs of `--rows` rows, and after a new worker starts, the + lines between the rest of the job and the cells that the old worker built (`"mesh": null`). +- The census does not run `records::check::agreement`, `heights::check::border`, `edge_steps`, + `ripple`, `kinks` and `short_features`. +- It does not read the feature archive's `features_format`: a release of another format gives + errors or wrong cells, where the viewer shows no features. + ## Memory The water networks run on all cores. The road jobs run on a core each, the largest first, as many diff --git a/host/obc-trailview-features/src/bake.rs b/host/obc-trailview-features/src/bake.rs index 4474b40e2a..15ad03b26a 100644 --- a/host/obc-trailview-features/src/bake.rs +++ b/host/obc-trailview-features/src/bake.rs @@ -5,17 +5,19 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::time::Instant; +use obc_ground_plan::sections::{is_track, leading_number, water_width_m, WidthRules}; use serde_json::{json, Map, Value}; +use crate::gate::{Census, GATE_M}; use crate::geometry::{area, bounds, contains, key, Boxes}; use crate::kinds::{kind_of, Entry, Waterway}; -use crate::osm::{self, Selected, LANDUSE, LIFT_REACH_M, USES}; +use crate::osm::{self, Selected, LANDUSE, LIFT_REACH_M}; use crate::pmtiles::{self, Header}; use crate::roads::{self, Classes, River, Surroundings}; -use crate::structures::{self, class_of, is_bridge, is_track, leading_number, road_half}; +use crate::structures::{self, is_bridge, GROUND}; use crate::tiles::{simplified, Geometry, Tiles, BUFFER_M, EXTENT, FORMAT, MAX_ZOOM, MIN_ZOOM, TOLERANCE}; use crate::water::{self, Kind, Level}; -use crate::{lifts, metres, rails, sea, world, Part, Tags, Terrain}; +use crate::{levels, lifts, metres, rails, sea, world, Part, Tags, Terrain}; const EARTH_RADIUS_KM: f64 = 6371.0088; /// The waterways and lakes that the water solver sets, and the falls, weirs and dams that keep the @@ -43,14 +45,15 @@ const UNPAVED: [&str; 12] = [ "grass_paver", ]; -/// What the step bakes: the kind table, the region, the credit, the road classes and the archive of -/// the water polygons, without which the tiles hold no sea. +/// What the step bakes: the kind table, the region, the credit, the road classes, their widths and the +/// archive of the water polygons, without which the tiles hold no sea. pub struct Options { pub kinds: Vec, pub bounds: [f64; 4], pub attribution: String, pub classes: Classes, pub class_names: Vec, + pub widths: WidthRules, pub waterways: BTreeMap, pub sea: Option, } @@ -74,7 +77,20 @@ struct Placer { impl Placer { fn place(&mut self, kind: &str, geometry: Geometry, min_zoom: u8, tags: Tags, parts: Vec) { - if self.tiles.add(MAX_ZOOM, kind, geometry, &tags, &parts) { + self.place_with(kind, geometry, min_zoom, tags, parts, None); + } + + /// `place`, with an id on the zoom-13 copies where the feature can take more tags after the cut. + fn place_with( + &mut self, + kind: &str, + geometry: Geometry, + min_zoom: u8, + tags: Tags, + parts: Vec, + id: Option, + ) { + if self.tiles.add(MAX_ZOOM, kind, geometry, &tags, &parts, id) { *self.counts.entry(kind.to_string()).or_default() += 1; } if min_zoom < MAX_ZOOM && self.tiles.meets(min_zoom, &parts) { @@ -114,18 +130,14 @@ pub fn bake( // The lifts wait for the buildings and the other lifts: a station shares their places. The buildings // of the region wait for the landuse areas that hold them; the features of the solvers for all of // their kind. - let (mut lift_ways, mut lift_entry, mut buildings, mut houses, mut landuse, mut uses) = - (Vec::new(), None, Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let (mut lift_ways, mut lift_entry, mut buildings, mut houses, mut landuse) = + (Vec::new(), None, Vec::new(), Vec::new(), Vec::new()); let (mut waters, mut ways, mut stations, mut beyond, mut river_areas, mut culverts) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); osm::objects(kinds, &cut, &binary, |(selected, mut tags, mut parts)| { let Selected::Entry(e) = selected else { if placer.tiles.meets(MAX_ZOOM, &parts) { - if selected == Selected::Use { - uses.push((tags, parts)) - } else { - landuse.push((tags, parts)) - } + landuse.push((tags, parts)); } return; }; @@ -174,20 +186,12 @@ pub fn bake( std::fs::remove_file(&cut).map_err(|e| e.to_string())?; eprintln!("osm: {:.1} s", started.elapsed().as_secs_f64()); let values = landuse_of(&houses.iter().map(|(_, _, parts)| parts).collect::>(), &landuse); - let shown = uses_of(&houses.iter().map(|(_, tags, parts)| (tags, parts)).collect::>(), &uses); - for (((e, mut tags, parts), value), shows) in houses.into_iter().zip(&values).zip(&shown) { + for ((e, mut tags, parts), value) in houses.into_iter().zip(&values) { if let Some(value) = value { tags.insert("landuse".into(), value.clone()); } - if let Some(shows) = shows { - tags.insert("use".into(), shows.clone()); - } placer.entry(&kinds[e], tags, parts); } - let use_counts: Map = - USES.iter().map(|u| (u.to_string(), shown.iter().filter(|v| v.as_deref() == Some(u)).count().into())).collect(); - metrics.insert("uses".into(), use_counts.into()); - drop(uses); let landuse_counts: Map = LANDUSE .iter() .map(|l| (l.to_string(), values.iter().filter(|v| v.as_deref() == Some(l)).count().into())) @@ -214,6 +218,7 @@ pub fn bake( drop(buildings); eprintln!("placed: {:.1} s", started.elapsed().as_secs_f64()); + let (mut ground_census, mut water_census) = (Census::default(), Census::default()); // The heights of a junction need every road that meets there, a river level its whole network, a // ford the water it crosses, and a platform its tracks. if !(waters.is_empty() && ways.is_empty() && stations.is_empty()) { @@ -222,13 +227,14 @@ pub fn bake( .map(|(e, tags, parts)| water_feature(&kinds[*e].kind, tags, std::mem::take(parts), options)) .collect(); let pool = rayon::ThreadPoolBuilder::new().build().map_err(|e| e.to_string())?; - let (levels, _, water_metrics) = pool.install(|| water::solve_by_network(&mut features, terrain)); + let (levels, drawn, _, water_metrics) = pool.install(|| water::solve_by_network(&mut features, terrain)); // The threads of the roads take over the memory of these. drop(pool); metrics.insert( "water".into(), json!({"lakes": water_metrics.lakes, "lakes_spilling": water_metrics.lakes_spilling, - "river_parts": water_metrics.river_parts, "turned": water_metrics.turned}), + "river_parts": water_metrics.river_parts, "turned": water_metrics.turned, + "added_vertices": water_metrics.added}), ); // A waterway that OSM draws uphill has turned round in `features`. for ((_, _, parts), (feature, z)) in waters.iter_mut().zip(features.into_iter().zip(levels)) { @@ -263,6 +269,13 @@ pub fn bake( ); drop((road_features, around, beyond)); eprintln!("roads: {:.1} s", started.elapsed().as_secs_f64()); + let m = &solved.metrics; + eprintln!( + "roads: jobs at the round cap per scale {:?}, largest move of their last round {:?} m, unsettled variables {:?}", + m.capped, + m.capped_step_m.map(|v| round(v, 3)), + m.capped_left + ); let mut road_metrics = road_metrics(&solved.metrics); road_metrics.insert("cut_features".into(), cut.len().into()); let culverts: Vec = solved.culverts.iter().map(|&i| kept[i]).collect(); @@ -274,8 +287,18 @@ pub fn bake( } } } - for (e, tags, parts) in &waters { - placer.entry(&kinds[*e], tags.clone(), parts.clone()); + // The roads read the levels at the map's vertices, the tiles and the census the vertices that the levels + // add: this road solver's active set moves places far from any changed input. The cost: at a crossing a + // road reads the straight level between two vertices of the map, which on a long span can lie metres off + // the water of the tiles. + for ((e, tags, parts), drawn) in waters.iter().zip(drawn) { + let parts: Vec = (parts.iter().zip(drawn)) + .map(|(p, k)| k.map_or_else(|| p.clone(), |(points, z)| Part { points, z: Some(z), ..p.clone() })) + .collect(); + if is_river(*e) && tags.get("bridge").is_none_or(|b| GROUND.contains(&b.as_str())) { + water_census.add(&kinds[*e].kind, &parts, 0.0, terrain, &|_| false); + } + placer.entry(&kinds[*e], tags.clone(), parts); } let mut tracks: Vec<(String, Tags, Part)> = Vec::new(); if !ways.is_empty() { @@ -301,12 +324,13 @@ pub fn bake( .map(|(_, _, parts)| parts.iter().map(|p| p.points.as_slice()).collect()) .chain(river_areas.iter().map(|rings| rings.iter().map(Vec::as_slice).collect())) .collect(); - // A pier stands on the curve of its deck, and beside the curve of a road under it. + // A pier stands on the curve of its deck, and off the outer half-width of a road under it. let deck_curves: Vec = decks.iter().map(|&n| roads::polyline(&ways[n].2[0])).collect(); - let grounded = ways - .iter() - .filter(|(e, tags, _)| !is_bridge(&kinds[*e].kind, tags)) - .flat_map(|(_, tags, parts)| parts.iter().map(move |p| (road_half(tags), p))); + let grounded = + ways.iter().filter(|(e, tags, _)| !is_bridge(&kinds[*e].kind, tags)).flat_map(|(e, tags, parts)| { + let outer = options.widths.way(&kinds[*e].kind, tags, false).outer_m(); + parts.iter().map(move |p| (outer, p)) + }); let under = near_decks(&deck_curves, grounded); let under: Vec<(f64, &[[f64; 2]])> = under.iter().map(|(half, p)| (*half, p.points.as_slice())).collect(); let deck_ways: Vec = decks @@ -321,13 +345,16 @@ pub fn bake( let mut extra: HashMap = decks.iter().zip(added).map(|(&n, tags)| (n, tags.unwrap_or_default())).collect(); let (mut floating, mut shallow) = (None, None); + // The vertices of the decks: a way on the ground that meets a deck there takes its height. + let on_deck: HashSet<[u64; 2]> = + decks.iter().flat_map(|&n| ways[n].2.iter().flat_map(|p| p.points.iter().map(|&q| key(q)))).collect(); for (n, (e, tags, parts)) in ways.iter().enumerate() { - let (mut entry, mut tags, mut parts) = (&kinds[*e], tags.clone(), parts.clone()); + let (mut entry, mut parts) = (&kinds[*e], parts.clone()); if entry.kind == "gallery" && parts[0].z.is_some() { let side = structures::uphill(&parts[0].points, terrain); extra.insert(n, Tags::from([("uphill".to_string(), side.to_string())])); } - let tunnel = entry.kind == "tunnel" && tags.get("tunnel").is_none_or(|t| t != "building_passage"); + let tunnel = entry.kind == "tunnel"; if tunnel { let count = parts.len(); parts.retain(|p| !p.z.as_ref().is_some_and(|z| structures::floating(&p.points, z, terrain))); @@ -340,22 +367,28 @@ pub fn bake( if tunnel && !underpasses.contains(&n) && heights().next().is_some() - && heights().all(|(p, z)| structures::shallow(&tags, &p.points, z, terrain)) + && heights().all(|(p, z)| structures::shallow(tags, &p.points, z, terrain)) { - // A tunnel under what the terrain leaves out, such as a building, is a way on the ground. - tags.remove("tunnel"); + // A tunnel under what the terrain leaves out, such as a building, is a way on the ground. It + // keeps its tunnel tag: the kind decides how it draws, the tag where the drawing may hide it. let mut ground = tags.clone(); ground.insert("tunnel".into(), "no".into()); entry = kind_of(kinds, Geometry::Line, &ground).map_or(entry, |i| &kinds[i]); *shallow.get_or_insert(0) += 1; } + if entry.kind != "tunnel" && tags.get("bridge").is_none_or(|b| GROUND.contains(&b.as_str())) { + let half = options.widths.way(&kinds[*e].kind, tags, false).half_m; + ground_census.add(&entry.kind, &parts, half, terrain, &|p| on_deck.contains(&key(p))); + } let mut all = tags.clone(); all.extend(extra.get(&n).cloned().unwrap_or_default()); - if is_track(&tags) { + if is_track(tags) { let curves = parts.iter().filter(|p| p.z.is_some()).map(roads::polyline); tracks.extend(curves.map(|p| (entry.kind.clone(), tags.clone(), p))); } - placer.entry(entry, all, parts); + // A way whose parts all have an alignment takes the tags of the levels: its metres along run on. + let id = parts.iter().all(|p| p.plan.is_some()).then_some(n as u32); + placer.place_with(&entry.kind, entry.geometry, entry.min_zoom, all, parts, id); } for (point, z, way) in piers { let min_zoom = kinds[ways[decks[way]].0].min_zoom; @@ -398,8 +431,15 @@ pub fn bake( } eprintln!("sea: {:.1} s", started.elapsed().as_secs_f64()); } + let (off, most) = ground_census.off_centre(); + eprintln!("census: {off} positions of ways on the ground lie more than {GATE_M} m off the terrain under their centre line, at most {most:.1} m"); + metrics.insert("census".into(), json!({"ground": ground_census.metrics(), "water": water_census.metrics()})); + let pass = Instant::now(); + let (levels, cells) = levels::tags(&placer.tiles, terrain, memory); + eprintln!("levels: {cells} cells, {} ways tagged in {:.1} s", levels.len(), pass.elapsed().as_secs_f64()); + metrics.insert("levels".into(), json!({"cells": cells, "ways": levels.len()})); low_zooms(&mut placer); - let size = write(&placer, options, output)?; + let size = write(&placer, &levels, options, output)?; eprintln!("tiles: {:.1} s", started.elapsed().as_secs_f64()); let mut out = Map::new(); out.insert("osmium".into(), version.lines().next().unwrap_or_default().into()); @@ -408,10 +448,21 @@ pub fn bake( out.insert("bytes".into(), size.into()); out.insert("bytes_per_km2".into(), (size as f64 / area_km2(options.bounds)).round_ties_even().into()); out.extend(metrics.into_iter().filter(|(_, v)| !v.as_object().is_some_and(Map::is_empty))); + // The gate: no vertex of a way on the ground lies more than GATE_M off the terrain. The census of + // the rivers and streams is in the metrics only. + let past = ground_census.over() + ground_census.under(); + if past > 0 { + return Err(format!( + "the census gate: {past} vertices of ways on the ground lie more than {GATE_M} m off the terrain. \ + Highest: {}. Lowest: {}", + ground_census.places(true), + ground_census.places(false) + )); + } Ok(Value::Object(out)) } -/// The curves of the `ways`, (half-width, part), that can hold a pier off a deck. Only these get a +/// The curves of the `ways`, (outer half-width, part), that can hold a pier off a deck. Only these get a /// polyline: the ways of a region would take gigabytes of them. fn near_decks<'a>(decks: &[Part], ways: impl Iterator) -> Vec<(f64, Part)> { let reach = |p: &Part| { @@ -472,9 +523,10 @@ fn solves_road(kind: &str, tags: &Tags) -> bool { ROADS.contains(&kind) && tags.get("highway").is_none_or(|h| h != "via_ferrata") } -/// The half-width of a waterway in metres: its `width`, else that of its kind. +/// The half-width of a waterway in metres, with no cap: the water solve also serves rivers wider than +/// the ground plan's widest way. fn half_width(rules: &Waterway, tags: &Tags) -> f64 { - tags.get("width").and_then(|w| leading_number(w)).unwrap_or(rules.width_m) / 2.0 + water_width_m(tags, rules.width_m) / 2.0 } /// The rules of a waterway: of its `waterway` value, else of its kind, `river` or `stream`. @@ -487,7 +539,9 @@ fn waterway<'a>(kind: &str, tags: &Tags, options: &'a Options) -> &'a Waterway { fn river(kind: &str, tags: &Tags, points: &[[f64; 2]], options: &Options) -> River { let rules = waterway(kind, tags, options); let (half, cover, lift) = (half_width(rules, tags), rules.cover_m, rules.cover_lift_max_m); - River { points: points.to_vec(), levels: Vec::new(), half, cover, lift } + // Water on a bridge, as an aqueduct, runs over the ways that cross it. + let untagged_culvert = 2.0 * half <= rules.culvert_width_m && tags.get("bridge").is_none_or(|b| b == "no"); + River { points: points.to_vec(), levels: Vec::new(), half, cover, lift, untagged_culvert } } /// The culvert parts of `culverts` with the levels of their water. Parts that meet end to end are one @@ -606,34 +660,46 @@ fn water_feature(name: &str, tags: &Tags, parts: Vec, options: &Options) - } else { Level::Natural }; + let (half, bank, freeboard, curve) = if kind == Kind::River { + let rules = waterway(name, tags, options); + let curve = water::Curve { turn_max_deg: rules.curve_turn_max_deg, off_max_m: rules.curve_off_max_m }; + (half_width(rules, tags), rules.bank_m, rules.freeboard_m, curve) + } else { + (0.0, 0.0, 0.0, water::Curve::default()) + }; water::Feature { kind, level, - half: if kind == Kind::River { half_width(waterway(name, tags, options), tags) } else { 0.0 }, + half, + bank, + freeboard, + curve, ele: tags.get("ele").and_then(|e| leading_number(e)).unwrap_or(f64::NAN), parts, } } -/// A way of the road solver, with the facts of its tags. +/// A way of the road solver, with the facts of its tags. Its class's rank in the width rule is its row +/// of the class table: both keep the order of `solver_rows`. fn road(kind: &str, tags: &Tags, parts: &[Part], options: &Options) -> roads::Feature { - let free = kind == "tunnel" || tags.get("bridge").is_some_and(|b| b != "no"); - let layer = tags.get("layer").and_then(|l| l.trim().parse::().ok()).unwrap_or(0); - let name = class_of(tags); - let rule = options.class_names.iter().position(|n| n == name).unwrap_or_else(|| { - let fallback = if kind == "path" { "path" } else { "road" }; - options.class_names.iter().position(|n| n == fallback).unwrap() - }); + let tag = |key: &str| tags.get(key).map(String::as_str); + let free = kind == "tunnel" || tag("bridge").is_some_and(|b| !GROUND.contains(&b)); + let layer = tag("layer").and_then(|l| l.trim().parse::().ok()).unwrap_or(0); + let widths = options.widths.way(kind, tags, false); + let stones = kind == "path" && tag("ford") == Some("stepping_stones"); + let ford = !stones && (tag("ford").is_some_and(|f| f != "no") || tag("bridge") == Some("low_water_crossing")); roads::Feature { free, tunnel: kind == "tunnel", - ford: tags.get("ford").is_some_and(|f| f != "no"), + ford, + stones, layer, layered: tags.contains_key("layer"), - indoor: !free && layer < 0 && tags.get("tunnel").is_none_or(|t| t == "no"), - half: road_half(tags), + indoor: !free && layer < 0 && tag("tunnel").is_none_or(|t| t == "no"), + half: widths.half_m, + outer: widths.outer_m(), sidewalks: sidewalks(kind, tags), - rule, + rule: widths.rank, parts: parts.iter().map(|p| p.points.clone()).collect(), } } @@ -646,11 +712,17 @@ fn round(value: f64, digits: i32) -> f64 { fn road_metrics(m: &roads::Metrics) -> Map { let value = json!({ "ways": m.ways, "variables": m.variables, "known": m.known, "approaches": m.approaches, "fords": m.fords, - "culverts": m.culverts, "rounds": m.rounds, "held": m.held, "clearances": m.clearances, + "culverts": m.culverts, "rounds": m.rounds, "rounds_capped": m.capped, + "rounds_capped_step_m": m.capped_step_m.map(|v| round(v, 3)), "rounds_capped_unsettled": m.capped_left, + "held": m.held, "clearances": m.clearances, "clearances_low_cm": m.clearances_low_cm, "passes": m.passes, "passes_near_cm": m.passes_near_cm, "grade_excess_m": round(m.grade_excess_m, 4), "grade_excess_at": m.grade_excess_at.map(|v| round(v, 5)), - "grade_excess_over_1cm": m.grade_excess_over_1cm, "residual_p99_m": round(m.residual_p99_m, 2), + "grade_excess_over_1cm": m.grade_excess_over_1cm, "grounded": m.grounded, + "residual_p99_m": round(m.residual_p99_m, 2), "refinements_unconverged": m.refinements_unconverged, "covers": m.covers, "covers_lifted": m.covers_lifted, + "covers_untagged": m.covers_untagged, "covers_untagged_lifted": m.covers_untagged_lifted, + "covers_capped": m.covers_capped, "covers_untagged_capped": m.covers_untagged_capped, + "cover_lift_top_m": round(m.cover_lift_top_m, 2), "sidewalk_tagged_m": m.sidewalks.tagged_m.round(), "sidewalk_built_m": m.sidewalks.built_m.round(), "sidewalk_steep_m": m.sidewalks.steep_m.round(), "sidewalk_bend_m": m.sidewalks.bend_m.round(), "sidewalk_bed_m": m.sidewalks.bed_m.round(), "sidewalk_short_m": m.sidewalks.short_m.round(), @@ -683,55 +755,19 @@ fn landuse_of(buildings: &[&Vec], areas: &[(Tags, Vec)]) -> Vec)], uses: &[(Tags, Vec)]) -> Vec> { - let rank = |u: &str| USES.iter().position(|v| *v == u).unwrap_or(USES.len()); - let mut shown: Vec> = buildings.iter().map(|(tags, _)| tags.get("use").cloned()).collect(); - let mut offer = |k: usize, value: &String| { - if shown[k].as_deref().is_none_or(|old| rank(value) < rank(old)) { - shown[k] = Some(value.clone()); - } - }; - let rings: Vec<&[[f64; 2]]> = buildings.iter().map(|(_, parts)| parts[0].points.as_slice()).collect(); - let houses = Boxes::new(&rings.iter().map(|ring| bounds(ring.iter())).collect::>()); - let (points, areas): (Vec<_>, Vec<_>) = uses.iter().partition(|(_, parts)| !parts[0].outer); - for (tags, parts) in points { - let p = parts[0].points[0]; - for k in houses.overlapping([p[0], p[1], p[0], p[1]]) { - // A shop is often a node of the outline, its entrance: on the ring, which the even-odd test leaves out half the time. - if contains(&[rings[k]], p) || rings[k].contains(&p) { - offer(k, &tags["use"]); - } - } - } - let about = - Boxes::new(&areas.iter().map(|(_, parts)| bounds(parts.iter().flat_map(|p| &p.points))).collect::>()); - for (k, ring) in rings.iter().enumerate() { - let (sx, sy) = ring.iter().fold((0.0, 0.0), |(x, y), p| (x + p[0], y + p[1])); - let middle = [sx / ring.len() as f64, sy / ring.len() as f64]; - for a in about.overlapping([middle[0], middle[1], middle[0], middle[1]]) { - let area_rings: Vec<&[[f64; 2]]> = areas[a].1.iter().map(|p| p.points.as_slice()).collect(); - if contains(&area_rings, middle) { - offer(k, &areas[a].0["use"]); - } - } - } - shown -} - /// The area of the region in km². fn area_km2([west, south, east, north]: [f64; 4]) -> f64 { EARTH_RADIUS_KM.powi(2) * (east - west).to_radians() * (north.to_radians().sin() - south.to_radians().sin()) } /// Write the tiles to the archive at `output`; its bytes. -fn write(placer: &Placer, options: &Options, output: &Path) -> Result { +/// Write the archive, with the tags of the levels on the ways of each id. +fn write(placer: &Placer, levels: &HashMap, options: &Options, output: &Path) -> Result { let mut tiles: Vec<(u64, Vec)> = placer .tiles .tiles .iter() - .map(|(&(z, x, y), tile)| (pmtiles::tile_id(z, x, y), pmtiles::gzip(&tile.bytes()))) + .map(|(&(z, x, y), tile)| (pmtiles::tile_id(z, x, y), pmtiles::gzip(&tile.bytes_with(&|id| levels.get(&id))))) .collect(); if tiles.is_empty() { return Err("The region has no TrailView features".into()); @@ -764,7 +800,7 @@ fn low_zooms(placer: &mut Placer) { for zoom in feature.min_zoom..MAX_ZOOM { let tolerance = TOLERANCE / ((1u64 << zoom) as f64 * EXTENT as f64); let parts = simplified(feature.geometry, &feature.parts, &anchors, tolerance); - placer.tiles.add(zoom, &feature.kind, feature.geometry, &feature.tags, &parts); + placer.tiles.add(zoom, &feature.kind, feature.geometry, &feature.tags, &parts, None); } } } @@ -777,15 +813,6 @@ mod tests { pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect() } - fn square(x: f64, y: f64, side: f64) -> Vec { - vec![Part { - outer: true, - points: vec![[x, y], [x + side, y], [x + side, y + side], [x, y + side]], - z: None, - plan: None, - }] - } - #[test] fn a_road_beside_a_deck_holds_its_piers_off_and_one_far_away_gets_no_polyline() { let y = 0.3218; @@ -805,23 +832,46 @@ mod tests { assert!(structures::bridges(&ways, &[], &[], &flat, &under).1.is_empty(), "the road takes the whole deck"); } - #[test] - fn a_culvert_of_three_ways_takes_its_levels_between_its_two_mouths() { + /// The options of the committed tables, with no kinds. + fn options() -> Options { let table = |text: &str| serde_json::from_str::(text).unwrap(); - let (class_names, classes) = crate::kinds::classes(&crate::kinds::solver_rows(&table(include_str!( - "../../../data/trailview/roads.json" - )))) - .unwrap(); + let roads = crate::kinds::solver_rows(&table(include_str!("../../../data/trailview/roads.json"))); + let finishes = crate::kinds::finish_rows(&table(include_str!("../../../data/trailview/finishes.json"))); + let (class_names, classes) = crate::kinds::classes(&roads).unwrap(); let waterways = table(include_str!("../../../data/trailview/waterways.json")); - let options = Options { + Options { kinds: Vec::new(), bounds: [0.0; 4], attribution: String::new(), classes, class_names, + widths: crate::kinds::widths(&roads, &finishes).unwrap(), waterways: crate::kinds::waterways(&crate::kinds::waterway_rows(&waterways)).unwrap(), sea: None, - }; + } + } + + #[test] + fn a_way_of_the_solver_takes_the_shared_widths_and_the_ground_and_ford_tags_of_the_graph() { + let options = options(); + let of = |kind: &str, pairs: &[(&str, &str)]| road(kind, &tags(pairs), &[], &options); + let boardwalk = of("path", &[("highway", "footway"), ("bridge", "boardwalk")]); + assert!(!boardwalk.free && !boardwalk.ford); + let low = of("road", &[("highway", "track"), ("bridge", "low_water_crossing")]); + assert!(!low.free && low.ford); + let stones = of("path", &[("highway", "path"), ("ford", "stepping_stones")]); + assert!(stones.stones && !stones.ford); + let track = of("road", &[("highway", "track"), ("ford", "stepping_stones")]); + assert!(!track.stones && track.ford); + let primary = of("main-road", &[("highway", "primary")]); + assert_eq!((primary.half, primary.outer, options.class_names[primary.rule].as_str()), (4.0, 6.0, "primary")); + assert_eq!(of("road", &[("highway", "residential"), ("width", "60")]).half, 15.0); + assert!(of("road", &[("highway", "residential"), ("bridge", "yes")]).free); + } + + #[test] + fn a_culvert_of_three_ways_takes_its_levels_between_its_two_mouths() { + let options = options(); // A stream flows west to east: its culvert is three ways, the middle one drawn against the flow. let at = |east: f64| [0.5 + east / metres(0.3), 0.3]; let stream = tags(&[("waterway", "stream"), ("tunnel", "culvert")]); @@ -876,27 +926,4 @@ mod tests { decided(&mut kept); assert_eq!(kept, tags(&[("highway", "residential")])); } - - #[test] - fn a_building_shows_the_strongest_use_of_its_own_its_points_and_the_areas_about_it() { - let point = |x: f64, y: f64, u: &str| { - (tags(&[("use", u)]), vec![Part { outer: false, points: vec![[x, y]], z: None, plan: None }]) - }; - // A shop with a pharmacy in it; a building in a hospital's grounds with a kiosk in it; a shop of its - // own; a building with nothing but a shop at a corner of its outline. - let (own, plain) = (tags(&[("use", "shop")]), tags(&[])); - let houses = - [square(0.0, 0.0, 10.0), square(100.0, 0.0, 10.0), square(200.0, 0.0, 10.0), square(300.0, 0.0, 10.0)]; - let buildings: Vec<(&Tags, &Vec)> = - vec![(&plain, &houses[0]), (&plain, &houses[1]), (&own, &houses[2]), (&plain, &houses[3])]; - let uses = vec![ - point(2.0, 2.0, "shop"), - point(5.0, 5.0, "pharmacy"), - point(105.0, 5.0, "shop"), - (tags(&[("use", "hospital")]), square(90.0, -10.0, 40.0)), - point(310.0, 0.0, "shop"), - ]; - let shown = uses_of(&buildings, &uses); - assert_eq!(shown, [Some("pharmacy".into()), Some("hospital".into()), Some("shop".into()), Some("shop".into())]); - } } diff --git a/host/obc-trailview-features/src/bin/census/driver.rs b/host/obc-trailview-features/src/bin/census/driver.rs new file mode 100644 index 0000000000..ac91f024c2 --- /dev/null +++ b/host/obc-trailview-features/src/bin/census/driver.rs @@ -0,0 +1,496 @@ +//! The driver: it cuts the targets into jobs (strips of columns, cut into runs of rows), runs each job +//! in a worker process under its own memory cap, and appends each line to `census.jsonl`. A worker that +//! panics, passes the time limit of a stage or is killed ends: the driver records the cell that it was +//! on with the reason, and gives the rest of the job to a new worker that skips that cell. A run +//! resumes from `census.jsonl`: it builds again once each cell that a timeout, a kill or a crash +//! stopped, as the PC can cause those. It writes `summary.json` at its end. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::fs::{File, OpenOptions}; +use std::io::{BufRead, BufReader, ErrorKind, Read, Seek, SeekFrom, Write}; +use std::os::unix::process::ExitStatusExt; +use std::path::Path; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::probe::FIELDS; +use serde_json::{json, Map, Value}; + +use crate::source::{Place, Source}; +use crate::{centre, Job}; + +pub struct Options { + pub workers: usize, + /// `MemoryMax` of each worker's scope, or None: no cap (tests). + pub memory: Option, + /// The time that one stage of one cell may take. + pub timeout: Duration, + pub strip: u32, + pub rows: u32, + pub limit: Option, + pub cells: Option>, + pub bounds: Option<[f64; 4]>, + /// The run stops when the PC has less memory available. + pub min_available_gb: f64, +} + +/// The states of a cell that the driver records: the worker ended on it. +const FAILED: [&str; 5] = ["panic", "timeout", "memory", "killed", "crash"]; +/// The failed states that a resume builds again: the PC can cause them. +const RETRY: [&str; 4] = ["timeout", "memory", "killed", "crash"]; +/// The builds of a cell at most: one more after a failure that a resume retries. +const ATTEMPTS: u64 = 2; +/// Workers in a row that end before their first cell stop the run: the source cannot be read. +const STARTS: u32 = 3; +/// The wait before a new worker after one that ended before its first cell. +const BACK_OFF: Duration = Duration::from_secs(1); +/// Cells that each list of the summary names at most. +const TOP: usize = 20; + +struct Running { + child: Child, + /// The worker's scope, when it runs under a memory cap. + unit: Option, + started: Instant, + /// Whether it began a cell. + begun: bool, + job: Job, + /// The cell and stage that it began last, and when, until its line. + current: Option<(CellKey, String, Instant)>, + panic: Option, + fatal: Option, + timed_out: bool, +} + +fn cell_of(v: &Value) -> Option { + let c = v.as_array()?; + Some(CellKey { x: c.first()?.as_u64()? as u32, y: c.get(1)?.as_u64()? as u32 }) +} + +/// MemAvailable of `/proc/meminfo` in GB. +fn available_gb() -> f64 { + let text = std::fs::read_to_string("/proc/meminfo").unwrap_or_default(); + let kb = + text.lines().find(|l| l.starts_with("MemAvailable:")).and_then(|l| l.split_whitespace().nth(1)?.parse().ok()); + kb.map_or(f64::INFINITY, |kb: f64| kb / (1 << 20) as f64) +} + +fn load() -> String { + std::fs::read_to_string("/proc/loadavg").unwrap_or_default().trim().to_string() +} + +/// The lines of `census.jsonl`, the last one of each cell. +fn read_lines(path: &Path) -> BTreeMap { + let text = std::fs::read_to_string(path).unwrap_or_default(); + let lines = text.lines().filter_map(|l| serde_json::from_str::(l).ok()); + lines.filter_map(|v| Some((cell_of(&v["cell"])?, v))).collect() +} + +/// The jobs of the targets: per strip of `strip` columns, runs of `rows` rows, each by row, then column. +fn jobs(mut targets: Vec, options: &Options) -> VecDeque> { + let (strip, rows) = (options.strip.max(1), options.rows.max(1)); + targets.sort_by_key(|k| (k.x / strip, k.y / rows, k.y, k.x)); + if let Some(limit) = options.limit { + targets.truncate(limit); + } + let mut out: VecDeque> = VecDeque::new(); + for k in targets { + match out.back_mut() { + Some(job) if (job[0].x / strip, job[0].y / rows) == (k.x / strip, k.y / rows) => job.push(k), + _ => out.push_back(vec![k]), + } + } + out +} + +fn spawn( + job: Job, + worker_args: &[String], + options: &Options, + log: &File, + id: usize, + tx: &mpsc::Sender<(usize, Option)>, +) -> Result { + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let unit = options.memory.as_ref().map(|_| format!("census-{}-{id}.scope", std::process::id())); + let mut command = match (&options.memory, &unit) { + (Some(max), Some(unit)) => { + let mut c = Command::new("systemd-run"); + c.args(["--user", "--scope", "--quiet", "--unit", unit]); + c.args(["-p", &format!("MemoryMax={max}"), "-p", "MemorySwapMax=0"]); + c.arg(&exe); + c + } + _ => Command::new(&exe), + }; + command.arg("worker").args(worker_args); + command.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(log.try_clone().map_err(|e| e.to_string())?); + let mut child = command.spawn().map_err(|e| format!("cannot start a worker: {e}"))?; + let mut stdin = child.stdin.take().expect("a piped stdin"); + // A worker that ends before it reads its job closes the pipe: the run counts it as a worker that + // ended before its first cell, so a broken pipe is not an error. + if let Err(e) = writeln!(stdin, "{}", job.to_line()) { + if e.kind() != ErrorKind::BrokenPipe { + return Err(format!("the job of a worker: {e}")); + } + } + drop(stdin); + let stdout = child.stdout.take().expect("a piped stdout"); + let tx = tx.clone(); + std::thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + let Ok(line) = line else { break }; + if tx.send((id, Some(line))).is_err() { + return; + } + } + let _ = tx.send((id, None)); + }); + let started = Instant::now(); + Ok(Running { child, unit, started, begun: false, job, current: None, panic: None, fatal: None, timed_out: false }) +} + +/// The bytes of `MemoryMax`-style sizes: a number with K, M, G or T. +fn bytes(size: &str) -> Option { + let (number, unit) = size.split_at(size.find(|c: char| c.is_ascii_alphabetic()).unwrap_or(size.len())); + let shift = ["", "K", "M", "G", "T"].iter().position(|u| u.eq_ignore_ascii_case(unit))?; + Some(number.parse::().ok()? * (1u64 << (10 * shift)) as f64) +} + +/// Whether the kernel's OOM killer ended a worker's scope (its `Result`), and the scope cleared. +fn oom_killed(unit: &str) -> bool { + let show = Command::new("systemctl").args(["--user", "show", "-p", "Result", "--value", unit]).output(); + let _ = Command::new("systemctl").args(["--user", "reset-failed", unit]).stderr(Stdio::null()).status(); + show.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).trim() == "oom-kill") +} + +/// Opens `census.jsonl` to append, locked for this driver, with a partial last line (a driver that +/// died in a write) ended so it cannot join the next line. +fn open_census(path: &Path) -> Result { + let fail = |e: std::io::Error| format!("{}: {e}", path.display()); + let mut file = OpenOptions::new().create(true).read(true).append(true).open(path).map_err(fail)?; + file.try_lock().map_err(|_| format!("{}: another census writes it", path.display()))?; + let length = file.metadata().map_err(fail)?.len(); + if length > 0 { + let mut last = [0u8]; + file.seek(SeekFrom::Start(length - 1)).map_err(fail)?; + file.read_exact(&mut last).map_err(fail)?; + if last[0] != b'\n' { + file.write_all(b"\n").map_err(fail)?; + } + } + Ok(file) +} + +/// The first line of `census.jsonl`: what the run reads and how. A resume must give the same. +fn header(place: &Place, worker_args: &[String]) -> Value { + json!({"census": 1, "place": format!("{place:?}"), "worker": worker_args}) +} + +pub fn run(place: &Place, out: &Path, options: &Options, worker_args: &[String]) -> Result<(), String> { + std::fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?; + let census = out.join("census.jsonl"); + let started = (Instant::now(), load(), available_gb()); + let source = Source::open(place)?; + let mut targets = match &options.cells { + Some(cells) => cells.clone(), + None => source.cells()?, + }; + drop(source); + if let Some(bounds) = options.bounds { + let inside: BTreeSet = crate::source::cells_meeting(bounds).into_iter().collect(); + targets.retain(|k| inside.contains(k)); + } + let all: BTreeSet = targets.iter().copied().collect(); + if let Some(max) = options.memory.as_deref() { + let need = + options.workers as f64 * bytes(max).ok_or_else(|| format!("--memory {max}: a size"))? / (1u64 << 30) as f64; + let free = available_gb() - options.min_available_gb; + if need > free { + return Err(format!( + "{} workers of {max} need {need:.1} GB, and {free:.1} GB is free past --min-available-gb", + options.workers + )); + } + } + let mut file = open_census(&census)?; + let head = header(place, worker_args); + match std::fs::read_to_string(&census).unwrap_or_default().lines().next() { + None => record(&mut file, &head)?, + Some(first) if serde_json::from_str::(first).ok().as_ref() == Some(&head) => {} + Some(_) => return Err(format!("{} holds a census of other options: {head}", census.display())), + } + let before = read_lines(&census); + let attempts = |v: &Value| v["attempt"].as_u64().unwrap_or(1); + let retried = |v: &Value| RETRY.contains(&v["state"].as_str().unwrap_or("")) && attempts(v) < ATTEMPTS; + let mut done: BTreeSet = before.iter().filter(|(_, v)| !retried(v)).map(|(k, _)| *k).collect(); + let mut skip: BTreeSet = (before.iter()) + .filter(|(_, v)| FAILED.contains(&v["state"].as_str().unwrap_or("")) && !retried(v)) + .map(|(k, _)| *k) + .collect(); + let mut tried: BTreeMap = before.iter().map(|(k, v)| (*k, attempts(v))).collect(); + targets.retain(|k| !done.contains(k)); + let mut queue = jobs(targets, options); + let todo: usize = queue.iter().map(Vec::len).sum(); + eprintln!("census: {} cells, {} done before, {todo} to build in {} jobs", all.len(), before.len(), queue.len()); + let log = OpenOptions::new().create(true).append(true).open(out.join("workers.log")).map_err(|e| e.to_string())?; + let (tx, rx) = mpsc::channel(); + let mut running: BTreeMap = BTreeMap::new(); + let (mut next_id, mut failed_starts, mut stopped, mut built) = (0, 0, None::, 0usize); + let mut next_start = Instant::now(); + loop { + while stopped.is_none() && running.len() < options.workers.max(1) && Instant::now() >= next_start { + let Some(job) = queue.pop_front() else { break }; + let targets: Vec = job.into_iter().filter(|k| !done.contains(k) && !skip.contains(k)).collect(); + if targets.is_empty() { + continue; + } + let job = Job { targets, skip: skip.iter().copied().collect() }; + running.insert(next_id, spawn(job, worker_args, options, &log, next_id, &tx)?); + next_id += 1; + } + if running.is_empty() && (queue.is_empty() || stopped.is_some()) { + break; + } + match rx.recv_timeout(Duration::from_millis(250)) { + Ok((id, Some(text))) => { + let Some(w) = running.get_mut(&id) else { continue }; + let Ok(v) = serde_json::from_str::(&text) else { continue }; + if let Some(cell) = cell_of(&v["begin"]) { + (w.begun, failed_starts) = (true, 0); + w.current = Some((cell, v["stage"].as_str().unwrap_or("").to_string(), Instant::now())); + } else if let Some(cell) = cell_of(&v["cell"]) { + let mut v = v; + v["attempt"] = json!(tried.get(&cell).map_or(1, |n| n + 1)); + record(&mut file, &v)?; + done.insert(cell); + w.current = None; + built += 1; + if built % 50 == 0 { + eprintln!("census: {built} of {todo} built, {:.1} GB available", available_gb()); + } + } else if v.get("panic").is_some() { + w.panic = Some(v["panic"].clone()); + } else if let Some(fatal) = v["fatal"].as_str() { + w.fatal = Some(fatal.to_string()); + } + } + Ok((id, None)) => { + let Some(mut w) = running.remove(&id) else { continue }; + let status = w.child.wait().map_err(|e| e.to_string())?; + let left: Vec = w.job.targets.iter().copied().filter(|k| !done.contains(k)).collect(); + if left.is_empty() || stopped.is_some() { + continue; + } + let Some((cell, stage, since)) = w.current.take() else { + // It ended before its first cell (it could not read its source or job), or + // between cells. + if !w.begun { + failed_starts += 1; + next_start = Instant::now() + BACK_OFF; + } + if failed_starts >= STARTS { + stopped = Some(format!( + "{STARTS} workers in a row ended before their first cell, the last with {status}: {}; can the source be read?", + w.fatal.unwrap_or_default() + )); + for other in running.values_mut() { + let _ = other.child.kill(); + } + continue; + } + queue.push_front(left); + continue; + }; + let (lat, lon) = centre(cell); + let mut line = json!({"cell": [cell.x, cell.y], "lat": lat, "lon": lon, "stage": stage, + "stage_ms": since.elapsed().as_secs_f64() * 1e3, "context": !all.contains(&cell)}); + if let Some(fatal) = &w.fatal { + line["error"] = json!(fatal); + } + line["state"] = json!(if w.timed_out { + "timeout" + } else if w.panic.is_some() { + "panic" + } else if status.signal() == Some(9) && w.unit.as_deref().is_some_and(oom_killed) { + "memory" + } else if status.signal() == Some(9) { + "killed" + } else { + "crash" + }); + let attempt = tried.get(&cell).map_or(1, |n| n + 1); + line["attempt"] = json!(attempt); + tried.insert(cell, attempt); + if let Some(panic) = w.panic { + line["panic"] = panic; + } + line["exit"] = json!(status.to_string()); + if !done.contains(&cell) { + record(&mut file, &line)?; + } + eprintln!("census: cell {}/{} ({lat}, {lon}): {} in {stage}", cell.x, cell.y, line["state"]); + done.insert(cell); + skip.insert(cell); + queue.push_front(left.into_iter().filter(|k| *k != cell).collect()); + } + Err(mpsc::RecvTimeoutError::Timeout) => {} + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + for w in running.values_mut() { + // A stage passed its time, or the worker has not begun its first cell in that time. + let late = w + .current + .as_ref() + .map_or(!w.begun && w.started.elapsed() > options.timeout, |c| c.2.elapsed() > options.timeout); + if !w.timed_out && late { + w.timed_out = true; + let _ = w.child.kill(); + } + } + let free = available_gb(); + if stopped.is_none() && free < options.min_available_gb { + stopped = Some(format!("the PC has {free:.1} GB available, under {} GB", options.min_available_gb)); + eprintln!("census: stop: {}", stopped.as_ref().unwrap()); + for w in running.values_mut() { + let _ = w.child.kill(); + } + } + } + let run = json!({ + "wall_s": started.0.elapsed().as_secs_f64(), "built": built, "workers": options.workers, + "memory_max": options.memory, "timeout_s": options.timeout.as_secs_f64(), + "load_start": started.1, "load_end": load(), "available_gb_start": started.2, "available_gb_end": available_gb(), + "stopped": stopped, + }); + let summary = summary(&read_lines(&census), &all, run); + let text = serde_json::to_string_pretty(&summary).expect("JSON"); + std::fs::write(out.join("summary.json"), text).map_err(|e| e.to_string())?; + eprintln!("census: {} -> {}", census.display(), out.join("summary.json").display()); + match stopped { + Some(why) => Err(format!("stopped: {why}; run again to resume")), + None => Ok(()), + } +} + +/// One line with its newline in one write, so a line of a killed driver ends whole or not at all. +fn record(file: &mut File, line: &Value) -> Result<(), String> { + file.write_all(format!("{line}\n").as_bytes()).map_err(|e| e.to_string()) +} + +fn num(v: &Value) -> f64 { + v.as_f64().unwrap_or(0.0) +} + +fn brief(k: &CellKey, v: &Value, extra: &[&str]) -> Value { + let mut out = json!({"cell": format!("{}/{}", k.x, k.y), "lat": v["lat"], "lon": v["lon"], "state": v["state"]}); + for &e in extra { + out[e] = v[e].clone(); + } + out +} + +/// The sum of a counter over the lines, and the cells where it is not 0. +fn tally(lines: &BTreeMap, get: impl Fn(&Value) -> f64) -> Value { + let values: Vec = lines.values().map(get).collect(); + json!({"total": values.iter().sum::(), "cells": values.iter().filter(|&&v| v > 0.0).count()}) +} + +fn summary(everything: &BTreeMap, all: &BTreeSet, run: Value) -> Value { + let lines: BTreeMap = + everything.iter().filter(|(k, _)| all.contains(k)).map(|(k, v)| (*k, v.clone())).collect(); + let mut states: BTreeMap = BTreeMap::new(); + for v in lines.values() { + *states.entry(v["state"].as_str().unwrap_or("?").to_string()).or_default() += 1; + } + let ok: Vec<(&CellKey, &Value)> = + lines.iter().filter(|(_, v)| v.get("ms").is_some() && v["digest"].is_string()).collect(); + let total_ms = |v: &Value| ["input", "graph", "faces", "mesh"].iter().map(|s| num(&v["ms"][s])).sum::(); + let top = |key: &dyn Fn(&Value) -> f64, extra: &[&str]| -> Vec { + let mut sorted = ok.clone(); + sorted.sort_by(|a, b| key(b.1).total_cmp(&key(a.1))); + sorted.iter().take(TOP).map(|(k, v)| brief(k, v, extra)).collect() + }; + let mut caps = Map::new(); + for cap in ["slots", "quads", "regions", "slice_fallback"] { + caps.insert(format!("build.{cap}"), tally(&lines, |v| num(&v["caps"][cap]))); + caps.insert(format!("audit.{cap}"), tally(&lines, |v| num(&v["audit"][cap]))); + } + for k in ["capped", "host_missing"] { + caps.insert(format!("audit.{k}_points"), tally(&lines, |v| num(&v["audit"][k]))); + } + for k in ["outside_d", "unlabelled", "split_edges"] { + caps.insert(format!("mesh.{k}"), tally(&lines, |v| num(&v["mesh"][k]))); + } + let mut fields = Map::new(); + for (field, name) in FIELDS { + let most = + lines.iter().max_by(|a, b| num(&a.1["caps"]["fields"][name]).total_cmp(&num(&b.1["caps"]["fields"][name]))); + let over = lines.values().filter(|v| num(&v["caps"]["fields"][name]) > field.limit() as f64).count(); + fields.insert( + name.into(), + json!({"limit": field.limit(), "cells_over": over, + "largest": most.map(|(k, v)| json!({"cell": format!("{}/{}", k.x, k.y), "lat": v["lat"], "lon": v["lon"], "value": v["caps"]["fields"][name]}))}), + ); + } + caps.insert("fields".into(), Value::Object(fields)); + let mut counters: BTreeMap = BTreeMap::new(); + for v in lines.values() { + for group in ["graph", "face_stats"] { + for (name, n) in v[group].as_object().into_iter().flatten() { + let c = counters.entry(format!("{group}.{name}")).or_default(); + (c.0, c.1) = (c.0 + num(n), c.1 + 1); + } + } + } + let checks = json!({ + "partition_faults": tally(&lines, |v| num(&v["checks"]["partition"])), + "artefacts": tally(&lines, |v| num(&v["checks"]["artefacts"])), + "mesh_validity": tally(&lines, |v| num(&v["mesh"]["validity"])), + "mesh_labels_ground_wrong": tally(&lines, |v| num(&v["mesh"]["labels"]["ground_wrong"])), + "mesh_labels_sharp_wrong": tally(&lines, |v| num(&v["mesh"]["labels"]["sharp_wrong"])), + "first": lines.iter().filter(|(_, v)| v["checks"]["first"].as_array().is_some_and(|f| !f.is_empty())) + .take(TOP).map(|(k, v)| json!({"cell": format!("{}/{}", k.x, k.y), "lat": v["lat"], "lon": v["lon"], "first": v["checks"]["first"]})) + .collect::>(), + }); + let (mut pairs, mut mesh_pairs, mut differ) = (0, 0, Vec::new()); + let mut by_check: BTreeMap<&str, usize> = BTreeMap::new(); + for (k, v) in &lines { + for (side, b) in v["borders"].as_object().into_iter().flatten() { + pairs += 1; + mesh_pairs += usize::from(!b["mesh"].is_null()); + let bad: Vec<&str> = + ["faces", "records", "outline", "mesh"].into_iter().filter(|c| num(&b[c]) > 0.0).collect(); + for c in &bad { + *by_check.entry(c).or_default() += 1; + } + if !bad.is_empty() { + differ.push(json!({"cell": format!("{}/{}", k.x, k.y), "side": side, "lat": v["lat"], "lon": v["lon"], + "faces": b["faces"], "records": b["records"], "outline": b["outline"], "mesh": b["mesh"], "first": b["first"]})); + } + } + } + // A neighbour outside the targets that failed as a mesh's context counts too. + let failed: Vec = (everything.iter()) + .filter(|(_, v)| !matches!(v["state"].as_str(), Some("ok" | "empty"))) + .map(|(k, v)| brief(k, v, &["context", "stage", "stage_ms", "panic", "error", "mesh", "exit"])) + .collect(); + let peak_rss_kb = lines.values().map(|v| num(&v["rss_kb"])).fold(0.0, f64::max); + json!({ + "cells": all.len(), + "recorded": lines.len(), + "states": states, + "run": run, + "peak_worker_rss_mb": peak_rss_kb / 1024.0, + "caps": caps, + "counters": counters.into_iter().map(|(k, (t, c))| (k, json!({"total": t, "cells": c}))).collect::>(), + "checks": checks, + "borders": {"pairs": pairs, "mesh_checked": mesh_pairs, "differ_by_check": by_check, "differ": differ}, + "failed": failed, + "slowest": top(&total_ms, &["ms"]), + "largest_records": top(&|v| num(&v["words"]), &["words"]), + "largest_heap": top(&|v| num(&v["heap"]).max(num(&v["heap_mesh"])), &["heap", "heap_mesh"]), + }) +} diff --git a/host/obc-trailview-features/src/bin/census/main.rs b/host/obc-trailview-features/src/bin/census/main.rs new file mode 100644 index 0000000000..8092c24714 --- /dev/null +++ b/host/obc-trailview-features/src/bin/census/main.rs @@ -0,0 +1,206 @@ +//! `census`: builds every zoom-16 cell of a box natively as the TrailView viewer does (the cell, then +//! its mesh with the rims of its eight neighbours), and records per cell whether the build is ok, +//! panics, hangs or grows too large, which caps it hits, the crate's own checks, and whether +//! neighbouring cells agree on their shared line. One bad cell never stops the run: the driver gives +//! jobs to worker processes, each under its own memory cap, and starts a new worker after one ends. + +#[path = "../../../../obc-ground-plan/tests/fixture/mod.rs"] +mod fixture; + +mod driver; +mod source; +mod worker; + +use std::path::PathBuf; +use std::time::Duration; + +use obc_ground_plan::frame::{CellKey, CELL_UNITS, FRAME_BITS}; + +use source::{parse_cell, Place}; +use worker::Fail; + +/// The heap in bytes, and its peak: the peak of a stage is the peak above the heap at its start. +mod heap { + use std::alloc::{GlobalAlloc, Layout, System}; + use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; + + static NOW: AtomicUsize = AtomicUsize::new(0); + static PEAK: AtomicUsize = AtomicUsize::new(0); + + pub struct Counting; + + unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let p = unsafe { System.alloc(layout) }; + if !p.is_null() { + PEAK.fetch_max(NOW.fetch_add(layout.size(), Relaxed) + layout.size(), Relaxed); + } + p + } + + unsafe fn dealloc(&self, p: *mut u8, layout: Layout) { + unsafe { System.dealloc(p, layout) }; + NOW.fetch_sub(layout.size(), Relaxed); + } + + unsafe fn realloc(&self, p: *mut u8, layout: Layout, size: usize) -> *mut u8 { + let q = unsafe { System.realloc(p, layout, size) }; + if !q.is_null() { + if size > layout.size() { + let grown = size - layout.size(); + PEAK.fetch_max(NOW.fetch_add(grown, Relaxed) + grown, Relaxed); + } else { + NOW.fetch_sub(layout.size() - size, Relaxed); + } + } + q + } + } + + /// The heap now, with the peak reset to it. + pub fn start() -> usize { + let now = NOW.load(Relaxed); + PEAK.store(now, Relaxed); + now + } + + /// The peak since `start` above its heap. + pub fn peak(base: usize) -> usize { + PEAK.load(Relaxed).saturating_sub(base) + } +} + +#[global_allocator] +static HEAP: heap::Counting = heap::Counting; + +/// The job of a worker, one JSON line on its stdin: its targets in order and the cells that it must not +/// build (they failed before). +#[derive(Debug, Default)] +pub struct Job { + pub targets: Vec, + pub skip: Vec, +} + +impl Job { + pub fn to_line(&self) -> String { + let cells = |c: &[CellKey]| c.iter().map(|k| [k.x, k.y]).collect::>(); + serde_json::json!({"targets": cells(&self.targets), "skip": cells(&self.skip)}).to_string() + } + + pub fn parse(line: &str) -> Result { + let value: serde_json::Value = serde_json::from_str(line).map_err(|e| format!("the job: {e}"))?; + let cells = |name: &str| -> Result, String> { + let list: Vec<[u32; 2]> = + serde_json::from_value(value[name].clone()).map_err(|e| format!("the job: {e}"))?; + Ok(list.into_iter().map(|[x, y]| CellKey { x, y }).collect()) + }; + Ok(Job { targets: cells("targets")?, skip: cells("skip")? }) + } +} + +/// The latitude and longitude of a cell's centre. +pub fn centre(key: CellKey) -> (f64, f64) { + let square = (1u64 << FRAME_BITS) as f64; + let o = key.origin(); + let (x, y) = ((o.x + CELL_UNITS / 2) as f64 / square, (o.y + CELL_UNITS / 2) as f64 / square); + let lat = (std::f64::consts::PI * (1.0 - 2.0 * y)).sinh().atan().to_degrees(); + let round = |v: f64| (v * 1e6).round() / 1e6; + (round(lat), round(x * 360.0 - 180.0)) +} + +const USAGE: &str = "census (--fixture DIR | --release DIR [--id ID]) --out DIR [--workers 3] [--memory 2G|none] + [--timeout-s 60] [--grid-m 4] [--strip 10] [--rows 48] [--limit N] [--cells X/Y,...] [--bounds W,S,E,N] + [--min-available-gb 2] [--levels] [--fail X/Y=panic|hang | --fail start]..."; + +fn main() { + let worker = std::env::args().nth(1).as_deref() == Some("worker"); + if let Err(e) = run(worker) { + if worker { + println!("{}", serde_json::json!({"fatal": e})); + } + eprintln!("census: {e}"); + std::process::exit(2); + } +} + +fn run(worker: bool) -> Result<(), String> { + let mut args = std::env::args().skip(1 + usize::from(worker)); + let (mut fixture, mut release, mut id, mut out) = (None::, None::, None, None::); + let mut options = driver::Options { + workers: 3, + memory: Some("2G".into()), + timeout: Duration::from_secs(60), + strip: 10, + rows: 48, + limit: None, + cells: None, + bounds: None, + min_available_gb: 2.0, + }; + let (mut grid_m, mut fail, mut levels) = (4.0, Vec::new(), false); + while let Some(arg) = args.next() { + let mut value = || args.next().ok_or_else(|| format!("{arg} needs a value\n{USAGE}")); + let number = |v: String| v.parse::().map_err(|_| format!("{arg}: a number")); + match arg.as_str() { + "--fixture" => fixture = Some(value()?.into()), + "--release" => release = Some(value()?.into()), + "--id" => id = Some(value()?), + "--out" => out = Some(value()?.into()), + "--workers" => options.workers = number(value()?)? as usize, + "--memory" => options.memory = Some(value()?).filter(|m| m != "none"), + "--timeout-s" => options.timeout = Duration::from_secs_f64(number(value()?)?), + "--grid-m" => grid_m = number(value()?)?, + "--levels" => levels = true, + "--strip" => options.strip = number(value()?)? as u32, + "--rows" => options.rows = number(value()?)? as u32, + "--limit" => options.limit = Some(number(value()?)? as usize), + "--min-available-gb" => options.min_available_gb = number(value()?)?, + "--cells" => options.cells = Some(value()?.split(',').map(parse_cell).collect::>()?), + "--bounds" => { + let v: Vec = value()? + .split(',') + .map(|v| v.parse().map_err(|_| "--bounds: W,S,E,N")) + .collect::>()?; + options.bounds = Some(v.try_into().map_err(|_| "--bounds: W,S,E,N")?); + } + "--fail" => { + let v = value()?; + if v == "start" { + fail.push((CellKey { x: 0, y: 0 }, Fail::Start)); + continue; + } + let (cell, how) = v.split_once('=').ok_or("--fail X/Y=panic|hang")?; + let how = match how { + "panic" => Fail::Panic, + "hang" => Fail::Hang, + _ => return Err("--fail X/Y=panic|hang".into()), + }; + fail.push((parse_cell(cell)?, how)); + } + _ => return Err(format!("unknown option {arg}\n{USAGE}")), + } + } + let place = match (fixture, release) { + (Some(dir), None) => Place::Fixture(dir), + (None, Some(dir)) => Place::Release(dir, id), + _ => return Err(format!("give --fixture or --release\n{USAGE}")), + }; + if worker { + return worker::run(worker::Options { place, grid_m, fail, levels }); + } + let out = out.ok_or_else(|| format!("give --out\n{USAGE}"))?; + let mut worker_args = place.args(); + worker_args.extend(["--grid-m".into(), grid_m.to_string()]); + if levels { + worker_args.push("--levels".into()); + } + for (cell, how) in &fail { + worker_args.push("--fail".into()); + worker_args.push(match how { + Fail::Panic => format!("{}/{}=panic", cell.x, cell.y), + Fail::Hang => format!("{}/{}=hang", cell.x, cell.y), + Fail::Start => "start".into(), + }); + } + driver::run(&place, &out, &options, &worker_args) +} diff --git a/host/obc-trailview-features/src/bin/census/source.rs b/host/obc-trailview-features/src/bin/census/source.rs new file mode 100644 index 0000000000..f6e104913c --- /dev/null +++ b/host/obc-trailview-features/src/bin/census/source.rs @@ -0,0 +1,229 @@ +//! The request of a cell as the viewer collects it: from a fixture folder (`features/13/C/R.bin` gzip, +//! `terrain/Z/X/Y.webp`) or from the map packs of a local release of `obc data`. It only reads. + +use std::collections::BTreeMap; +use std::io::Read; +use std::path::{Path, PathBuf}; + +use obc_data::engine::Client; +use obc_data::release::{manifest_key, List, Release as Manifest, Serving, SERVING}; +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::terrain::{pages_from_terrarium, StoredPage, Terrain}; +use obc_ground_plan::transport::{FeatureTile, Request}; +use obc_trailview_features::Archive; +use serde_json::Value; + +use crate::fixture::{self, Fixture}; + +/// Decoded terrain tiles that a release keeps: about 0.5 MB each. +const TERRAIN_TILES: usize = 64; + +/// The pages of a stored terrain tile; None where the release lacks the tile. +type Pages = Option<[Option; 4]>; + +pub enum Source { + Fixture(Box), + Release(Box), +} + +/// Where the cells come from, as the driver passes it to its workers. +#[derive(Clone, Debug)] +pub enum Place { + Fixture(PathBuf), + Release(PathBuf, Option), +} + +impl Place { + pub fn args(&self) -> Vec { + match self { + Place::Fixture(dir) => vec!["--fixture".into(), dir.display().to_string()], + Place::Release(dir, id) => { + let mut out = vec!["--release".into(), dir.display().to_string()]; + out.extend(id.iter().flat_map(|id| ["--id".into(), id.clone()])); + out + } + } + } +} + +impl Source { + pub fn open(place: &Place) -> Result { + Ok(match place { + Place::Fixture(dir) => Source::Fixture(Box::new(Fixture::open(dir))), + Place::Release(dir, id) => Source::Release(Box::new(Release::open(dir, id.as_deref())?)), + }) + } + + /// The request of a cell, or None where none of its feature tiles exists: the viewer builds no plan + /// there. + pub fn request(&mut self, key: CellKey) -> Result, String> { + let request = match self { + Source::Fixture(fixture) => fixture.request(key), + Source::Release(release) => release.request(key)?, + }; + Ok((!request.tiles.is_empty()).then_some(request)) + } + + /// The cells to census: the fixture's `cells.json`, or every cell whose square lies inside the + /// fixture's bounds and whose feature tiles all exist; every cell that meets a release's bounds. + pub fn cells(&self) -> Result, String> { + match self { + Source::Fixture(fixture) => { + let listed = fixture.dir().join("cells.json"); + if listed.is_file() { + let text = std::fs::read(&listed).map_err(|e| format!("{}: {e}", listed.display()))?; + let cells: Vec = serde_json::from_slice(&text).map_err(|e| e.to_string())?; + return cells.iter().map(|c| parse_cell(c["cell"].as_str().unwrap_or(""))).collect(); + } + let dir = fixture.dir(); + Ok((fixture.cells().into_iter()) + .filter(|k| k.feature_tiles().iter().all(|&(c, r)| fixture::feature_tile(dir, c, r).is_some())) + .collect()) + } + Source::Release(release) => Ok(cells_meeting(release.bounds)), + } + } +} + +/// `16/X/Y` or `X/Y`. +pub fn parse_cell(text: &str) -> Result { + let parts: Vec<&str> = text.split('/').collect(); + let [x, y] = parts[parts.len().saturating_sub(2)..] else { return Err(format!("not a cell: {text:?}")) }; + let n = |v: &str| v.parse::().map_err(|_| format!("not a cell: {text:?}")); + Ok(CellKey { x: n(x)?, y: n(y)? }) +} + +/// The zoom-16 cells that meet [west, south, east, north], by row, then column. +pub fn cells_meeting([west, south, east, north]: [f64; 4]) -> Vec { + use obc_ground_plan::frame::from_lon_lat; + let (a, b) = (CellKey::of(from_lon_lat(west, north)), CellKey::of(from_lon_lat(east, south))); + (a.y..=b.y).flat_map(|y| (a.x..=b.x).map(move |x| CellKey { x, y })).collect() +} + +/// The map packs of one kind of a release: `maps/tiles//...pmtiles` to its object. +struct Packs { + files: BTreeMap, + open: BTreeMap, +} + +impl Packs { + /// The tile's bytes as its pack stores them: the deepest pack that exists whose square holds the + /// tile, from the tile's zoom back to the base level of its zoom (`specs/planner-offline.md`). + fn get(&mut self, prefix: &str, z: u32, x: u32, y: u32) -> Result>, String> { + let base = match z { + 0..=6 => 0, + 7..=8 => 7, + _ => 9, + }; + let Some(name) = (base..=z) + .rev() + .map(|level| format!("{prefix}{level}-{}-{}.pmtiles", x >> (z - level), y >> (z - level))) + .find(|name| self.files.contains_key(name)) + else { + return Ok(None); + }; + if !self.open.contains_key(&name) { + let archive = Archive::open(&self.files[&name]).map_err(|e| format!("{name}: {e}"))?; + self.open.insert(name.clone(), archive); + } + self.open[&name].get(z as u8, x, y).map_err(|e| format!("{name}: {e}")) + } +} + +pub struct Release { + features: Packs, + terrain: Packs, + /// West, south, east, north of the feature layer. + pub bounds: [f64; 4], + /// Decoded terrain tiles with the order of their decode. + pages: BTreeMap<(u32, u32, u32), (u64, Pages)>, + clock: u64, +} + +impl Release { + /// The release `id` of the target folder `dir`, or the one that it serves. + pub fn open(dir: &Path, id: Option<&str>) -> Result { + let read = |key: &str| std::fs::read(dir.join(key)).map_err(|e| format!("{}: {e}", dir.join(key).display())); + let id = match id { + Some(id) => id.to_string(), + None => { + let serving: Serving = serde_json::from_slice(&read(SERVING)?).map_err(|e| e.to_string())?; + serving.serving.id + } + }; + let manifest = Manifest::parse(&id, &read(&manifest_key(&id))?)?; + let files = manifest.load(|list: &List| read(&list.key()))?; + // The published output of a layer: its files hold its pack index. + let packs = |layer: &str| -> Result<(Packs, Value), String> { + let output = (files.outputs.iter()) + .find(|o| { + o.layer == layer && matches!(&o.client, Client::Paths(p) if p.iter().any(|p| p == "index.json")) + }) + .ok_or_else(|| format!("release {id} publishes no {layer}"))?; + let index = output.files.iter().find(|f| f.path == "index.json").ok_or("no index.json")?; + let index: Value = + serde_json::from_slice(&read(&format!("objects/{}", index.sha256))?).map_err(|e| e.to_string())?; + let files = (index["files"].as_object().ok_or("index.json has no files")?.iter()) + .filter(|(name, _)| name.ends_with(".pmtiles")) + .map(|(name, entry)| { + let sha = entry["sha256"].as_str().ok_or_else(|| format!("{name} has no sha256"))?; + Ok((name.clone(), dir.join("objects").join(sha))) + }) + .collect::>()?; + Ok((Packs { files, open: BTreeMap::new() }, output.options.clone())) + }; + let (features, options) = packs("planner/trailview-features")?; + let (terrain, _) = packs("planner/terrain")?; + let bounds: [f64; 4] = serde_json::from_value(options["bounds"].clone()) + .map_err(|_| "planner/trailview-features has no bounds".to_string())?; + Ok(Release { features, terrain, bounds, pages: BTreeMap::new(), clock: 0 }) + } + + fn request(&mut self, key: CellKey) -> Result { + let mut tiles = Vec::new(); + for (column, row) in key.feature_tiles() { + let Some(body) = self.features.get("maps/tiles/trailview-features/", 13, column, row)? else { continue }; + // A body can be the gzip of the tile, as the viewer finds it. + let bytes = if body.starts_with(&[0x1f, 0x8b]) { + let mut plain = Vec::new(); + flate2::read::GzDecoder::new(&body[..]).read_to_end(&mut plain).map_err(|e| e.to_string())?; + plain + } else { + body + }; + tiles.push(FeatureTile { column, row, bytes }); + } + let mut pages = Vec::new(); + for page in Terrain::wanted(key) { + let (z, x, y, quadrant) = page.tile(); + if let Some(p) = self.tile_pages(z, x, y)?.and_then(|t| t[quadrant].clone()) { + pages.push(p); + } + } + Ok(Request { key, tiles, pages }) + } + + fn tile_pages(&mut self, z: u32, x: u32, y: u32) -> Result { + self.clock += 1; + if let Some(entry) = self.pages.get_mut(&(z, x, y)) { + entry.0 = self.clock; + return Ok(entry.1.clone()); + } + let prefix = if z == 13 { "maps/tiles/terrain/13/" } else { "maps/tiles/terrain/" }; + let decoded = match self.terrain.get(prefix, z, x, y)? { + None => None, + Some(webp) => { + let rgba = image::load_from_memory_with_format(&webp, image::ImageFormat::WebP) + .map_err(|e| format!("terrain {z}/{x}/{y}: {e}"))? + .to_rgba8(); + Some(pages_from_terrarium(rgba.as_raw(), rgba.width() as usize, z, x, y).map_err(|e| e.to_string())?) + } + }; + if self.pages.len() >= TERRAIN_TILES { + let oldest = self.pages.iter().min_by_key(|e| e.1 .0).map(|e| *e.0); + self.pages.remove(&oldest.unwrap()); + } + self.pages.insert((z, x, y), (self.clock, decoded.clone())); + Ok(decoded) + } +} diff --git a/host/obc-trailview-features/src/bin/census/worker.rs b/host/obc-trailview-features/src/bin/census/worker.rs new file mode 100644 index 0000000000..1bee0cd801 --- /dev/null +++ b/host/obc-trailview-features/src/bin/census/worker.rs @@ -0,0 +1,357 @@ +//! A worker: it builds the cells of its job as the viewer does and prints one JSON line per cell. It +//! walks its targets by row and keeps the cells of the last three rows, so each target's mesh reads the +//! rims of its eight neighbours and each target meets its west and north neighbours in the checks. +//! Before each stage it prints `{"begin": [x, y], "stage": …}`: the driver times that stage and names +//! the cell when the worker ends. + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{BufRead, Write}; +use std::time::Instant; + +use obc_ground_plan::cell::{build_cell_with, CellBuild}; +use obc_ground_plan::faces::check::{artefacts, feature_names, neighbours, partition}; +use obc_ground_plan::faces::heights::check::caps; +use obc_ground_plan::faces::records::check::{border as records_border, outline_border}; +use obc_ground_plan::faces::{window, Rules}; +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::mesh::{check as mesh_check, mesh_cell, CellMesh, Reads, Rim}; +use obc_ground_plan::probe::{self, Probe, FIELDS}; +use obc_ground_plan::terrain::Terrain; +use obc_ground_plan::tile::TileCache; +use obc_ground_plan::transport::Flat; +use serde_json::{json, Map, Value}; + +use crate::heap; +use crate::source::{Place, Source}; +use crate::{centre, Job}; + +/// The zoom-13 tiles that the worker keeps parsed, as the viewer's plan worker does. +const TILES: usize = 6; +/// The step along a shared line of the records' border check, in frame units. +const BORDER_STEP: i32 = 256; +/// The faults that a line names per check. +const FIRST: usize = 3; + +/// What the worker does besides the census, for the driver's test: a made-up failure of one cell, or +/// of each worker before its first cell. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Fail { + Panic, + Hang, + Start, +} + +pub struct Options { + pub place: Place, + pub grid_m: f64, + /// Only the graph's counters and levels per cell: no mesh and no checks. + pub levels: bool, + pub fail: Vec<(CellKey, Fail)>, +} + +struct Built { + build: CellBuild, + terrain: Terrain, + names: Vec<[u32; 3]>, + rim: Rim, + heap: usize, + probe: Probe, + mesh: Option, + /// The cell's levels (`graph::levels`), for the census of the crossings. + levels: Value, +} + +impl Built { + fn face_cell(&self) -> obc_ground_plan::faces::check::Cell<'_> { + (&self.build.faces, &self.build.graph, &self.names) + } + + fn records_cell(&self) -> obc_ground_plan::faces::records::check::Cell<'_> { + (&self.build.records, &self.build.graph, &self.names) + } + + fn mesh_cell<'a>(&'a self, mesh: &'a CellMesh) -> mesh_check::Cell<'a> { + mesh_check::Cell { key: self.build.key, mesh, words: &self.build.records, terrain: &self.terrain } + } +} + +enum Slot { + Built(Box), + /// None of its feature tiles exists, or the driver skips it. + Missing, + Error(String), +} + +fn emit(line: &Value) { + let mut out = std::io::stdout().lock(); + writeln!(out, "{line}").and_then(|()| out.flush()).expect("the driver reads the lines"); +} + +fn begin(key: CellKey, stage: &str, options: &Options) { + emit(&json!({"begin": [key.x, key.y], "stage": stage})); + match options.fail.iter().find(|f| f.0 == key && stage == "build").map(|f| f.1) { + Some(Fail::Panic) => panic!("a made-up failure of cell {}/{}", key.x, key.y), + Some(Fail::Hang) => loop { + std::thread::sleep(std::time::Duration::from_secs(1)); + }, + Some(Fail::Start) | None => {} + } +} + +/// The cells about a cell, by row, then column, itself among them. +fn around(key: CellKey) -> impl Iterator { + (-1..=1i64).flat_map(move |dy| { + (-1..=1i64).map(move |dx| CellKey { x: (i64::from(key.x) + dx) as u32, y: (i64::from(key.y) + dy) as u32 }) + }) +} + +fn probe_json(p: &Probe) -> Value { + let fields: Map = FIELDS.iter().map(|f| (f.1.to_string(), json!(p.fields[f.0 as usize]))).collect(); + json!({"slots": p.slots, "quads": p.quads, "regions": p.regions, "slice_fallback": p.slice_fallback, "fields": fields}) +} + +fn counters(list: &[(&'static str, u32)]) -> Value { + Value::Object(list.iter().filter(|c| c.1 > 0).map(|c| (c.0.to_string(), json!(c.1))).collect()) +} + +fn rss_kb() -> u64 { + let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); + let line = status.lines().find(|l| l.starts_with("VmHWM:")).unwrap_or(""); + line.split_whitespace().nth(1).and_then(|v| v.parse().ok()).unwrap_or(0) +} + +struct Worker<'a> { + options: &'a Options, + source: Source, + cache: TileCache, + rules: &'static Rules, + cells: BTreeMap, + skip: BTreeSet, + start: Instant, +} + +impl Worker<'_> { + fn now(&self) -> f64 { + self.start.elapsed().as_secs_f64() * 1e3 + } + + fn ensure(&mut self, key: CellKey) -> Result<(), String> { + if self.cells.contains_key(&key) { + return Ok(()); + } + if self.skip.contains(&key) { + self.cells.insert(key, Slot::Missing); + return Ok(()); + } + begin(key, "build", self.options); + let Some(request) = self.source.request(key)? else { + self.cells.insert(key, Slot::Missing); + return Ok(()); + }; + let bytes = request.encode(); + probe::take(); + let base = heap::start(); + let start = self.start; + let built = build_cell_with(&bytes, &mut self.cache, self.rules, &mut || start.elapsed().as_secs_f64() * 1e3); + let (heap, probe) = (heap::peak(base), probe::take()); + let slot = match built { + Err(e) => Slot::Error(e), + Ok(build) => { + let input = request.input(&mut self.cache)?; + let rim = Rim::of(&build.faces); + let names = feature_names(&input); + let mut graph = build.graph.clone(); + obc_ground_plan::graph::levels(&mut graph, &input, &self.rules.sections, &self.rules.structures); + let levels = crate::fixture::levels_detail(&graph, &input.terrain); + Slot::Built(Box::new(Built { + build, + terrain: input.terrain, + names, + rim, + heap, + probe, + mesh: None, + levels, + })) + } + }; + self.cells.insert(key, slot); + Ok(()) + } + + fn built(&self, key: CellKey) -> Option<&Built> { + match self.cells.get(&key) { + Some(Slot::Built(b)) => Some(b), + _ => None, + } + } + + /// The line of a target, its mesh kept for the checks of its east and south neighbours. + fn census(&mut self, key: CellKey) -> Value { + let (lat, lon) = centre(key); + let mut line = json!({"cell": [key.x, key.y], "lat": lat, "lon": lon}); + let b = match self.cells.get(&key) { + Some(Slot::Built(b)) => b, + Some(Slot::Error(e)) => { + line["state"] = json!("error"); + line["error"] = json!(e); + return line; + } + _ => { + line["state"] = json!("empty"); + return line; + } + }; + let build = &b.build; + line["levels"] = b.levels.clone(); + if self.options.levels { + line["state"] = json!("ok"); + line["graph"] = counters(&build.graph.stats.counters()); + return line; + } + begin(key, "mesh", self.options); + let rims: Vec = around(key).filter_map(|k| self.built(k).map(|n| n.rim.clone())).collect(); + let reads = Reads::of(&build.faces, &rims); + let t0 = self.now(); + let base = heap::start(); + let start = self.start; + let mesh = mesh_cell(&build.faces, &build.records, &reads, &mut || start.elapsed().as_secs_f64() * 1e3); + let heap_mesh = heap::peak(base); + let mesh_ms = self.now() - t0; + begin(key, "checks", self.options); + let t1 = self.now(); + let (mut laps, mut last) = (Map::new(), t1); + let mut lap = |name: &str| { + let t = start.elapsed().as_secs_f64() * 1e3; + laps.insert(name.into(), json!(t - last)); + last = t; + }; + let (plan, graph) = (&build.faces, &build.graph); + let mut first: Vec = Vec::new(); + let mut note = |found: Vec| { + let n = found.len(); + first.extend(found.into_iter().take(FIRST)); + n + }; + let digest = Flat::of(build).digest(build).unwrap_or_else(|e| format!("error: {e}")); + lap("digest"); + let faults = note(partition(plan, window(key, 0.0)).into_iter().map(|f| format!("1: {}", f.what)).collect()); + lap("partition"); + let thin = artefacts(plan, graph).len(); + lap("artefacts"); + let mesh_json = match &mesh { + Ok(m) => { + let validity = note(mesh_check::validity(m).into_iter().map(|f| format!("mesh: {f}")).collect()); + let labels = mesh_check::labels(m, &build.records); + let s = &m.stats; + json!({ + "corners": m.corners.len(), "triangles": m.triangles.len(), "strip_triangles": m.strip_triangles, + "steps": m.steps.len(), "outside_d": s.outside_d, "unlabelled": s.unlabelled, + "split_edges": s.split_edges, "validity": validity, + "labels": {"sharp_wrong": labels.sharp_wrong, "ground_wrong": labels.ground_wrong, "ground_other": labels.ground_other}, + }) + } + Err(e) => json!({"error": format!("{e:?}")}), + }; + lap("mesh"); + probe::take(); + let [points, capped, host_missing] = caps(&build.records, &b.terrain, key, self.options.grid_m); + let mut audit = probe_json(&probe::take()); + for (k, v) in [("grid_m", json!(self.options.grid_m)), ("points", json!(points)), ("capped", json!(capped))] { + audit[k] = v; + } + audit["host_missing"] = json!(host_missing); + lap("audit"); + let mut borders = Map::new(); + for (side, other, east) in + [("west", CellKey { x: key.x - 1, y: key.y }, true), ("north", CellKey { x: key.x, y: key.y - 1 }, false)] + { + let Some(a) = self.built(other) else { continue }; + let faces = neighbours(a.face_cell(), b.face_cell(), east); + let (_, _, records) = records_border(a.records_cell(), b.records_cell(), east, BORDER_STEP); + let (_, [outline, _]) = outline_border((&a.build.records, other), (&build.records, key)); + let meshed = match (&a.mesh, &mesh) { + (Some(ma), Ok(mb)) => Some(mesh_check::border(&a.mesh_cell(ma), &b.mesh_cell(mb), east).0), + _ => None, + }; + let mut named: Vec = faces.iter().map(|f| format!("2: {}", f.what)).take(FIRST).collect(); + named.extend(records.iter().take(FIRST).map(|d| format!("records at {}: {} | {}", d.0, d.1, d.2))); + named.extend(outline.iter().take(FIRST).map(|d| format!("outline: {d}"))); + named.extend(meshed.iter().flatten().take(FIRST).map(|d| format!("mesh: {d}"))); + borders.insert( + side.into(), + json!({"faces": faces.len(), "records": records.len(), "outline": outline.len(), + "mesh": meshed.as_ref().map(Vec::len), "first": named}), + ); + } + lap("borders"); + let times = &build.times; + line["state"] = json!(if mesh.is_ok() { "ok" } else { "mesh_error" }); + line["digest"] = json!(digest); + line["ms"] = json!({"input": times[0], "graph": times[1], "faces": times[2], "mesh": mesh_ms, "checks": self.now() - t1}); + line["check_ms"] = Value::Object(laps); + line["heap"] = json!(b.heap); + line["heap_mesh"] = json!(heap_mesh); + line["rss_kb"] = json!(rss_kb()); + for (k, v) in [ + ("tiles", build.tiles), + ("pages", build.pages), + ("ways", graph.ways.len()), + ("words", build.records.len()), + ("faces", plan.faces.len()), + ("vertices", plan.vertices.len()), + ("edges", plan.edges.len()), + ] { + line[k] = json!(v); + } + line["mesh"] = mesh_json; + line["caps"] = probe_json(&b.probe); + line["audit"] = audit; + line["graph"] = counters(&graph.stats.counters()); + line["face_stats"] = counters(&plan.stats.counters()); + line["checks"] = json!({"partition": faults, "artefacts": thin, "first": first}); + line["borders"] = Value::Object(borders); + if let (Ok(m), Some(Slot::Built(b))) = (mesh, self.cells.get_mut(&key)) { + b.mesh = Some(m); + } + line + } +} + +pub fn run(options: Options) -> Result<(), String> { + std::panic::set_hook(Box::new(|info| { + let message = info + .payload() + .downcast_ref::<&str>() + .map(|s| s.to_string()) + .or_else(|| info.payload().downcast_ref::().cloned()) + .unwrap_or_default(); + let at = info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_default(); + eprintln!("census worker: panic at {at}: {message}"); + emit(&json!({"panic": {"message": message, "at": at}})); + })); + if options.fail.iter().any(|f| f.1 == Fail::Start) { + return Err("a made-up failure before the first cell".into()); + } + let mut text = String::new(); + std::io::stdin().lock().read_line(&mut text).map_err(|e| e.to_string())?; + let job = Job::parse(&text)?; + let mut worker = Worker { + source: Source::open(&options.place)?, + options: &options, + cache: TileCache::new(TILES), + rules: Rules::embedded(), + cells: BTreeMap::new(), + skip: job.skip.into_iter().collect(), + start: Instant::now(), + }; + for key in job.targets { + worker.cells.retain(|k, _| k.y + 1 >= key.y); + for n in around(key) { + worker.ensure(n)?; + } + let line = worker.census(key); + emit(&line); + } + Ok(()) +} diff --git a/host/obc-trailview-features/src/gate.rs b/host/obc-trailview-features/src/gate.rs new file mode 100644 index 0000000000..a7f4837582 --- /dev/null +++ b/host/obc-trailview-features/src/gate.rs @@ -0,0 +1,175 @@ +//! The census gate of a bake: the heights of the ways on the ground and of the rivers and streams +//! against the terrain that the bake reads, which TrailView draws. + +use std::collections::HashSet; + +use serde_json::{json, Value}; + +use crate::geometry::abreast; +use crate::{Part, Terrain}; + +/// Chosen by the owner: a way or water this far off the terrain shows as a wall or a gorge that is +/// not there. +pub const GATE_M: f64 = 10.0; +/// The census counts the offsets in bins of BIN_M up to BINS × BIN_M; the last bin holds all past it. +const BIN_M: f64 = 0.05; +const BINS: usize = 2000; +/// The places that the census names: the worst of each side, one per square of about 100 m. +const WORST: usize = 10; +const PLACE_DEG: f64 = 0.001; + +/// The offsets of a set of vertices from the terrain, height less terrain. +pub struct Census { + vertices: u64, + bins: Vec, + over: u64, + under: u64, + /// The positions of the vertices more than GATE_M off the terrain under their centre line, which the gate + /// does not count (a vertex that several ways share is one), and the largest such distance. + off_centre: HashSet<[u64; 2]>, + off_centre_max_m: f64, + /// (offset, latitude and longitude, kind), the largest above and below. + highest: Vec<(f64, [f64; 2], String)>, + lowest: Vec<(f64, [f64; 2], String)>, +} + +impl Default for Census { + fn default() -> Self { + Census { + vertices: 0, + bins: vec![0; BINS + 1], + over: 0, + under: 0, + off_centre: HashSet::new(), + off_centre_max_m: 0.0, + highest: Vec::new(), + lowest: Vec::new(), + } + } +} + +impl Census { + /// Counts the vertices of `parts` with a height and a known terrain, but those that `skip` marks. The offset + /// of a vertex is how far it lies past the terrain across its way, at it and at ± `half` square to the way: + /// the band of the road solver. + pub fn add( + &mut self, + kind: &str, + parts: &[Part], + half: f64, + terrain: &dyn Terrain, + skip: &dyn Fn([f64; 2]) -> bool, + ) { + for part in parts { + let Some(z) = &part.z else { continue }; + let p = &part.points; + let edges: Vec<[f64; 2]> = (0..p.len()) + .filter(|_| half > 0.0) + .flat_map(|j| abreast(p[j], [p[j.saturating_sub(1)], p[(j + 1).min(p.len() - 1)]], half)) + .collect(); + let sides = terrain.heights(&edges); + for (j, ((&point, &z), ground)) in p.iter().zip(z).zip(terrain.heights(p)).enumerate() { + if !(z - ground).is_finite() || skip(point) { + continue; + } + let [low, high] = sides + .get(2 * j..2 * j + 2) + .unwrap_or_default() + .iter() + .filter(|h| h.is_finite()) + .fold([ground, ground], |[low, high], &h| [low.min(h), high.max(h)]); + let dz = z - z.clamp(low, high); + self.vertices += 1; + self.bins[((dz.abs() / BIN_M) as usize).min(BINS)] += 1; + self.over += u64::from(dz > GATE_M); + self.under += u64::from(dz < -GATE_M); + if (z - ground).abs() > GATE_M { + self.off_centre.insert(point.map(f64::to_bits)); + } + self.off_centre_max_m = self.off_centre_max_m.max((z - ground).abs()); + let at = crate::degrees(point); + keep(&mut self.highest, (dz, at, kind), |a, b| a > b); + keep(&mut self.lowest, (dz, at, kind), |a, b| a < b); + } + } + } + + pub fn over(&self) -> u64 { + self.over + } + + pub fn under(&self) -> u64 { + self.under + } + + /// The positions more than GATE_M off the terrain under their centre line, and the largest distance. + pub fn off_centre(&self) -> (usize, f64) { + (self.off_centre.len(), self.off_centre_max_m) + } + + /// The worst places past the gate above (`high`) or below the terrain, as text. + pub fn places(&self, high: bool) -> String { + let list = if high { &self.highest } else { &self.lowest }; + let past = list.iter().filter(|(dz, _, _)| if high { *dz > GATE_M } else { *dz < -GATE_M }); + past.map(|(dz, [lat, lon], kind)| format!("{lat:.5},{lon:.5} {kind} {dz:+.1} m")).collect::>().join("; ") + } + + pub fn metrics(&self) -> Value { + let share = |past: u64| past as f64 / self.vertices.max(1) as f64; + let percentile = |p: f64| { + let wanted = (p / 100.0 * self.vertices as f64).ceil() as u64; + let mut seen = 0; + let bin = self.bins.iter().position(|&n| { + seen += n; + seen >= wanted.max(1) + }); + (bin.unwrap_or(BINS) as f64 + 1.0) * BIN_M + }; + let over_5 = self.bins[(5.0 / BIN_M) as usize..].iter().sum::(); + json!({"vertices": self.vertices, "over_m": self.over, "under_m": self.under, + "p50_m": percentile(50.0), "p90_m": percentile(90.0), "p99_m": percentile(99.0), + "share_past_5m": (share(over_5) * 1e5).round() / 1e5, + "off_centre_past_gate": self.off_centre.len(), "off_centre_max_m": (self.off_centre_max_m * 10.0).round() / 10.0, + "highest": self.places(true), "lowest": self.places(false)}) + } +} + +/// Keeps the WORST entries of `list` that come first by `before`, one per place of about PLACE_DEG. +fn keep(list: &mut Vec<(f64, [f64; 2], String)>, (dz, at, kind): (f64, [f64; 2], &str), before: fn(f64, f64) -> bool) { + let same = |p: [f64; 2]| (p[0] - at[0]).abs() < PLACE_DEG && (p[1] - at[1]).abs() < PLACE_DEG; + if let Some(k) = list.iter().position(|e| same(e.1)) { + if !before(dz, list[k].0) { + return; + } + list.remove(k); + } + if list.len() == WORST && !before(dz, list[WORST - 1].0) { + return; + } + let at_index = list.iter().position(|e| before(dz, e.0)).unwrap_or(list.len()); + list.insert(at_index, (dz, at, kind.to_string())); + list.truncate(WORST); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_census_counts_the_vertices_past_the_gate_on_each_side_and_names_the_worst() { + let flat = |_: f64, _: f64| 500.0; + let line = |z: Vec| Part { + outer: false, + points: (0..z.len()).map(|i| [0.53 + i as f64 * 1e-5, 0.36]).collect(), + z: Some(z), + plan: None, + }; + let mut census = Census::default(); + census + .add("road", &[line(vec![500.5, 512.0, 499.0, f64::NAN, 470.0, 520.0])], 0.0, &flat, &|p| p[0] > 0.530045); + assert_eq!((census.vertices, census.over(), census.under()), (4, 1, 1)); + assert!(census.places(true).ends_with("road +12.0 m"), "{}", census.places(true)); + assert!(census.places(false).ends_with("road -30.0 m"), "{}", census.places(false)); + assert_eq!(census.metrics()["p50_m"], 1.05); + } +} diff --git a/host/obc-trailview-features/src/geometry.rs b/host/obc-trailview-features/src/geometry.rs index 876518bf4c..bb755333d7 100644 --- a/host/obc-trailview-features/src/geometry.rs +++ b/host/obc-trailview-features/src/geometry.rs @@ -10,6 +10,15 @@ pub fn key([x, y]: [f64; 2]) -> [u64; 2] { [x.to_bits(), y.to_bits()] } +/// The two points `half` metres either side of `p`, square to the line from `a` to `b`; `p` twice where they +/// are one point. +pub fn abreast(p: [f64; 2], [a, b]: [[f64; 2]; 2], half: f64) -> [[f64; 2]; 2] { + let d = [b[0] - a[0], b[1] - a[1]]; + let reach = half / crate::metres(p[1]) / d[0].hypot(d[1]); + let o = if reach.is_finite() { [-d[1] * reach, d[0] * reach] } else { [0.0, 0.0] }; + [[p[0] + o[0], p[1] + o[1]], [p[0] - o[0], p[1] - o[1]]] +} + /// The box (x0, y0, x1, y1) of the points; x0 > x1 of none. pub fn bounds<'a>(points: impl IntoIterator) -> [f64; 4] { points.into_iter().fold([f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY], |b, &[x, y]| { diff --git a/host/obc-trailview-features/src/kinds.rs b/host/obc-trailview-features/src/kinds.rs index 15f3a9b4de..aad3d94968 100644 --- a/host/obc-trailview-features/src/kinds.rs +++ b/host/obc-trailview-features/src/kinds.rs @@ -4,6 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; +use obc_ground_plan::sections::{ClassWidths, FinishWidths, WidthRules}; use serde_json::Value; use crate::roads::{Class, Classes}; @@ -12,9 +13,11 @@ use crate::Tags; const FIELDS: [&str; 7] = ["kind", "geometry", "match", "keep", "height", "min_zoom", "active"]; const HEIGHTS: [&str; 4] = ["surface", "pad", "profile", "none"]; -/// The fields of a road class that the road solver reads. The other fields of the table are the stamp -/// profile of the engine, which `builder/web` checks. -const CLASS_FIELDS: [&str; 10] = [ +/// The fields of a road class that the road solver and the width rule read. The other fields of the +/// table are the stamp profile of the engine, which `builder/web` checks. +const CLASS_FIELDS: [&str; 12] = [ + "half_m", + "shoulder_m", "grade", "smooth_m", "plan_tol_m", @@ -28,9 +31,24 @@ const CLASS_FIELDS: [&str; 10] = [ ]; /// The widest sidewalk: the walk byte of the engine's mask holds no more (`mask-walk.wgsl`). pub const SIDEWALK_MAX_M: f64 = 2.0; +/// The fields of a finish of `data/trailview/finishes.json` that the width rule reads. +const FINISH_FIELDS: [&str; 2] = ["half_m", "shoulder_m"]; /// The fields of a waterway kind that the bake reads: its width without a `width` tag, the cover of a road -/// or a track over a culvert of it, the most that the cover may lift that way, and the longest culvert. -const WATERWAY_FIELDS: [&str; 4] = ["width_m", "cover_m", "cover_lift_max_m", "culvert_max_m"]; +/// or a track over a culvert of it, the most that the cover may lift that way, the longest culvert, the +/// widest water that an untagged way crosses on a culvert, the bank top that the level keeps under: +/// `freeboard_m` under the terrain `bank_m` past the waterline, and the reader's curve of the water's +/// spans (`curve_turn_max_deg`, `curve_off_max_m`), on which the vertices that the levels add lie. +const WATERWAY_FIELDS: [&str; 9] = [ + "width_m", + "cover_m", + "cover_lift_max_m", + "culvert_max_m", + "culvert_width_m", + "freeboard_m", + "bank_m", + "curve_turn_max_deg", + "curve_off_max_m", +]; /// The classes of the tracks. const RAILS: [&str; 5] = ["rail", "light_rail", "narrow_gauge", "rack", "funicular"]; @@ -164,17 +182,69 @@ pub struct Waterway { pub cover_m: f64, pub cover_lift_max_m: f64, pub culvert_max_m: f64, + pub culvert_width_m: f64, + pub freeboard_m: f64, + pub bank_m: f64, + /// A vertex where the water turns by more than this is a corner of its curve. + pub curve_turn_max_deg: f64, + /// A span whose curve leaves its chord by more than this is its chord. + pub curve_off_max_m: f64, +} + +/// Each row of an object table with only the fields of `fields`, in the table's order. +fn rows_of(table: &Value, fields: &[&str]) -> Value { + let rows = table.as_object().into_iter().flatten().map(|(name, row)| { + let kept = row.as_object().into_iter().flatten().filter(|(field, _)| fields.contains(&field.as_str())); + (name.clone(), Value::Object(kept.map(|(field, value)| (field.clone(), value.clone())).collect())) + }); + Value::Object(rows.collect()) } /// The waterway kinds of the step's options: the fields of `WATERWAY_FIELDS` of each `waterway` value of /// the table. The stamp profile is not an option, so a change to it does not bake again. pub fn waterway_rows(table: &Value) -> Value { - let rows = table.as_object().into_iter().flatten().map(|(name, row)| { - let fields = - row.as_object().into_iter().flatten().filter(|(field, _)| WATERWAY_FIELDS.contains(&field.as_str())); - (name.clone(), Value::Object(fields.map(|(field, value)| (field.clone(), value.clone())).collect())) + rows_of(table, &WATERWAY_FIELDS) +} + +/// The rule values that the levels of the ground plan read (`levels`): per class the fields of the way graph and of a +/// way's body (`fill`, `reach`), per waterway kind the fields of the graph, and the `structures` of `plan.json`. They +/// are options of the step, so a change of them bakes again. +pub fn level_rows(roads: &Value, waterways: &Value, plan: &Value) -> Value { + use obc_ground_plan::sections::{GRAPH_FIELDS, WATER_GRAPH_FIELDS}; + let road_fields: Vec<&str> = GRAPH_FIELDS.iter().copied().chain(["fill", "reach"]).collect(); + serde_json::json!({"roads": rows_of(roads, &road_fields), "waterways": rows_of(waterways, &WATER_GRAPH_FIELDS), + "structures": plan["structures"]}) +} + +/// The finishes of the step's options: the fields of `FINISH_FIELDS` of each finish of the table. +pub fn finish_rows(table: &Value) -> Value { + rows_of(table, &FINISH_FIELDS) +} + +/// The width rule of the options: the widths of each class of `solver_rows` and the caps of each +/// finish of `finish_rows`, a `null` cap for none. +pub fn widths(roads: &Value, finishes: &Value) -> Result { + let number = |row: &Value, field: &str| row[field].as_f64().unwrap_or(f64::NAN); + let classes = roads.as_array().into_iter().flatten().map(|row| { + let widths = ClassWidths { + half_m: number(row, "half_m"), + shoulder_m: number(row, "shoulder_m"), + sidewalk_m: number(row, "sidewalk_m"), + }; + (row["class"].as_str().unwrap_or_default().to_string(), widths) }); - Value::Object(rows.collect()) + let mut caps = Vec::new(); + for (name, row) in finishes.as_object().ok_or("The finishes are an object")? { + let cap = |field: &str| match &row[field] { + Value::Null => Ok(None), + value => value.as_f64().map(Some).ok_or(format!("Finish {name:?}: {field} is a number or null")), + }; + if row.as_object().is_none_or(|r| r.len() != FINISH_FIELDS.len()) { + return Err(format!("Finish {name:?}: the fields are {FINISH_FIELDS:?}")); + } + caps.push((name.clone(), FinishWidths { half_m: cap("half_m")?, shoulder_m: cap("shoulder_m")? })); + } + WidthRules::new(classes.collect(), caps) } /// The waterway kinds of `waterway_rows`, or an error that names the first row that breaks a rule. A @@ -186,13 +256,33 @@ pub fn waterways(rows: &Value) -> Result, String> { .map(|(name, row)| { let field = |key: &str| row[key].as_f64().filter(|v| *v >= 0.0); let fields = row.as_object().is_some_and(|r| r.len() == WATERWAY_FIELDS.len()); - let lengths = (field("cover_lift_max_m"), field("culvert_max_m")); - match (fields, field("width_m").filter(|w| *w > 0.0), field("cover_m"), lengths) { - (true, Some(width_m), Some(cover_m), (Some(cover_lift_max_m), Some(culvert_max_m))) => { - Ok((name.clone(), Waterway { width_m, cover_m, cover_lift_max_m, culvert_max_m })) - } + let [width_m, cover_m, cover_lift_max_m, culvert_max_m, culvert_width_m, freeboard_m, bank_m, turn, off] = + WATERWAY_FIELDS.map(field); + let widths = (width_m.filter(|w| *w > 0.0), culvert_width_m.filter(|w| *w > 0.0)); + let lengths = (cover_m, cover_lift_max_m, culvert_max_m, freeboard_m, bank_m); + let curve = (turn.filter(|t| *t <= 180.0), off); + match (fields, widths, lengths, curve) { + ( + true, + (Some(width_m), Some(culvert_width_m)), + (Some(cover_m), Some(cover_lift_max_m), Some(culvert_max_m), Some(freeboard_m), Some(bank_m)), + (Some(curve_turn_max_deg), Some(curve_off_max_m)), + ) => Ok(( + name.clone(), + Waterway { + width_m, + cover_m, + cover_lift_max_m, + culvert_max_m, + culvert_width_m, + freeboard_m, + bank_m, + curve_turn_max_deg, + curve_off_max_m, + }, + )), _ => Err(format!( - "Waterway {name:?}: the fields are {WATERWAY_FIELDS:?}, numbers of 0 or more, a width over 0" + "Waterway {name:?}: the fields are {WATERWAY_FIELDS:?}, numbers of 0 or more, the widths over 0, the turn at most 180" )), } }) @@ -292,12 +382,25 @@ mod tests { let rows = waterway_rows(&table); assert_eq!( waterways(&rows).unwrap()["stream"], - Waterway { width_m: 1.0, cover_m: 1.0, cover_lift_max_m: 1.5, culvert_max_m: 60.0 } + Waterway { + width_m: 1.0, + cover_m: 1.0, + cover_lift_max_m: 1.5, + culvert_max_m: 60.0, + culvert_width_m: 3.0, + freeboard_m: 0.4, + bank_m: 0.6, + curve_turn_max_deg: 60.0, + curve_off_max_m: 2.0 + } ); table["river"]["cut"] = 0.3.into(); assert_eq!(waterway_rows(&table), rows, "the stamp profile is not an option of the step"); - table["river"].as_object_mut().unwrap().remove("cover_m"); - assert!(waterways(&waterway_rows(&table)).is_err()); + for field in ["cover_m", "culvert_width_m"] { + let mut broken = table.clone(); + broken["river"].as_object_mut().unwrap().remove(field); + assert!(waterways(&waterway_rows(&broken)).is_err(), "{field}"); + } } #[test] @@ -314,4 +417,54 @@ mod tests { table["road"]["grade"] = 1.0.into(); assert!(super::classes(&solver_rows(&table)).is_err()); } + + #[test] + fn the_finishes_are_options_of_the_step_and_the_bake_and_the_crate_give_one_width() { + let json = |text: &str| serde_json::from_str::(text).unwrap(); + let roads = solver_rows(&json(include_str!("../../../data/trailview/roads.json"))); + let mut table = json(include_str!("../../../data/trailview/finishes.json")); + let rules = widths(&roads, &finish_rows(&table)).unwrap(); + let crate_rules = obc_ground_plan::sections::Sections::embedded().widths(); + let tag_sets: [&[(&str, &str)]; 12] = [ + &[], + &[("surface", "asphalt")], + &[("surface", "gravel")], + &[("surface", "dirt")], + &[("surface", "grass")], + &[("tracktype", "grade1")], + &[("tracktype", "grade3")], + &[("width", "4.5 m")], + &[("width", "60")], + &[("oneway", "yes")], + &[("gauge", "1000")], + &[("rack", "yes")], + ]; + for row in roads.as_array().unwrap() { + let class = row["class"].as_str().unwrap(); + let key = if RAILS.contains(&class) && class != "rack" { "railway" } else { "highway" }; + for (kind, extra) in ["main-road", "road", "path", "railway"].iter().flat_map(|k| tag_sets.map(|t| (k, t))) + { + let mut tags: Tags = extra.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + if class == "rack" { + tags.insert("railway".into(), "rail".into()); + tags.insert("rack".into(), "yes".into()); + } else { + tags.insert(key.into(), class.into()); + } + assert_eq!(rules.way(kind, &tags, false), crate_rules.way(kind, &tags, false), "{class} {tags:?}"); + } + } + table["gravel"]["shoulder_m"] = 0.35.into(); + assert_ne!(finish_rows(&table), finish_rows(&json(include_str!("../../../data/trailview/finishes.json")))); + let mut extra = table.clone(); + extra["gravel"]["colour"] = "grey".into(); + assert_eq!(finish_rows(&extra), finish_rows(&table), "a field that the bake does not read is no option"); + let mut narrow = roads.clone(); + narrow[0]["half_m"] = 0.3.into(); + assert!(widths(&narrow, &finish_rows(&table)).is_err()); + let mut missing = roads.clone(); + missing[0].as_object_mut().unwrap().remove("shoulder_m"); + let message = widths(&missing, &finish_rows(&table)).unwrap_err(); + assert!(message.contains(r#""rail".shoulder_m: NaN is not a number of 0 or more"#), "{message}"); + } } diff --git a/host/obc-trailview-features/src/levels.rs b/host/obc-trailview-features/src/levels.rs new file mode 100644 index 0000000000..5110ec36c1 --- /dev/null +++ b/host/obc-trailview-features/src/levels.rs @@ -0,0 +1,98 @@ +//! The levels of the ground plan on the zoom-13 tiles of a bake: the states along each road way, its storey and the +//! slab of its deck on ladder step 2, from `graph::levels` on every cell of each tile with a road way, as +//! `obc_ground_plan::graph::level_tags` writes them. The cells read the tiles and the terrain as the viewer does, +//! with the ground plan's own rule tables. + +use std::collections::{BTreeMap, HashMap}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; + +use obc_ground_plan::faces::Rules; +use obc_ground_plan::frame::{CellKey, CELL_ZOOM, FEATURE_ZOOM}; +use obc_ground_plan::graph::{self, level_tags}; +use obc_ground_plan::terrain::{pages_from_heights, StoredPage, Terrain as Pages}; +use obc_ground_plan::tile::TileCache; +use obc_ground_plan::CellInput; + +use crate::tiles::{Tile, Tiles, MAX_ZOOM}; +use crate::{Tags, Terrain}; + +/// The tiles that a job keeps parsed: a cell reads its own tile and up to three about it. +const PARSED: usize = 9; +/// The memory of one job at most: its parsed tiles, its pages and the graph of one cell. +const JOB_BYTES: usize = 400 << 20; + +/// The decoded pages of a terrain tile. +type Quadrants = [Option; 4]; + +/// The tags of each feature id of the zoom-13 tiles, and the number of cells read. A job reads the cells of one +/// tile, as many jobs at once as `memory` holds. +pub fn tags(tiles: &Tiles, terrain: &dyn Terrain, memory: usize) -> (HashMap, usize) { + let rules = Rules::embedded(); + let z13 = |c: u32, r: u32| tiles.tiles.get(&(MAX_ZOOM, c, r)); + let mut jobs: Vec<(u32, u32)> = + (tiles.tiles.iter()).filter(|(k, t)| k.0 == MAX_ZOOM && t.has_ids()).map(|(k, _)| (k.1, k.2)).collect(); + jobs.sort_unstable(); + let threads = std::thread::available_parallelism().map_or(1, usize::from).min(memory / JOB_BYTES).max(1); + let (next, done) = (AtomicUsize::new(0), Mutex::new(Vec::new())); + std::thread::scope(|scope| { + for _ in 0..threads.min(jobs.len()) { + scope.spawn(|| { + while let Some(&(c, r)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let cells = cells_of(c, r, &z13, terrain, rules); + done.lock().unwrap().push(((c, r), cells)); + } + }); + } + }); + // The jobs in the order of their tiles, whatever the order the threads finish them in. + let mut done = done.into_inner().unwrap(); + done.sort_unstable_by_key(|d| d.0); + let id = |[c, r, index]: [u32; 3]| z13(c, r).and_then(|t| t.id(index)); + let mut by_id: BTreeMap> = BTreeMap::new(); + let (mut groups, mut over): (Vec>, Vec<(u32, u32)>) = Default::default(); + for cell in done.into_iter().flat_map(|d| d.1) { + for (key, f) in cell.found { + if let Some(id) = id(key) { + by_id.entry(id).or_default().push(f); + } + } + groups.extend(cell.groups.into_iter().map(|g| g.into_iter().filter_map(id).collect::>())); + over.extend(cell.over.into_iter().filter_map(|(l, u)| Some((id(l)?, id(u)?)))); + } + let tags = level_tags::merge(&by_id, &groups, &over); + (tags.into_iter().collect(), jobs.len() << (2 * (CELL_ZOOM - FEATURE_ZOOM))) +} + +/// What the cells of zoom-13 tile (c, r) find, in the order of the cells. +fn cells_of<'a>( + c: u32, + r: u32, + z13: &dyn Fn(u32, u32) -> Option<&'a Tile>, + terrain: &dyn Terrain, + rules: &Rules, +) -> Vec { + let (mut cache, mut quadrants) = (TileCache::new(PARSED), HashMap::<(u32, u32, u32), Option>::new()); + let n = 1 << (CELL_ZOOM - FEATURE_ZOOM); + let mut out = Vec::new(); + for y in r * n..(r + 1) * n { + for x in c * n..(c + 1) * n { + let key = CellKey { x, y }; + let pages = (Pages::wanted(key).into_iter()) + .filter_map(|page| { + let (z, tx, ty, q) = page.tile(); + let tile = quadrants.entry((z, tx, ty)).or_insert_with(|| { + terrain.tile(z as u8, tx, ty).map(|heights| pages_from_heights(&heights, z, tx, ty)) + }); + tile.as_ref()?[q].clone() + }) + .collect(); + let input = CellInput::new(key, &mut cache, |tc, tr| z13(tc, tr).map(Tile::bytes), pages) + .unwrap_or_else(|e| panic!("the bake's own tile about cell {x}/{y}: {e:?}")); + let mut g = graph::build(key, &input, &rules.sections); + graph::levels(&mut g, &input, &rules.sections, &rules.structures); + out.push(level_tags::found(&g, &input, &rules.sections)); + } + } + out +} diff --git a/host/obc-trailview-features/src/lib.rs b/host/obc-trailview-features/src/lib.rs index c75e68d4f0..17c4688262 100644 --- a/host/obc-trailview-features/src/lib.rs +++ b/host/obc-trailview-features/src/lib.rs @@ -3,25 +3,32 @@ //! lakes ([`water`]), the heights of roads, paths, tracks, bridges and tunnels ([`roads`]) from the //! master terrain ([`terrain`]), the lifts ([`lifts`]), the railway furniture ([`rails`]), the //! bridges and tunnels ([`structures`]) and the sea ([`sea`]), cut into tiles ([`tiles`]) of a -//! PMTiles archive ([`pmtiles`]). `specs/trailview-features.md` defines the archive. +//! PMTiles archive ([`pmtiles`]), after the census of their heights ([`gate`]). +//! `specs/trailview-features.md` defines the archive. use std::collections::BTreeMap; pub mod bake; +mod gate; mod geometry; pub mod kinds; +mod levels; mod lifts; mod osm; mod pmtiles; mod rails; mod roads; mod sea; +pub mod stamps; pub mod step; mod structures; pub mod terrain; mod tiles; mod water; +/// The PMTiles reader, for the census's reads of a release. +pub use pmtiles::Archive; + pub const EQUATOR_M: f64 = 40075016.686; /// Metres per world unit at world row y: the Mercator scale. @@ -34,6 +41,11 @@ pub fn world(lon: f64, lat: f64) -> [f64; 2] { [(lon + 180.0) / 360.0, (1.0 - lat.to_radians().tan().asinh() / std::f64::consts::PI) / 2.0] } +/// Latitude and longitude of a world point. +pub fn degrees([x, y]: [f64; 2]) -> [f64; 2] { + [(std::f64::consts::PI * (1.0 - 2.0 * y)).sinh().atan().to_degrees(), x * 360.0 - 180.0] +} + /// Heights in metres at world points (x, y in [0, 1], y down); NaN where unknown. pub trait Terrain: Sync { fn heights(&self, points: &[[f64; 2]]) -> Vec; @@ -46,12 +58,20 @@ pub trait Terrain: Sync { fn height(&self, point: [f64; 2]) -> f64 { self.heights(&[point])[0] } + + /// The heights of its 512 px tile z/x/y, row by row from north, NaN where unknown; None where it has no tile. + fn tile(&self, z: u8, x: u32, y: u32) -> Option>>; } +/// Heights at points alone: it has no tiles, so the levels of a bake on it read no terrain. impl f64 + Sync> Terrain for F { fn heights(&self, points: &[[f64; 2]]) -> Vec { points.iter().map(|&[x, y]| self(x, y)).collect() } + + fn tile(&self, _z: u8, _x: u32, _y: u32) -> Option>> { + None + } } /// The OSM tags that a feature keeps. diff --git a/host/obc-trailview-features/src/main.rs b/host/obc-trailview-features/src/main.rs index 5f846baf79..1d4faacad6 100644 --- a/host/obc-trailview-features/src/main.rs +++ b/host/obc-trailview-features/src/main.rs @@ -1,6 +1,7 @@ //! `trailview-features --osm OSM.pbf --terrain TERRAIN.mbtiles --bounds W,S,E,N --output OUT.pmtiles -//! [--sea water-polygons-split-3857.zip]`: the archive of a box without `obc data`, with the kind table -//! and the road classes of the checkout and the terrain of a `planner-dem` MBTiles. Prints the metrics. +//! [--sea water-polygons-split-3857.zip]`: the archive of a box without `obc data`, with the kind table, +//! the road classes and the finishes of the checkout, and the terrain of a `planner-dem` MBTiles. +//! Prints the metrics. use std::path::{Path, PathBuf}; @@ -28,14 +29,16 @@ fn run() -> Result<(), String> { let bounds: Vec = bounds.split(',').map(|v| v.parse().map_err(|_| usage.to_string())).collect::>()?; let table = |text: &str| serde_json::from_str::(text).map_err(|e| e.to_string()); - let (class_names, classes) = - kinds::classes(&kinds::solver_rows(&table(include_str!("../../../data/trailview/roads.json"))?))?; + let roads = kinds::solver_rows(&table(include_str!("../../../data/trailview/roads.json"))?); + let finishes = kinds::finish_rows(&table(include_str!("../../../data/trailview/finishes.json"))?); + let (class_names, classes) = kinds::classes(&roads)?; let options = Options { kinds: kinds::validate(&table(include_str!("../../../data/trailview/kinds.json"))?)?, bounds: bounds.try_into().map_err(|_| usage.to_string())?, attribution: "© OpenStreetMap contributors".into(), classes, class_names, + widths: kinds::widths(&roads, &finishes)?, waterways: kinds::waterways(&kinds::waterway_rows(&table(include_str!( "../../../data/trailview/waterways.json" ))?))?, diff --git a/host/obc-trailview-features/src/osm.rs b/host/obc-trailview-features/src/osm.rs index 52b9ea696f..afa0348f56 100644 --- a/host/obc-trailview-features/src/osm.rs +++ b/host/obc-trailview-features/src/osm.rs @@ -17,22 +17,6 @@ pub const LIFT_REACH_M: f64 = 20000.0; const METRES_PER_DEGREE: f64 = 111320.0; /// The landuse areas whose value a building in them keeps as its tag `landuse`. They are not features. pub const LANDUSE: [&str; 2] = ["farmyard", "industrial"]; -/// The uses that a building shows on its walls, as its tag `use`: its own, or that of a point in it or an -/// area about it. One before another in the list wins. -pub const USES: [&str; 3] = ["pharmacy", "hospital", "shop"]; - -/// The use of an object's tags, of USES. -pub fn use_of(tags: &Tags) -> Option<&'static str> { - let is = |key: &str, value: &str| tags.get(key).is_some_and(|v| v == value); - if is("amenity", "pharmacy") || is("healthcare", "pharmacy") { - Some("pharmacy") - } else if is("amenity", "hospital") || is("healthcare", "hospital") { - Some("hospital") - } else { - tags.contains_key("shop").then_some("shop") - } -} - /// The Osmium program: `OBC_OSMIUM`, else `osmium` on the path; and its version. pub fn probe() -> Result<(PathBuf, String), String> { let binary = PathBuf::from(std::env::var_os("OBC_OSMIUM").unwrap_or_else(|| "osmium".into())); @@ -111,14 +95,8 @@ pub fn selected(entries: &[Entry], pbf: &Path, binary: &Path, tiles: &Tiles, wor std::fs::remove_file(&area_pbf).map_err(|e| e.to_string())?; Ok(kept) }; - // A building of the region keeps the landuse of the area that holds it, and shows the use of the - // points in it and the areas about it. - let more = [ - format!("nwr/landuse={}", LANDUSE.join(",")), - "nwr/shop".into(), - "nwr/amenity=pharmacy,hospital".into(), - "nwr/healthcare=pharmacy,hospital".into(), - ]; + // A building of the region keeps the landuse of the area that holds it. + let more = [format!("nwr/landuse={}", LANDUSE.join(","))]; let mut paths = vec![cut("near", area(MAX_ZOOM, LIFT_REACH_M), &active, &more)?]; if let Some(zoom) = low.iter().map(|e| e.min_zoom).min() { paths.push(cut("wide", area(zoom, 0.0), &low, &[])?); @@ -134,13 +112,12 @@ pub fn selected(entries: &[Entry], pbf: &Path, binary: &Path, tiles: &Tiles, wor Ok(out) } -/// What an exported object becomes: a feature of an entry, a landuse area that a building takes -/// its `landuse` from, or a point or an area that a building takes its `use` from. +/// What an exported object becomes: a feature of an entry, or a landuse area that a building takes +/// its `landuse` from. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Selected { Entry(usize), Landuse, - Use, } /// An exported object: what it becomes, the tags that it keeps, and its parts. A ring does not repeat @@ -199,7 +176,6 @@ fn object(entries: &[Entry], feature: &Value) -> Option { None if kind == Geometry::Area && tags.get("landuse").is_some_and(|l| LANDUSE.contains(&l.as_str())) => { (Selected::Landuse, vec!["landuse".to_string()]) } - None if kind != Geometry::Line && use_of(&tags).is_some() => (Selected::Use, Vec::new()), None => return None, }; let point = |v: &Value| -> Option<[f64; 2]> { Some(world(v[0].as_f64()?, v[1].as_f64()?)) }; @@ -231,15 +207,7 @@ fn object(entries: &[Entry], feature: &Value) -> Option { parts } }; - let mut kept: Tags = keep.iter().filter_map(|k| Some((k.clone(), tags.get(k)?.clone()))).collect(); - let shows = match selected { - Selected::Entry(e) => entries[e].kind == "building", - Selected::Use => true, - Selected::Landuse => false, - }; - if let Some(value) = use_of(&tags).filter(|_| shows) { - kept.insert("use".into(), value.into()); - } + let kept: Tags = keep.iter().filter_map(|k| Some((k.clone(), tags.get(k)?.clone()))).collect(); Some((selected, kept, parts)) } diff --git a/host/obc-trailview-features/src/pmtiles.rs b/host/obc-trailview-features/src/pmtiles.rs index 0edddff6ad..a79f0289b4 100644 --- a/host/obc-trailview-features/src/pmtiles.rs +++ b/host/obc-trailview-features/src/pmtiles.rs @@ -192,7 +192,7 @@ pub fn write(path: &Path, tiles: &[(u64, Vec)], header: &Header, metadata: & } /// A PMTiles v3 archive, read on demand. -pub(crate) struct Archive { +pub struct Archive { file: File, gzip: bool, pub(crate) tile_compression: u8, @@ -202,7 +202,7 @@ pub(crate) struct Archive { } impl Archive { - pub(crate) fn open(path: &Path) -> Result { + pub fn open(path: &Path) -> Result { let file = File::open(path).map_err(|e| e.to_string())?; let mut header = [0u8; 127]; file.read_exact_at(&mut header, 0).map_err(|e| e.to_string())?; @@ -269,7 +269,7 @@ impl Archive { } /// The bytes of a tile as the archive stores them, None where it has none. - pub(crate) fn get(&self, z: u8, x: u32, y: u32) -> Result>, String> { + pub fn get(&self, z: u8, x: u32, y: u32) -> Result>, String> { let id = tile_id(z, x, y); let mut leaf; let mut entries = &self.root[..]; diff --git a/host/obc-trailview-features/src/rails.rs b/host/obc-trailview-features/src/rails.rs index e0a97b4a69..2f54fcb56b 100644 --- a/host/obc-trailview-features/src/rails.rs +++ b/host/obc-trailview-features/src/rails.rs @@ -9,7 +9,6 @@ use std::collections::BTreeSet; use rstar::primitives::GeomWithData; use rstar::RTree; -use crate::structures::trim_space; use crate::{metres, Part, Tags}; /// The most metres between two masts of a track, and how far beside the track's middle a mast @@ -48,6 +47,12 @@ fn narrow(tags: &Tags) -> bool { digits.len() <= 4 && digits.parse::().unwrap_or(0) < NARROW_MM } +/// The text without the white space that JavaScript trims before a number: Rust's white space, less +/// U+0085, and U+FEFF. +fn trim_space(text: &str) -> &str { + text.trim_start_matches(|c: char| c.is_whitespace() && c != '\u{85}' || c == '\u{feff}') +} + /// Whether a track runs under a contact wire. pub fn electrified(tags: &Tags) -> bool { matches!(tags.get("electrified").map(String::as_str), Some("contact_line" | "yes")) @@ -203,7 +208,8 @@ pub fn platforms(platforms: &[Vec], tracks: &[Track]) -> Vec (f64, f64, f64) { diff --git a/host/obc-trailview-features/src/roads/align_tests.rs b/host/obc-trailview-features/src/roads/align_tests.rs index c00d3d477c..b1f1d7b61e 100644 --- a/host/obc-trailview-features/src/roads/align_tests.rs +++ b/host/obc-trailview-features/src/roads/align_tests.rs @@ -308,7 +308,8 @@ fn the_ways_over_a_seam_keep_their_tolerances_though_the_two_jobs_round_apart() let (_, classes) = table(); let (_, mut tight) = table(); tight.rows.iter_mut().for_each(|row| row.keep_m = 0.005); - for layout in 0..48 { + // Every 4th of 48 layouts, and layout 1: the deepest sag of the 48. + for layout in (0..48).step_by(4).chain([1]) { // Long ways: a job holds a stroke that its neighbour cuts elsewhere, so a tangent can round apart. let (ways, length) = (7, 900.0); let from = seam(&place) - 3.5 * length + 13.0 * layout as f64; @@ -406,6 +407,7 @@ fn a_vertex_shared_with_a_river_stays_and_lies_on_a_whole_tile_unit() { half: 1.0, cover: 1.0, lift: 1.5, + untagged_culvert: true, }; let solved = run(&[road], &flat, &[river]); let way = solved.ways[0][0].as_ref().unwrap(); diff --git a/host/obc-trailview-features/src/roads/fit.rs b/host/obc-trailview-features/src/roads/fit.rs index 4c31617633..b051cf1995 100644 --- a/host/obc-trailview-features/src/roads/fit.rs +++ b/host/obc-trailview-features/src/roads/fit.rs @@ -9,7 +9,7 @@ use faer::sparse::linalg::cholesky::{factorize_symbolic_cholesky, SymmetricOrder use faer::sparse::{SparseColMatRef, SymbolicSparseColMatRef}; use faer::{Conj, MatMut, Par, Side}; -use super::{REFINE_M, REFINE_STEPS}; +use super::{ARMIJO, BISECTIONS, FINAL_ROUNDS, REFINE_M, REFINE_STEPS, ROUNDS, SETTLE_M}; /// Sparse rows: per row, its (variable, coefficient) entries. #[derive(Clone)] @@ -42,15 +42,6 @@ impl Rows { (self.ptr[i]..self.ptr[i + 1]).map(|e| (self.col[e], self.val[e])) } - /// The rows that `keep` marks. - pub fn select(&self, keep: &[bool]) -> Rows { - let mut out = Rows::default(); - for i in (0..self.len()).filter(|&i| keep[i]) { - out.push(self.row(i)); - } - out - } - /// A · z. pub fn times(&self, z: &[f64]) -> Vec { (0..self.len()).map(|i| self.row(i).map(|(c, v)| v * z[c]).sum()).collect() @@ -58,6 +49,7 @@ impl Rows { } /// The rows of a term: sparse rows, or a row (1 − t)·z_a + t·z_b per terrain sample on its segment. +#[derive(Clone, Copy)] pub(crate) enum Block<'a> { Rows(&'a Rows), Samples { seg: &'a [usize], t: &'a [f64], a: &'a [usize], b: &'a [usize] }, @@ -71,6 +63,13 @@ impl Block<'_> { } } + /// Its row i times z. + fn at(&self, i: usize, z: &[f64]) -> f64 { + let mut sum = 0.0; + self.each(i, |v, c| sum += c * z[v]); + sum + } + fn each(&self, i: usize, mut f: impl FnMut(usize, f64)) { match self { Block::Rows(rows) => rows.row(i).for_each(|(col, val)| f(col, val)), @@ -144,6 +143,17 @@ impl Stack<'_> { /// times the heights. GMRES with that factorization then solves against the residuals of the rows, /// which keep it. pub(crate) fn fit(terms: &[Term], n: usize, from: Option<(&[f64], &[usize])>) -> (Vec, bool) { + let rows = (0..terms.len()).flat_map(|k| (0..terms[k].block.len()).map(move |i| (k as u32, i as u32))); + fit_rows(terms, n, from, rows) +} + +/// `fit` with the rows of the terms that may hold a variable that moves: (term, row). +fn fit_rows( + terms: &[Term], + n: usize, + from: Option<(&[f64], &[usize])>, + candidates: impl Iterator, +) -> (Vec, bool) { let (m, local) = match from { None => (n, (0..n).collect::>()), Some((_, moved)) => { @@ -155,20 +165,19 @@ pub(crate) fn fit(terms: &[Term], n: usize, from: Option<(&[f64], &[usize])>) -> } }; let (mut rows, mut c) = (Vec::new(), Vec::new()); - for (k, term) in terms.iter().enumerate() { - for i in 0..term.block.len() { - let mut moves = false; - term.block.each(i, |col, _| moves |= local[col] != usize::MAX); - if !moves { - continue; - } - let mut target = term.c[i]; - if let Some((z, _)) = from { - term.block.each(i, |col, val| target -= val * z[col]); - } - rows.push((k as u32, i as u32)); - c.push(target); + for (k, i) in candidates { + let (term, i) = (&terms[k as usize], i as usize); + let mut moves = false; + term.block.each(i, |col, _| moves |= local[col] != usize::MAX); + if !moves { + continue; } + let mut target = term.c[i]; + if let Some((z, _)) = from { + term.block.each(i, |col, val| target -= val * z[col]); + } + rows.push((k, i as u32)); + c.push(target); } let stack = Stack { terms, rows, local, m, c }; let solver = Solver::new(&stack); @@ -190,6 +199,307 @@ pub(crate) fn fit(terms: &[Term], n: usize, from: Option<(&[f64], &[usize])>) -> } } +/// Per variable, the rows of some blocks that hold it: (block, row). +struct Holders { + ptr: Vec, + rows: Vec<(u32, u32)>, +} + +impl Holders { + fn new(blocks: &[Block], n: usize) -> Holders { + let mut ptr = vec![0usize; n + 1]; + for block in blocks { + (0..block.len()).for_each(|i| block.each(i, |v, _| ptr[v + 1] += 1)); + } + for v in 0..n { + ptr[v + 1] += ptr[v]; + } + let (mut fill, mut rows) = (ptr.clone(), vec![(0, 0); ptr[n]]); + for (k, block) in blocks.iter().enumerate() { + for i in 0..block.len() { + block.each(i, |v, _| { + rows[fill[v]] = (k as u32, i as u32); + fill[v] += 1; + }); + } + } + Holders { ptr, rows } + } + + /// The rows that hold a variable of `region`, each once, in order. + fn of(&self, region: &[usize]) -> Vec<(u32, u32)> { + let mut out: Vec<(u32, u32)> = + region.iter().flat_map(|&v| &self.rows[self.ptr[v]..self.ptr[v + 1]]).copied().collect(); + out.sort_unstable(); + out.dedup(); + out + } +} + +/// Limits: rows A·z with a band from `lo(z)` to `hi` and a cost per square metre past it; a row of cost 0 +/// does not act. A lower bound may follow heights that its row does not move. +pub(crate) struct Limits<'a> { + pub rows: &'a Rows, + pub lo: &'a dyn Fn(&[f64]) -> Vec, + pub hi: &'a [f64], + pub cost: &'a [f64], +} + +/// The distance of x past the band from lo to hi, signed: positive above, negative below. +fn past(x: f64, lo: f64, hi: f64) -> f64 { + x - x.max(lo).min(hi) +} + +/// Moves z on the variables `moved` towards the minimum of the cost: the least squares of `terms` plus, per limit, +/// its cost times the square of its distance past its band. Damped Newton rounds for each of `scales`, which +/// multiply the costs: soft costs find the limits that act in a few rounds, and each next scale starts from +/// there. A round solves the quadratic model of the cost at z, in which each limit past its band pulls to the +/// bound that it passed, and each piece of the network that the solve moves steps along it as far as its cost +/// falls. With fixed bands the cost is convex with a continuous slope, so it falls in every round; a lower +/// bound that follows other heights (`Limits::lo`) changes between rounds. The first round of a scale solves +/// all of `moved`; the next ones only within `reach` in `graph` of the limits that changed side and of the +/// pieces that did not take a full step. A scale ends where a Newton step of each variable alone, from the rows +/// that hold it, would move none by SETTLE_M (`unsettled`), or after ROUNDS, FINAL_ROUNDS at the last scale. +/// The stop rule is local: on a long stiff piece, such as a deck, a joint move of metres can remain open where no +/// variable alone would move by SETTLE_M, so a job can stop metres from the minimum, and where it stops depends on +/// the start that the earlier scale gives. +pub(crate) fn settle( + terms: &[Term], + limits: &Limits, + z: &mut [f64], + moved: &[usize], + (graph, reach): (&Graph, f64), + scales: &[f64], +) -> Settled { + let (mut rounds, mut unconverged, mut capped) = (0, 0, Vec::new()); + let n = z.len(); + let mut inside = vec![false; n]; + moved.iter().for_each(|&v| inside[v] = true); + // The rows of each term and of the limits, last, that hold each variable. + let mut blocks: Vec = terms.iter().map(|t| t.block).collect(); + blocks.push(Block::Rows(limits.rows)); + let holders = Holders::new(&blocks, n); + let last = terms.len() as u32; + let excess = |i: usize, x: f64, lo: &[f64]| (x - limits.hi[i]).max(lo[i] - x); + for (k, &scale) in scales.iter().enumerate() { + let region_of = |sources: Vec| { + let distance = graph.distances(sources.into_iter().map(|v| (v, 0.0)), reach); + (0..n).filter(|&v| inside[v] && distance[v].is_finite()).collect::>() + }; + let mut region = region_of(unsettled(terms, limits, z, scale, moved)); + let mut step: f64 = 0.0; + let cap = if k + 1 == scales.len() { FINAL_ROUNDS } else { ROUNDS }; + for _ in 0..cap { + if region.is_empty() { + break; + } + let held = holders.of(®ion); + let lo = (limits.lo)(z); + // The limits that hold a variable of the region, their values, and those past their band. + let near: Vec = + held.iter().filter(|r| r.0 == last).map(|r| r.1 as usize).filter(|&i| limits.cost[i] > 0.0).collect(); + let x: Vec = near.iter().map(|&i| blocks[last as usize].at(i, z)).collect(); + // The model holds each limit past its band at z at the bound that it passed. + let chosen: Vec = (0..near.len()).filter(|&j| excess(near[j], x[j], &lo) > 0.0).collect(); + let mut rows = Rows::default(); + chosen.iter().for_each(|&j| rows.push(limits.rows.row(near[j]))); + let bound: Vec = chosen + .iter() + .map(|&j| if x[j] > limits.hi[near[j]] { limits.hi[near[j]] } else { lo[near[j]] }) + .collect(); + let w: Vec = chosen.iter().map(|&j| scale * limits.cost[near[j]]).collect(); + let mut model: Vec = terms.iter().map(|t| Term { block: t.block, w: t.w, c: t.c }).collect(); + model.push(Term { block: Block::Rows(&rows), w: &w, c: &bound }); + let candidates = + held.iter().copied().filter(|r| r.0 != last).chain((0..rows.len()).map(|j| (last, j as u32))); + let (next, converged) = fit_rows(&model, n, Some((&*z, ®ion[..])), candidates); + unconverged += usize::from(!converged); + let d: Vec = next.iter().zip(z.iter()).map(|(next, z)| next - z).collect(); + let (piece, alphas) = steps(terms, limits, scale, (z, &d), (&near, &x, &lo), (&held, ®ion)); + step = 0.0; + for &v in ®ion { + z[v] += alphas[piece[v]] * d[v]; + step = step.max((alphas[piece[v]] * d[v]).abs()); + } + rounds += 1; + // The limits that changed side, by more than a tenth of SETTLE_M in or out, and the pieces that + // stopped short start the next region. A lower bound that follows other heights may change too. + let lo_now = (limits.lo)(z); + let mut changed: Vec = (0..near.len()) + .filter(|&j| { + let (was, is) = + (excess(near[j], x[j], &lo), excess(near[j], blocks[last as usize].at(near[j], z), &lo_now)); + (was > 0.0) != (is > 0.0) && (is - was).abs() > SETTLE_M / 10.0 + }) + .map(|j| near[j]) + .collect(); + changed.extend((0..lo.len()).filter(|&i| limits.cost[i] > 0.0 && lo_now[i] != lo[i]).filter(|&i| { + let x = blocks[last as usize].at(i, z); + (excess(i, x, &lo) > 0.0) != (excess(i, x, &lo_now) > 0.0) + })); + let mut sources: Vec = changed.iter().flat_map(|&i| limits.rows.row(i).map(|(v, _)| v)).collect(); + // A piece where the model's step does not fall at all is settled within the solve's precision. + sources.extend( + region + .iter() + .filter(|&&v| alphas[piece[v]] > 0.0 && ((1.0 - alphas[piece[v]]) * d[v]).abs() >= SETTLE_M), + ); + // Where the regions settle, the rest of the network may not have: the next region is around the + // heights that a step would still move. + if sources.is_empty() { + sources = unsettled(terms, limits, z, scale, moved); + } + region = region_of(sources); + } + capped.push((!region.is_empty()).then_some((step, region.len()))); + } + Settled { rounds, unconverged, capped } +} + +/// What `settle` did: its rounds, the refinements that did not converge, and per scale, where it ended at its +/// round cap and not at its stop rule, the largest move of its last round and the variables still unsettled. +/// Neither the last move nor the stop rule bounds how far the heights are from the minimum. +pub(crate) struct Settled { + pub rounds: usize, + pub unconverged: usize, + pub capped: Vec>, +} + +/// The variables of `moved` that a Newton step of each alone would move by SETTLE_M or more, for a fall of the +/// cost of SETTLE_M² or more: the slope of the cost at it over its curvature, both from the rows that hold it. +fn unsettled(terms: &[Term], limits: &Limits, z: &[f64], scale: f64, moved: &[usize]) -> Vec { + let n = z.len(); + let (mut slope, mut curve) = (vec![0.0; n], vec![0.0; n]); + for term in terms { + for i in 0..term.block.len() { + let p = term.block.at(i, z) - term.c[i]; + term.block.each(i, |v, c| { + slope[v] += term.w[i] * p * c; + curve[v] += term.w[i] * c * c; + }); + } + } + let (lo, x) = ((limits.lo)(z), limits.rows.times(z)); + for i in (0..x.len()).filter(|&i| limits.cost[i] > 0.0) { + let beyond = past(x[i], lo[i], limits.hi[i]); + if beyond != 0.0 { + let w = scale * limits.cost[i]; + limits.rows.row(i).for_each(|(v, c)| { + slope[v] += w * beyond * c; + curve[v] += w * c * c; + }); + } + } + let far = |v: usize| { + curve[v] > 0.0 && slope[v].abs() >= SETTLE_M * curve[v] && slope[v].powi(2) >= SETTLE_M.powi(2) * curve[v] + }; + moved.iter().copied().filter(|&v| far(v)).collect() +} + +/// The pieces of `region` that the rows `held` tie, per variable, and per piece how far along z + α·d, +/// 0 ≤ α ≤ 1, its cost falls: to where its slope turns positive, or all the way where that falls enough. No row +/// ties two pieces, so each steps alone. +/// Per piece, the slope is linear in α for the least squares and grows with α for the limits `near`. +fn steps( + terms: &[Term], + limits: &Limits, + scale: f64, + (z, d): (&[f64], &[f64]), + (near, x, lo): (&[usize], &[f64], &[f64]), + (held, region): (&[(u32, u32)], &[usize]), +) -> (Vec, Vec) { + let n = z.len(); + let mut slot = vec![usize::MAX; n]; + region.iter().enumerate().for_each(|(k, &v)| slot[v] = k); + let mut parent: Vec = (0..region.len()).collect(); + let last = Block::Rows(limits.rows); + let block = |k: u32| if (k as usize) < terms.len() { terms[k as usize].block } else { last }; + for &(k, i) in held { + let mut first = None; + block(k).each(i as usize, |v, _| { + if slot[v] != usize::MAX { + match first { + None => first = Some(slot[v]), + Some(f) => super::rows::union(&mut parent, f, slot[v]), + } + } + }); + } + let mut number = vec![usize::MAX; region.len()]; + let mut count = 0; + let mut piece = vec![0; n]; + for (k, &v) in region.iter().enumerate() { + let root = super::rows::root(&mut parent, k); + if number[root] == usize::MAX { + number[root] = count; + count += 1; + } + piece[v] = number[root]; + } + // The piece of a row: that of a variable of the region that it holds. + let of = |block: Block, i: usize| { + let mut found = 0; + block.each(i, |v, _| { + if slot[v] != usize::MAX { + found = piece[v]; + } + }); + found + }; + let (mut s0, mut s1) = (vec![0.0; count], vec![0.0; count]); + for &(k, i) in held.iter().filter(|r| (r.0 as usize) < terms.len()) { + let (term, i) = (&terms[k as usize], i as usize); + let q = term.block.at(i, d); + if q != 0.0 { + let p = term.block.at(i, z) - term.c[i]; + let k = of(term.block, i); + s0[k] += term.w[i] * p * q; + s1[k] += term.w[i] * q * q; + } + } + let q: Vec = near.iter().map(|&i| last.at(i, d)).collect(); + let mut acting: Vec> = vec![Vec::new(); count]; + for j in (0..near.len()).filter(|&j| q[j] != 0.0) { + acting[of(last, near[j])].push(j); + } + let beyond = |j: usize, alpha: f64| past(x[j] + alpha * q[j], lo[near[j]], limits.hi[near[j]]); + let alphas = (0..count) + .map(|k| { + let slope = |alpha: f64| { + let pull: f64 = acting[k].iter().map(|&j| limits.cost[near[j]] * beyond(j, alpha) * q[j]).sum(); + s0[k] + alpha * s1[k] + scale * pull + }; + // The fall of the cost at 1, from the change of each row. + let fall = { + let change: f64 = acting[k] + .iter() + .map(|&j| limits.cost[near[j]] * (beyond(j, 1.0).powi(2) - beyond(j, 0.0).powi(2))) + .sum(); + s0[k] + s1[k] / 2.0 + scale * change / 2.0 + }; + // A step that saves less than moving a metre of way by SETTLE_M is within the solve's precision. + if -slope(0.0) < SETTLE_M * SETTLE_M { + return 0.0; + } + // A full step that falls by ARMIJO of its slope is taken whole: a step short of 1 makes more rounds. + if slope(1.0) <= 0.0 || fall <= ARMIJO * slope(0.0) { + return 1.0; + } + let (mut low, mut high) = (0.0, 1.0); + for _ in 0..BISECTIONS { + let mid = (low + high) / 2.0; + if slope(mid) > 0.0 { + high = mid; + } else { + low = mid; + } + } + low + }) + .collect(); + (piece, alphas) +} + /// The LDLᵀ factorization of the normal matrix Aᵀ·W·A, in a fill-reducing order. struct Solver { symbolic: faer::sparse::linalg::cholesky::SymbolicCholesky, @@ -462,3 +772,54 @@ impl Graph { distance } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Heights 1 m apart pulled to a terrain with a spike of 20 m, grades of 10 % and a ground band of ±5 m: at the + /// spike the grades and the band cannot both hold. From any start, the rounds end at one minimum, where the + /// slope of the cost is 0 and a limit pushes only where its row lies past its band. + #[test] + fn settle_ends_at_the_minimum_of_the_cost_from_any_start() { + let h = [0.0, 0.0, 0.0, 0.0, 20.0, 0.0, 0.0, 0.0, 0.0]; + let n = h.len(); + let mut pull = Rows::default(); + (0..n).for_each(|v| pull.push([(v, 1.0)])); + let w = vec![1.0; n]; + let terms = [Term { block: Block::Rows(&pull), w: &w, c: &h }]; + let (mut rows, mut lo, mut hi, mut cost) = (Rows::default(), Vec::new(), Vec::new(), Vec::new()); + for v in 0..n - 1 { + rows.push([(v, -1.0), (v + 1, 1.0)]); + lo.push(-0.1); + hi.push(0.1); + cost.push(1e4); + } + for (v, &hv) in h.iter().enumerate() { + rows.push([(v, 1.0)]); + lo.push(hv - 5.0); + hi.push(hv + 5.0); + cost.push(1e2); + } + let lows = |_: &[f64]| lo.clone(); + let limits = Limits { rows: &rows, lo: &lows, hi: &hi, cost: &cost }; + let graph = Graph::new(n, &(0..n - 1).map(|v| (v, v + 1, 1.0)).collect::>()); + let all: Vec = (0..n).collect(); + let mut ends = Vec::new(); + for start in [h.to_vec(), vec![-30.0; n], vec![50.0; n], vec![5.0; n]] { + let mut z = start; + settle(&terms, &limits, &mut z, &all, (&graph, 300.0), &[1e-2, 1.0]); + let x = rows.times(&z); + let mut slope: Vec = (0..n).map(|v| 2.0 * (z[v] - h[v])).collect(); + for i in 0..rows.len() { + rows.row(i).for_each(|(v, c)| slope[v] += 2.0 * cost[i] * past(x[i], lo[i], hi[i]) * c); + } + assert!(slope.iter().all(|s| s.abs() < 1e-6), "{slope:?}"); + ends.push(z); + } + assert!(ends.iter().all(|z| z.iter().zip(&ends[0]).all(|(a, b)| (a - b).abs() < 1e-6)), "{ends:?}"); + // The band, which costs less, gives way to the grades: the spike passes it by more than a metre. + let x = rows.times(&ends[0]); + assert!(past(x[n - 1 + 4], lo[n - 1 + 4], hi[n - 1 + 4]) < -1.0); + } +} diff --git a/host/obc-trailview-features/src/roads/mod.rs b/host/obc-trailview-features/src/roads/mod.rs index f725477427..d221c8b9f5 100644 --- a/host/obc-trailview-features/src/roads/mod.rs +++ b/host/obc-trailview-features/src/roads/mod.rs @@ -3,16 +3,20 @@ //! //! A way is sampled every SAMPLE_M metres. Its heights minimise Σ wᵢ(zᵢ − hᵢ)² + λ·Σ Δgrade² / s, //! with Huber weights wᵢ, so that a spike or a gully of the terrain does not move the road, and -//! λ = smooth_m⁴ of its class. No segment is steeper than the grade of its class. Ways that share a +//! λ = smooth_m⁴ of its class. A way on the ground lies within GROUND_M of the terrain across its width, and +//! no other segment is steeper than the grade of its class. Ways that share a //! vertex share its height, and a side road leaves a junction on the surface of the through road. A //! bridge or a tunnel ignores the terrain under it and runs between its ends, a tunnel in a straight //! line; a bridge never sags under the straight line between its ends, and rises where it would pass //! too low over the river, the road, the path or the track that it crosses; a short bridge that lies //! on the terrain is a culvert and does not. A tunnel sinks under a road, a path or a track that //! crosses over it, which does not move. Of two bridges that cross, the one of the higher layer -//! passes over the other, at one layer the better class, and of one class the later one. A ford lies -//! FORD_M below the water it crosses. Tracks side by side, as OSM maps each track of a double line, -//! lie at one height: their beds are one bed. A track on a ramp beside another keeps its own height. +//! passes over the other, at one layer the better class, and of one class the later one. A path's ford, +//! and a ford over water wider than a culvert's, lies FORD_M below the water it crosses, and a road, a +//! track or a railway on the ground lies over the cover of a culvert part or of narrow water that it +//! crosses, tagged as a ford or not. Tracks side by side, as OSM maps each track of a double line, +//! lie at one height: their beds are one bed. So do roads and paths whose carriageways overlap. A way +//! on a ramp beside another keeps its own height. //! Each solve ends with the alignment of its ways (`align`): a fitted plan, and the vertices that hold it. mod align; @@ -27,21 +31,21 @@ mod sidewalks; #[cfg(test)] mod tests; -use std::collections::{BTreeSet, HashSet}; +use std::collections::{BTreeSet, HashMap, HashSet}; use rstar::RTree; pub use align::polyline; pub use area::{context, solve_by_area}; -use fit::{fit, Block, Graph, Rows, Term}; +use fit::{fit, settle, Block, Graph, Limits, Rows, Term}; use network::{hypot, sub, Network}; use rows::union; use sidewalks::Town; pub use sidewalks::Walks; -use crate::geometry::{key, percentile}; +use crate::geometry::{abreast, key, percentile}; use crate::structures::{BORE_M, BORE_PATH_M, BORE_RAIL_M}; -use crate::{metres, Plan, Terrain}; +use crate::{degrees, metres, Plan, Terrain}; const SAMPLE_M: f64 = 2.0; /// While it solves, a way has a vertex at least every VERTEX_M. @@ -50,7 +54,19 @@ const VERTEX_M: f64 = 10.0; /// that meets a path, for APPROACH_PATH_M. const APPROACH_M: f64 = 4.0; const APPROACH_PATH_M: f64 = 1.5; +/// A way without a grade limit leaves a road with one as a ramp: for RAMP_M from the junction its +/// grade differs from the terrain's under it by at most RAMP_GRADE, the owner's choice for a path. +/// The ramps are solved last, with all else fixed, so a ramp never moves a road. Where the terrain +/// is unknown, a way has no ramp. +const RAMP_M: f64 = 15.0; +const RAMP_GRADE: f64 = 0.25; +/// The grade of a tunnel of a class without one (a path, a funicular): 1:1, which stops a step and no slope that +/// a way climbs; the terrain's rise between its portals raises it where that is steeper. +const TUNNEL_GRADE: f64 = 1.0; const HUBER_M: f64 = 1.0; +/// A way on the ground lies within GROUND_M of the terrain across its width: half the census gate of the bake +/// (`gate::GATE_M`), which leaves room for the curve between the samples. +const GROUND_M: f64 = 5.0; pub const FORD_M: f64 = 0.2; /// A bridge shorter than CULVERT_M that lies no higher than CULVERT_RISE_M over the terrain is a /// road over a culvert. @@ -66,9 +82,10 @@ pub const DECK_M: f64 = 1.0; pub const DECK_PATH_M: f64 = 0.4; /// A road or a path over a tunnel lies at least this far over its bore. pub const COVER_M: f64 = 1.0; -/// A track within PARALLEL_M beside another, and within PARALLEL_COS of its direction, lies at its -/// height, unless the terrain under the two differs by more than PARALLEL_RISE_M within -/// PARALLEL_FREE_M along it: a ramp or a flyover, whose climb the smoothing of a track spreads that far. +/// A track within PARALLEL_M beside another, or a road or path whose carriageway overlaps another's, +/// and within PARALLEL_COS of its direction, lies at its height, unless the terrain under the two +/// differs by more than PARALLEL_RISE_M within PARALLEL_FREE_M along it: a ramp or a flyover, whose +/// climb the smoothing of a track spreads that far. const PARALLEL_M: f64 = 6.0; const PARALLEL_COS: f64 = 0.9; const PARALLEL_RISE_M: f64 = 0.5; @@ -78,18 +95,39 @@ const PARALLEL_FREE_M: f64 = 100.0; /// tunnel the preference for level, so that one that meets a road at one end only is level from there. const FREE: f64 = 1e-4; const PIN: f64 = 1e8; +/// The weight of a row that holds a tunnel on the straight line between the ends of its chain. It is a value +/// from a window, not from a rule: a lighter line lets a side tunnel lift the line out of the mountain, and a +/// heavier one is a lever that carries a pass or a slope at one portal to the other. +const BORE: f64 = 1e3; const LEVEL: f64 = 1e-3; +/// The cost of a limit per square metre past its band: GROUND for the ground of a sample, LIMIT for a +/// grade, a deck, a cover and a pass, and HARD for a sample HARD_M off the terrain. So the ground gives way +/// to the other limits, and past HARD_M only to a pin, which costs as much: HARD_M is the census gate +/// (`gate::GATE_M`) less room for the curve between the samples. A factor of 100 between the tiers lets each +/// win over the one below. +const GROUND: f64 = 1e4; +const LIMIT: f64 = 1e6; +const HARD: f64 = 1e8; +const HARD_M: f64 = 8.0; +/// The Newton rounds run with the costs times each scale in turn: soft costs find the limits that act in a +/// few rounds, and each next scale starts from there. +const SCALES: [f64; 2] = [1e-2, 1.0]; /// GMRES refines each solve to REFINE_M, in at most REFINE_STEPS steps. const REFINE_M: f64 = 1e-6; const REFINE_STEPS: usize = 30; -/// Solves of the whole network, the first ones with the Huber weights of the solve before. Then -/// rounds of the slope limits solve only the network within REGION_M of the segments whose limit -/// changed, and the bridges and tunnels it meets: the terrain anchors the rest. -const SOLVES: usize = 2; +/// The Newton rounds of a scale end when a Newton step of each vertex alone would move none by SETTLE_M, or +/// after ROUNDS (`Metrics::capped`), FINAL_ROUNDS at the last scale, whose heights are the result. The stop rule +/// is local, so a job can end metres from the minimum of its cost, capped or not, and the start that the earlier +/// scale gives changes where. The rounds after the first solve only the network within REGION_M of the limits +/// that changed side, and the bridges and tunnels that it meets: the terrain anchors the rest. const ROUNDS: usize = 40; +const FINAL_ROUNDS: usize = 80; +const SETTLE_M: f64 = 1e-2; const REGION_M: f64 = 300.0; -/// The grade excess in metres that a segment may have before it holds its limit. -const TOLERANCE_M: f64 = 1e-3; +/// Halvings of the step in the line search, and the share of its slope by which a full step must cut the +/// cost to be taken whole (the usual Armijo value). +const BISECTIONS: usize = 40; +const ARMIJO: f64 = 1e-4; /// The cell of the grid of the crossings in world units, about 100 m. const GRID_UNITS: f64 = 2.5e-6; @@ -128,13 +166,17 @@ pub struct Feature { pub free: bool, pub tunnel: bool, pub ford: bool, + /// A path over stepping stones: no ford, it keeps its height. + pub stones: bool, /// Its OSM `layer`, 0 without one, and whether it has one. pub layer: i64, pub layered: bool, /// A way on the ground of a negative `layer` without a `tunnel` tag lies under something that the /// solver does not model, such as a station hall: no way on the ground passes over or under it. pub indoor: bool, + /// The carriageway's half-width, and the outer half-width of its outermost band. pub half: f64, + pub outer: f64, /// Per side, left and right of its direction, whether OSM tags a sidewalk there; None where the /// bake decides. A way that can have none has `Some(false)` on both. pub sidewalks: [Option; 2], @@ -143,8 +185,9 @@ pub struct Feature { pub parts: Vec>, } -/// A solved waterway: its points and their levels, NaN where unknown, its half-width, and the cover of a -/// road or a track over it at a culvert with the most that the cover may lift that way. +/// A solved waterway: its points and their levels, NaN where unknown, its half-width, the cover of a +/// road or a track over it at a culvert with the most that the cover may lift that way, and whether it +/// is narrow enough that a way on the ground crosses it on a culvert without a tag. #[derive(Clone, Debug)] pub struct River { pub points: Vec<[f64; 2]>, @@ -152,6 +195,7 @@ pub struct River { pub half: f64, pub cover: f64, pub lift: f64, + pub untagged_culvert: bool, } /// What the ways of a region meet besides the terrain: the solved waterways, the culvert parts with the @@ -203,6 +247,12 @@ pub struct Metrics { pub fords: usize, pub culverts: usize, pub rounds: usize, + /// Per scale of SCALES, the jobs whose Newton rounds ended at their cap, not at their stop rule, the largest + /// move of their last round and the variables still unsettled. Neither the last move nor the stop rule bounds + /// how far the heights are from the minimum. + pub capped: [usize; SCALES.len()], + pub capped_step_m: [f64; SCALES.len()], + pub capped_left: [usize; SCALES.len()], pub held: usize, pub clearances: usize, pub clearances_low_cm: usize, @@ -212,16 +262,28 @@ pub struct Metrics { /// Where the grade excess is largest: latitude, longitude. pub grade_excess_at: [f64; 2], pub grade_excess_over_1cm: usize, + /// The samples that the ground holds GROUND_M off the terrain. + pub grounded: usize, pub residual_p99_m: f64, pub refinements_unconverged: usize, pub covers: usize, pub covers_lifted: usize, + /// The cover rows of untagged culverts, and those that lift their way. + pub covers_untagged: usize, + pub covers_untagged_lifted: usize, + /// Tagged cover rows of a way on the ground or a culvert whose lift would pass the most of their + /// water: the way keeps its height. + pub covers_capped: usize, + /// The same for the cover rows of untagged culverts. + pub covers_untagged_capped: usize, + /// The largest lift of a lifted cover row over the first solve. + pub cover_lift_top_m: f64, pub sidewalks: Walks, } impl Metrics { - /// The metrics of two jobs: the counts add up; `rounds` and `residual_p99_m` are the largest, and so - /// is the grade excess, with its place. + /// The metrics of two jobs: the counts add up; `rounds`, `capped_step_m`, `residual_p99_m` and + /// `cover_lift_top_m` are the largest, and so is the grade excess, with its place. pub fn add(&mut self, other: &Metrics) { let sums = [ (&mut self.ways, other.ways), @@ -236,16 +298,27 @@ impl Metrics { (&mut self.passes, other.passes), (&mut self.passes_near_cm, other.passes_near_cm), (&mut self.grade_excess_over_1cm, other.grade_excess_over_1cm), + (&mut self.grounded, other.grounded), (&mut self.refinements_unconverged, other.refinements_unconverged), (&mut self.covers, other.covers), (&mut self.covers_lifted, other.covers_lifted), + (&mut self.covers_untagged, other.covers_untagged), + (&mut self.covers_untagged_lifted, other.covers_untagged_lifted), + (&mut self.covers_capped, other.covers_capped), + (&mut self.covers_untagged_capped, other.covers_untagged_capped), ]; for (sum, value) in sums { *sum += value; } self.sidewalks.add(&other.sidewalks); self.rounds = self.rounds.max(other.rounds); + for k in 0..SCALES.len() { + self.capped[k] += other.capped[k]; + self.capped_left[k] += other.capped_left[k]; + self.capped_step_m[k] = self.capped_step_m[k].max(other.capped_step_m[k]); + } self.residual_p99_m = self.residual_p99_m.max(other.residual_p99_m); + self.cover_lift_top_m = self.cover_lift_top_m.max(other.cover_lift_top_m); if (other.grade_excess_m, other.grade_excess_at) > (self.grade_excess_m, self.grade_excess_at) { (self.grade_excess_m, self.grade_excess_at) = (other.grade_excess_m, other.grade_excess_at); } @@ -324,14 +397,9 @@ pub fn solve( seg.push(end - 1); t.push(1.0); } - // A bridge or a tunnel sees no terrain, unless nothing that it meets does. A bridge's end that - // meets no other way stands on the terrain: else the smoothness carries any rise of its deck on up. - let mut loose = vec![false; n]; - for w in (0..net.free.len()).filter(|&w| net.free[w] && !net.tunnel[w]) { - for v in [net.way_first[w], net.way_last[w]] { - loose[net.vertex_var[v]] = !net.junction[net.vertex_var[v]]; - } - } + // A bridge or a tunnel sees no terrain, unless nothing that it meets does. A bridge's end that stands + // on the terrain (`rows::standing`) sees it: else the smoothness carries any rise of its deck on up. + let loose = rows::standing(&net); let at_end = |i: usize| if t[i] == 0.0 { a[seg[i]] } else { b[seg[i]] }; let mut weight: Vec = (0..seg.len()) .map(|i| { @@ -340,16 +408,14 @@ pub fn solve( length[s] / k[s] as f64 * f64::from(u8::from(seen)) }) .collect(); + let point = |i: usize| { + let v = net.segment_start[seg[i]]; + let (pa, pb) = (net.vertex_xy[v], net.vertex_xy[v + 1]); + [pa[0] + t[i] * (pb[0] - pa[0]), pa[1] + t[i] * (pb[1] - pa[1])] + }; let mut h = Vec::with_capacity(seg.len()); for chunk in (0..seg.len()).collect::>().chunks(1 << 21) { - let points: Vec<[f64; 2]> = chunk - .iter() - .map(|&i| { - let v = net.segment_start[seg[i]]; - let (pa, pb) = (net.vertex_xy[v], net.vertex_xy[v + 1]); - [pa[0] + t[i] * (pb[0] - pa[0]), pa[1] + t[i] * (pb[1] - pa[1])] - }) - .collect(); + let points: Vec<[f64; 2]> = chunk.iter().map(|&i| point(i)).collect(); h.extend(terrain.heights(&points)); } let finite: Vec = h.iter().map(|h| h.is_finite()).collect(); @@ -405,28 +471,32 @@ pub fn solve( // Rows that pin a combination of variables to a value: the approaches of side roads, the fords, // the bores, the tracks side by side. - let (approach, approached) = rows::approaches(&net); - let fords = rows::fords(&net, rivers); - let bores = rows::chains(&net, &net.tunnel); + let (approach, approached, ramp) = rows::approaches(&net, classes); + let fords = rows::fords(&net, rivers, classes); + let untagged = rows::untagged_crossings(&net, rivers, classes); + // A way on the ground meets a tunnel where it comes out of the ground: at a portal, which ends its chain. + let mut grounded = vec![false; n]; + for s in (0..a.len()).filter(|&s| !free[s]) { + grounded[a[s]] = true; + grounded[b[s]] = true; + } + let (bores, tunnels) = rows::chains(&net, &net.tunnel, &grounded); let beside = rows::parallels(&net, classes, terrain); let bridge: Vec = (0..net.free.len()).map(|w| net.free[w] && !net.tunnel[w]).collect(); // The decks over what they cross and the bridges that do not sag: each ≥ its value. let (above, deck_ways) = rows::clearances(&net, rivers, classes, terrain); - let sags = rows::chains(&net, &bridge); - // The covers over the culverts: each ≥ its value where its way lies on the ground. - let (cover, cover_ways) = rows::covers(&net, &near.culverts, rivers, classes, terrain); + let (sags, _) = rows::chains(&net, &bridge, &[]); + // The covers over the culverts, tagged and untagged: each ≥ its value where its way lies on the ground. + let (cover, cover_ways, cover_untagged) = rows::covers(&net, (&near.culverts, rivers), &untagged, classes, terrain); let (mut k_rows, mut k_least, mut k_way, mut k_first) = (Rows::default(), Vec::new(), Vec::new(), Vec::new()); + let mut k_untagged = Vec::new(); for i in (0..cover.values.len()).filter(|&i| all_known(&cover.variables[i])) { k_rows.push(cover.variables[i].into_iter().zip(cover.coefficients[i])); k_least.push(cover.values[i]); k_way.push(cover_ways[i]); k_first.push(cover.variables[i][0]); + k_untagged.push(cover_untagged[i]); } - // Per row, whether its way holds the cover: on the ground or a culvert, and lifted by no more than its - // most; and whether the cover lifts it. - let (mut holds, mut lifted) = (vec![false; k_least.len()], vec![false; k_least.len()]); - // The culverts by the first solve: the cover that lifts one keeps it a culvert. - let mut culvert = vec![false; net.free.len()]; let mut c_rows = Rows::default(); let (mut least, mut deck_way, mut deck_first) = (Vec::new(), Vec::new(), Vec::new()); for (i, &w) in deck_ways.iter().enumerate() { @@ -462,13 +532,14 @@ pub fn solve( pass_first.push(upper.0[0]); } let mut p_rows = Rows::default(); - let (mut values, mut counted) = (Vec::new(), Vec::new()); - for pins in [&approach, &fords, &bores, &beside] { + let (mut values, mut counted, mut p_w) = (Vec::new(), Vec::new(), Vec::new()); + for (k, pins) in [&approach, &fords, &bores, &beside].into_iter().enumerate() { let mut count = 0; for i in 0..pins.values.len() { if all_known(&pins.variables[i]) { p_rows.push(pins.variables[i].into_iter().zip(pins.coefficients[i])); values.push(pins.values[i]); + p_w.push(if k == 2 { BORE } else { PIN }); count += usize::from(var_mine[pins.variables[i][0]]); } } @@ -511,30 +582,126 @@ pub fn solve( add_bend(across, span(p, j), span(q, j), smooth(net.rule[net.osm_way[o1]])); } } - // Grades: per segment of a class with a limit, z_b − z_a within ± grade × length. A bridge or a - // tunnel has the grade that its ends give it: OSM joins shafts and ramps to tunnels that no limit - // could meet. Nor has the approach of a side road, or a segment between two approaches: the through - // roads give them their heights. + // Grades: per segment of a class with a limit, z_b − z_a within ± grade × length. A tunnel between two + // portals has the grade of its class too, TUNNEL_GRADE where its class has none, so a pass near a portal does + // not dig a step into it; but at least the terrain's rise from portal to portal over its length, so the grade + // never pulls a portal off the terrain. A side tunnel or a shaft that ends on another tunnel has the grade that + // its ends give it, so it never lifts that tunnel; so has a bridge. The pieces run portal to portal along the + // straightest line of a chain, so a tunnel that branches inside the mountain grades only that line: its + // branch has no grade, as a side tunnel. Nor has the approach of a side road, or a segment between two + // approaches: the through roads give them their heights. A ramp rises at most RAMP_GRADE off the grade of the + // terrain. + let portal = |v: usize| grounded[net.vertex_var[v]] || loose[net.vertex_var[v]]; + let segment_of: HashMap<(usize, usize), usize> = + (0..a.len()).flat_map(|s| [((a[s], b[s]), s), ((b[s], a[s]), s)]).collect(); + let pieces: Vec<&Vec> = + tunnels.iter().filter(|piece| portal(piece[0]) && portal(piece[piece.len() - 1])).collect(); + let portals: Vec<[f64; 2]> = + pieces.iter().flat_map(|piece| [piece[0], piece[piece.len() - 1]].map(|v| net.vertex_xy[v])).collect(); + let portals = terrain.heights(&portals); + // Per segment of a graded piece, the terrain's mean grade between the piece's portals. + let mut graded: Vec> = vec![None; a.len()]; + for (k, piece) in pieces.iter().enumerate() { + let segments: Vec = (piece.windows(2)) + .filter_map(|pair| segment_of.get(&(net.vertex_var[pair[0]], net.vertex_var[pair[1]])).copied()) + .collect(); + let along: f64 = segments.iter().map(|&s| length[s]).sum(); + let rise = (portals[2 * k + 1] - portals[2 * k]).abs() / along.max(0.01); + for s in segments { + graded[s] = Some(if rise.is_finite() { rise } else { 0.0 }); + } + } let mut pinned = vec![false; n]; for variables in &approach.variables { pinned[variables[0]] = true; } let grade = |s: usize| classes.rows[net.rule[net.segment_way[s]]].grade; + // The terrain's rise under each ramp, which its limit centres on; a ramp without one has no limit. + let ramps: Vec = (0..a.len()).filter(|&s| ramp[s]).collect(); + let ends: Vec<[f64; 2]> = + ramps.iter().flat_map(|&s| [0, 1].map(|k| net.vertex_xy[net.segment_start[s] + k])).collect(); + let ground = terrain.heights(&ends); + let mut rise = vec![f64::NAN; a.len()]; + for (k, &s) in ramps.iter().enumerate() { + rise[s] = ground[2 * k + 1] - ground[2 * k]; + } + let tunnel = |s: usize| graded[s].is_some(); let limited: Vec = (0..a.len()) .filter(|&s| { - grade(s).is_finite() - && !free[s] + ((grade(s).is_finite() && !approached[s] || rise[s].is_finite()) && !free[s] || tunnel(s)) && known[a[s]] && known[b[s]] - && !approached[s] && !(pinned[a[s]] && pinned[b[s]]) }) .collect(); - let mut g_rows = Rows::default(); + // The ground: a way on the ground lies within GROUND_M of the terrain across it at each of its samples, and + // the end of a bridge that meets no way at its own; but not where a bridge runs through an end of + // its segment: steps or a ramp that meet a deck there take its height. + let mut decked = vec![0u8; n]; + for s in (0..a.len()).filter(|&s| free[s] && !net.tunnel[net.segment_way[s]]) { + decked[a[s]] += 1; + decked[b[s]] += 1; + } + let on_ground = |i: usize| { + let s = seg[i]; + let ends = t[i] == 0.0 || t[i] == 1.0; + finite[i] + && known[a[s]] + && known[b[s]] + && if free[s] { loose[at_end(i)] && ends } else { decked[a[s]] < 2 && decked[b[s]] < 2 } + }; + let ground_samples: Vec = (0..seg.len()).filter(|&i| on_ground(i)).collect(); + // The terrain across the way at each ground sample, at its centre and at ± its half-width square to its + // segment: on a slope the terrain under the line of OSM is not the bed of the road, and the ground holds + // the road near the terrain range of its whole width. + let edges = |i: usize| { + let v = net.segment_start[seg[i]]; + abreast(point(i), [net.vertex_xy[v], net.vertex_xy[v + 1]], net.half[net.segment_way[seg[i]]]) + }; + let width = across(&ground_samples, &h, edges, terrain); + // The limits: rows A·z with a band from lo to hi, each with a cost per square metre past its band, so a + // limit only pushes, and only where the heights pass it. First the grades of the segments; then the + // ground of the vertices; then the rows of one side, A·z ≥ lo, that the first solve chooses: the decks + // over what they cross and the bridges that do not sag, the covers over the culverts, and the ways + // that pass over each other. + let mut limits = Rows::default(); + let mut band: Vec<[f64; 2]> = Vec::new(); for &s in &limited { - g_rows.push([(a[s], -1.0), (b[s], 1.0)]); + let (bound, centre) = match grade(s) { + g if tunnel(s) => (g.min(TUNNEL_GRADE).max(graded[s].unwrap_or(0.0)) * length[s], 0.0), + g if g.is_finite() => (g * length[s], 0.0), + _ => (RAMP_GRADE * length[s], rise[s]), + }; + limits.push([(a[s], -1.0), (b[s], 1.0)]); + band.push([centre - bound, centre + bound]); + } + for off in [GROUND_M, HARD_M] { + for (&i, &[low, high]) in ground_samples.iter().zip(&width) { + limits.push([(a[seg[i]], 1.0 - t[i]), (b[seg[i]], t[i])]); + band.push([low - off, high + off]); + } } - let bound: Vec = limited.iter().map(|&s| grade(s) * length[s]).collect(); + let mut starts = [0; 3]; + for (k, (rows, least)) in [(&c_rows, &least), (&k_rows, &k_least), (&apart, &need)].into_iter().enumerate() { + starts[k] = band.len(); + for (i, &least) in least.iter().enumerate() { + limits.push(rows.row(i)); + band.push([least, f64::INFINITY]); + } + } + let (lo, hi): (Vec, Vec) = band.into_iter().map(|[lo, hi]| (lo, hi)).unzip(); + let [decks, covers, passes] = starts; + let hard = limited.len() + ground_samples.len(); + let is_ramp: Vec = + (0..lo.len()).map(|i| i < limited.len() && !tunnel(limited[i]) && !grade(limited[i]).is_finite()).collect(); + // The lower bound now: a tunnel under a road on the ground lies the margin under the road's height. + let lows = |z: &[f64]| -> Vec { + let mut out = lo.clone(); + for (i, uz) in u_rows.times(z).into_iter().enumerate().filter(|&(i, _)| !moves[i]) { + out[passes + i] = need[i] - uz; + } + out + }; let (mut level_rows, mut level_w) = (Rows::default(), Vec::new()); for s in (0..a.len()).filter(|&s| free[s] && known[a[s]] && known[b[s]]) { level_rows.push([(a[s], -1.0), (b[s], 1.0)]); @@ -546,102 +713,70 @@ pub fn solve( } let zeros = vec![0.0; unknown.len()]; // The rows (A, w, c) of the least squares Σ w·(A·z − c)² that every solve holds. - let mut fixed = - vec![level(d2, lam), level(level_rows, level_w), held_at(p_rows, PIN, values), held_at(unknown, 1.0, zeros)]; - let mut unconverged = 0; - let solve = |fixed: &[(Rows, Vec, Vec)], w: &[f64], held: &[f64], from: Option<(&[f64], &[usize])>| { - let on: Vec = held.iter().map(|&x| x != 0.0).collect(); - let g_on = g_rows.select(&on); - let g_c: Vec = (0..held.len()).filter(|&i| on[i]).map(|i| held[i] * bound[i]).collect(); - let g_w = vec![PIN; g_c.len()]; - let mut terms: Vec = fixed.iter().map(|(rows, w, c)| Term { block: Block::Rows(rows), w, c }).collect(); - terms.push(Term { block: Block::Samples { seg: &seg, t: &t, a, b }, w, c: &h }); - terms.push(Term { block: Block::Rows(&g_on), w: &g_w, c: &g_c }); - fit(&terms, n, from) - }; - // The slope limits after a solve: a segment past its limit holds it, a held one that the solve - // would make less steep lets go. Without releases the rounds end: the held segments only grow. - let update = |held: &[f64], z: &[f64], release: bool| -> Vec { - let gz = g_rows.times(z); - (0..held.len()) - .map(|i| { - let mut out = if release && held[i] * gz[i] < bound[i] { 0.0 } else { held[i] }; - if gz[i] > bound[i] + TOLERANCE_M { - out = 1.0; - } - if gz[i] < -bound[i] - TOLERANCE_M { - out = -1.0; - } - out - }) - .collect() - }; - let deck = |rows: &Rows, z: &[f64]| rows.times(z); - let mut held = vec![0.0; limited.len()]; - let mut before = held.clone(); - let mut w = weight.clone(); - let mut z = Vec::new(); - for solves in 0..SOLVES { - let converged; - (z, converged) = solve(&fixed, &w, &held, None); - unconverged += usize::from(!converged); - if solves < SOLVES - 1 { - w = (0..seg.len()) - .map(|i| { - let residual = (z[a[seg[i]]] * (1.0 - t[i]) + z[b[seg[i]]] * t[i] - h[i]).abs(); - weight[i] * (HUBER_M / residual.max(1e-9)).min(1.0) - }) - .collect(); - // A short bridge that lies on the terrain is a culvert. Any other deck that passes too low - // holds its least height from the next solve on. - culvert = culverts(&net, &z, &seg, &t, &h, &finite); - let cz = deck(&c_rows, &z); - let low: Vec = (0..least.len()) - .map(|i| cz[i] < least[i] - TOLERANCE_M && !deck_way[i].is_some_and(|w| culvert[w])) - .collect(); - let low_rows = c_rows.select(&low); - let low_least: Vec = (0..least.len()).filter(|&i| low[i]).map(|i| least[i]).collect(); - fixed.push(held_at(low_rows, PIN, low_least)); - // So does a road or a track over a culvert, and a culvert's bridge of one, that lies too low. - let kz = deck(&k_rows, &z); - holds = (0..k_least.len()) - .map(|i| (!net.free[k_way[i].0] || culvert[k_way[i].0]) && k_least[i] - kz[i] <= k_way[i].1) - .collect(); - lifted = (0..k_least.len()).map(|i| holds[i] && kz[i] < k_least[i] - TOLERANCE_M).collect(); - let k_least: Vec = (0..k_least.len()).filter(|&i| lifted[i]).map(|i| k_least[i]).collect(); - fixed.push(held_at(k_rows.select(&lifted), PIN, k_least)); - // Ways that pass too near hold the margin from the next solve on; a tunnel under a road holds - // the road's height less the margin. - let (uz, lz) = (u_rows.times(&z), l_rows.times(&z)); - let near: Vec = (0..need.len()).map(|i| uz[i] - lz[i] < need[i] - TOLERANCE_M).collect(); - let target: Vec = (0..need.len()) - .filter(|&i| near[i]) - .map(|i| if moves[i] { need[i] } else { need[i] - uz[i] }) - .collect(); - let near_rows = apart.select(&near); - fixed.push(held_at(near_rows, PIN, target)); - } - let next = update(&held, &z, true); - before = std::mem::replace(&mut held, next); - } - // Rounds of the slope limits near the segments whose limit changed, the rest of the network - // fixed. Nothing anchors a bridge or a tunnel but its ends: a region takes it whole. + let fixed = [level(d2, lam), level(level_rows, level_w), (p_rows, p_w, values), held_at(unknown, 1.0, zeros)]; + let samples = Block::Samples { seg: &seg, t: &t, a, b }; + // The first solve, without limits, gives the Huber weights, the culverts and the covers. + let (mut z, converged) = fit(&terms(&fixed, samples, (&weight, &h)), n, None); + let mut unconverged = usize::from(!converged); + let w: Vec = (0..seg.len()) + .map(|i| { + let residual = (z[a[seg[i]]] * (1.0 - t[i]) + z[b[seg[i]]] * t[i] - h[i]).abs(); + weight[i] * (HUBER_M / residual.max(1e-9)).min(1.0) + }) + .collect(); + // A short bridge that lies on the terrain is a culvert; the cover that lifts one keeps it a culvert. + let culvert = culverts(&net, &z, &seg, &t, &h, &finite); + // Per cover row, its lift over the first solve; whether its way holds the cover: on the ground or a + // culvert, and lifted by no more than its most; and whether its lift passes the most. + let kz = k_rows.times(&z); + let k_lift: Vec = (0..k_least.len()).map(|i| k_least[i] - kz[i]).collect(); + let ground = |i: usize| !net.free[k_way[i].0] || culvert[k_way[i].0]; + let holds: Vec = (0..k_least.len()).map(|i| ground(i) && k_lift[i] <= k_way[i].1).collect(); + let capped: Vec = (0..k_least.len()).map(|i| ground(i) && k_lift[i] > k_way[i].1).collect(); + // The cost of each limit: a deck acts only where its bridge is no culvert, a cover only where it lifts its + // way by no more than its most. The ramps act once the rest is solved: then they bend only their sides. + let cost: Vec = (0..lo.len()) + .map(|i| match i { + _ if i < limited.len() || i >= passes => LIMIT, + _ if i < hard => GROUND, + _ if i < decks => HARD, + _ if i < covers => LIMIT * f64::from(u8::from(!deck_way[i - decks].is_some_and(|w| culvert[w]))), + _ => LIMIT * f64::from(u8::from(holds[i - covers])), + }) + .collect(); + let rest: Vec = (0..lo.len()).map(|i| if is_ramp[i] { 0.0 } else { cost[i] }).collect(); + let terms = terms(&fixed, samples, (&w, &h)); + let all: Vec = (0..n).collect(); + let limit = |cost| Limits { rows: &limits, lo: &lows, hi: &hi, cost }; + // Nothing anchors a bridge or a tunnel but its ends: a region takes it whole. let edges: Vec<(usize, usize, f64)> = (0..a.len()).map(|s| (a[s], b[s], if free[s] { 1e-6 } else { length[s].max(0.01) })).collect(); - let graph = Graph::new(n, &edges); - let mut rounds = 0; - while rounds < ROUNDS && held != before { - rounds += 1; - let sources: BTreeSet = - (0..held.len()).filter(|&i| held[i] != before[i]).flat_map(|i| [a[limited[i]], b[limited[i]]]).collect(); - let distance = graph.distances(sources.into_iter().map(|v| (v, 0.0)), REGION_M); - let region: Vec = (0..n).filter(|&v| distance[v].is_finite()).collect(); - let converged; - (z, converged) = solve(&fixed, &w, &held, Some((&z, ®ion))); - unconverged += usize::from(!converged); - let next = update(&held, &z, rounds < ROUNDS / 2); - before = std::mem::replace(&mut held, next); + let graph = (&Graph::new(n, &edges), REGION_M); + let solved_rest = settle(&terms, &limit(&rest), &mut z, &all, graph, &SCALES); + let (mut rounds, mut at_cap) = (solved_rest.rounds, solved_rest.capped); + unconverged += solved_rest.unconverged; + // The ramps, with every vertex fixed but those of the ramps' sides past their approach and before any + // junction: a ramp bends its side and never moves the road it leaves. + let mut ramp_region: Vec = (0..limited.len()) + .filter(|&i| is_ramp[i]) + .flat_map(|i| limits.row(i).map(|(v, _)| v)) + .filter(|&v| !net.junction.get(v).copied().unwrap_or(false) && !pinned[v]) + .collect(); + ramp_region.sort_unstable(); + ramp_region.dedup(); + if !ramp_region.is_empty() { + let ramps = settle(&terms, &limit(&cost), &mut z, &ramp_region, graph, &[1.0]); + (rounds, unconverged) = (rounds + ramps.rounds, unconverged + ramps.unconverged); + // The ramps run at the last scale. + if let Some((step, left)) = ramps.capped[0] { + let (most, all) = at_cap[SCALES.len() - 1].unwrap_or((0.0, 0)); + at_cap[SCALES.len() - 1] = Some((most.max(step), all + left)); + } } + // Per limit, whether it acts at the end: past its band. + let (gz, low) = (limits.times(&z), lows(&z)); + let held: Vec = (0..lo.len()).map(|i| cost[i] > 0.0 && (gz[i] > hi[i] || gz[i] < low[i])).collect(); + let lifted: Vec = (0..k_least.len()).map(|i| held[covers + i]).collect(); // A clearance and a ford hold on the curve only where their vertices stay in the tiles. let mut stay = vec![false; n]; @@ -655,7 +790,10 @@ pub fn solve( water[net.osm_var[o]] = shores.contains(&key(xy)); } let ground: Vec = (0..culvert.len()).map(|w| !net.free[w] || culvert[w]).collect(); - let town = Town::new(&net, (rivers, &near.culverts), near.buildings, terrain); + // A pipe runs under the sidewalks only where its row holds the cover. + let piped: Vec = + (0..k_least.len()).filter(|&i| holds[i]).filter_map(|i| Some(untagged[k_untagged[i]?])).collect(); + let town = Town::new(&net, (rivers, &near.culverts), (&piped, classes), near.buildings, terrain); let (ways, joins, walks) = align::align(&net, &z, &known, &stay, &water, &ground, classes, &mine, &town); for (way, &(f, p)) in ways.into_iter().zip(&net.way_feature) { solved.ways[f][p] = Some(way); @@ -664,15 +802,15 @@ pub fn solve( solved.joins = joins.into_iter().map(|join| join.map(named)).collect(); let way_mine: Vec = net.way_first.iter().map(|&v| mine[v]).collect(); solved.culverts = (0..culvert.len()).filter(|&w| culvert[w] && way_mine[w]).map(|w| net.way_feature[w].0).collect(); - let cz = deck(&c_rows, &z); + let cz = c_rows.times(&z); let deck_mine: Vec = (0..least.len()).map(|i| deck_way[i].is_some_and(|w| !culvert[w]) && var_mine[deck_first[i]]).collect(); let (uz, lz) = (u_rows.times(&z), l_rows.times(&z)); let pass_mine: Vec = pass_first.iter().map(|&v| var_mine[v]).collect(); - let gz = g_rows.times(&z); + let gz = limits.times(&z); let excess: Vec<(f64, usize)> = (0..limited.len()) - .filter(|&i| segment_mine[limited[i]]) - .map(|i| (gz[i].abs() - bound[i], limited[i])) + .filter(|&i| segment_mine[limited[i]] && !is_ramp[i] && !free[limited[i]]) + .map(|i| ((gz[i] - hi[i]).max(lo[i] - gz[i]), limited[i])) .collect(); let worst = excess.iter().fold(None, |best: Option<(f64, usize)>, &(e, s)| match best { Some((b, _)) if b >= e => best, @@ -691,7 +829,13 @@ pub fn solve( fords: counted[1], culverts: solved.culverts.len(), rounds, - held: count(&mut (0..limited.len()).map(|i| held[i] != 0.0 && segment_mine[limited[i]])), + capped: std::array::from_fn(|k| usize::from(at_cap[k].is_some())), + capped_step_m: std::array::from_fn(|k| at_cap[k].map_or(0.0, |c| c.0)), + capped_left: std::array::from_fn(|k| at_cap[k].map_or(0, |c| c.1)), + held: count(&mut (0..limited.len()).map(|i| held[i] && segment_mine[limited[i]] && !free[limited[i]])), + grounded: count( + &mut (limited.len()..hard).map(|i| held[i] && segment_mine[seg[ground_samples[i - limited.len()]]]), + ), clearances: count(&mut deck_mine.iter().copied()), clearances_low_cm: count(&mut (0..least.len()).map(|i| cz[i] < least[i] - 0.01 && deck_mine[i])), passes: count(&mut pass_mine.iter().copied()), @@ -703,6 +847,22 @@ pub fn solve( refinements_unconverged: unconverged, covers: count(&mut (0..k_least.len()).map(|i| holds[i] && var_mine[k_first[i]])), covers_lifted: count(&mut (0..k_least.len()).map(|i| lifted[i] && var_mine[k_first[i]])), + covers_untagged: count( + &mut (0..k_least.len()).map(|i| holds[i] && k_untagged[i].is_some() && var_mine[k_first[i]]), + ), + covers_untagged_lifted: count( + &mut (0..k_least.len()).map(|i| lifted[i] && k_untagged[i].is_some() && var_mine[k_first[i]]), + ), + covers_capped: count( + &mut (0..k_least.len()).map(|i| capped[i] && k_untagged[i].is_none() && var_mine[k_first[i]]), + ), + covers_untagged_capped: count( + &mut (0..k_least.len()).map(|i| capped[i] && k_untagged[i].is_some() && var_mine[k_first[i]]), + ), + cover_lift_top_m: (0..k_least.len()) + .filter(|&i| lifted[i] && var_mine[k_first[i]]) + .map(|i| k_lift[i]) + .fold(0.0, f64::max), sidewalks: walks, }; solved.underpasses = (0..held_up.len()) @@ -712,6 +872,36 @@ pub fn solve( solved } +/// The terms of the least squares that every solve holds: the fixed rows and the terrain samples of weights w. +fn terms<'a>( + fixed: &'a [(Rows, Vec, Vec)], + samples: Block<'a>, + (w, h): (&'a [f64], &'a [f64]), +) -> Vec> { + let mut terms: Vec = fixed.iter().map(|(rows, w, c)| Term { block: Block::Rows(rows), w, c }).collect(); + terms.push(Term { block: samples, w, c: h }); + terms +} + +/// Per sample of `samples`, the lowest and the highest terrain across its way: its height `h` and the known +/// terrain at its two `edges`. +fn across( + samples: &[usize], + h: &[f64], + edges: impl Fn(usize) -> [[f64; 2]; 2], + terrain: &dyn Terrain, +) -> Vec<[f64; 2]> { + let mut out = Vec::with_capacity(samples.len()); + for chunk in samples.chunks(1 << 16) { + let points: Vec<[f64; 2]> = chunk.iter().flat_map(|&i| edges(i)).collect(); + let heights = terrain.heights(&points); + out.extend(chunk.iter().zip(heights.chunks(2)).map(|(&i, pair)| { + pair.iter().filter(|z| z.is_finite()).fold([h[i], h[i]], |[lo, hi], &z| [lo.min(z), hi.max(z)]) + })); + } + out +} + /// Rows of their weights against 0. fn level(rows: Rows, w: Vec) -> (Rows, Vec, Vec) { let c = vec![0.0; rows.len()]; @@ -723,11 +913,6 @@ fn held_at(rows: Rows, w: f64, c: Vec) -> (Rows, Vec, Vec) { (rows, vec![w; c.len()], c) } -/// Latitude and longitude of a world point. -fn degrees([x, y]: [f64; 2]) -> [f64; 2] { - [(std::f64::consts::PI * (1.0 - 2.0 * y)).sinh().atan().to_degrees(), x * 360.0 - 180.0] -} - /// Per way, whether it is a culvert: a bridge shorter than CULVERT_M, with the deck no more than /// CULVERT_RISE_M above the terrain under it. fn culverts(net: &Network, z: &[f64], seg: &[usize], t: &[f64], h: &[f64], finite: &[bool]) -> Vec { diff --git a/host/obc-trailview-features/src/roads/network.rs b/host/obc-trailview-features/src/roads/network.rs index 529456fb5e..db62c7e434 100644 --- a/host/obc-trailview-features/src/roads/network.rs +++ b/host/obc-trailview-features/src/roads/network.rs @@ -22,10 +22,12 @@ pub(crate) struct Network { pub free: Vec, pub tunnel: Vec, pub ford: Vec, + pub stones: Vec, pub layer: Vec, pub layered: Vec, pub indoor: Vec, pub half: Vec, + pub outer: Vec, pub sidewalks: Vec<[Option; 2]>, pub osm_xy: Vec<[f64; 2]>, pub osm_way: Vec, @@ -124,11 +126,12 @@ impl Network { } let of = |get: &dyn Fn(&Feature) -> bool| way_feature.iter().map(|&(f, _)| get(features[f])).collect::>(); - let (free, tunnel, ford) = (of(&|f| f.free), of(&|f| f.tunnel), of(&|f| f.ford)); + let (free, tunnel, ford, stones) = (of(&|f| f.free), of(&|f| f.tunnel), of(&|f| f.ford), of(&|f| f.stones)); let (layered, indoor) = (of(&|f| f.layered), of(&|f| f.indoor)); let rule: Vec = way_feature.iter().map(|&(f, _)| features[f].rule).collect(); let layer: Vec = way_feature.iter().map(|&(f, _)| features[f].layer).collect(); let half: Vec = way_feature.iter().map(|&(f, _)| features[f].half).collect(); + let outer: Vec = way_feature.iter().map(|&(f, _)| features[f].outer).collect(); let sidewalks = way_feature.iter().map(|&(f, _)| features[f].sidewalks).collect(); let counts: Vec = xys.iter().map(Vec::len).collect(); let osm_xy: Vec<[f64; 2]> = xys.concat(); @@ -164,10 +167,12 @@ impl Network { free, tunnel, ford, + stones, layer, layered, indoor, half, + outer, sidewalks, osm_xy, osm_way, diff --git a/host/obc-trailview-features/src/roads/rows.rs b/host/obc-trailview-features/src/roads/rows.rs index 920a55c731..bcac29f4cc 100644 --- a/host/obc-trailview-features/src/roads/rows.rs +++ b/host/obc-trailview-features/src/roads/rows.rs @@ -11,6 +11,9 @@ use super::network::{dot, hypot, sub, Network}; use super::*; use crate::geometry::key; use crate::{metres, Terrain}; +use obc_ground_plan::frame::GlobalPoint; +use obc_ground_plan::graph::end_on_chord; +use obc_ground_plan::sections::GRAZE_DEG; /// Rows of up to four variables: Σ coefficient × z_variable, against a value. #[derive(Default)] @@ -33,10 +36,16 @@ impl Pins { /// through direction that the side leans along most and τ ≥ 0 the place of P along J-Q. A side pins /// only the vertices at least a metre nearer to its junction than to the next junction along its /// way, so that the two ends of a short link do not pin one vertex. Also, per segment, whether it -/// lies within the approach distance of a junction where its way is a side. A tunnel that leaves a -/// junction as a side runs straight (`chains`) and has no approach. -pub(crate) fn approaches(net: &Network) -> (Pins<3>, Vec) { +/// lies within the approach distance of a junction where its way is a side, and the through roads +/// give it its grade: a pin holds its far end, or its way is a side at both of its junctions (past +/// any junction where it runs through). A +/// tunnel that leaves a junction as a side runs straight (`chains`) and has no approach. Last, per +/// segment, whether it is a ramp: a segment within RAMP_M of a junction that no pin holds, of a side +/// without a grade limit that leaves a through road with one. +pub(crate) fn approaches(net: &Network, classes: &Classes) -> (Pins<3>, Vec, Vec) { let mut approached = vec![false; net.segment_start.len()]; + let mut ramp = vec![false; net.segment_start.len()]; + let limited = |o: usize| classes.rows[net.rule[net.osm_way[o]]].grade.is_finite(); let mut segment = vec![usize::MAX; net.vertex_xy.len()]; for (s, &v) in net.segment_start.iter().enumerate() { segment[v] = s; @@ -44,6 +53,9 @@ pub(crate) fn approaches(net: &Network) -> (Pins<3>, Vec) { // (side, vertex, metres along) in the order of the steps of the walk. let mut found: Vec> = Vec::new(); let mut sides = Vec::new(); + let side_at: HashSet<(usize, i64)> = (0..net.sides.occurrence.len()) + .map(|i| (net.osm_position[net.sides.occurrence[i]], net.sides.step[i])) + .collect(); for i in 0..net.sides.occurrence.len() { let occurrence = net.sides.occurrence[i]; if net.tunnel[net.osm_way[occurrence]] { @@ -65,20 +77,30 @@ pub(crate) fn approaches(net: &Network) -> (Pins<3>, Vec) { let unit = metres(net.vertex_xy[j][1]); let reach = net.sides.distance[i] + 1.01; let (mut p, mut along, mut run) = (j, 0.0, f64::INFINITY); - let (mut walking, mut inside, mut steps) = (true, true, 0); + let (mut walking, mut inside, mut steps, mut link) = (true, true, 0, false); + // (segment, metres along at its far end) within the approach distance, and the walked segments. + let (mut near, mut walked) = (Vec::new(), Vec::new()); + let ramps = !limited(occurrence) && net.sides.through[i].iter().flatten().any(|&(o, _)| limited(o)); while walking { let ahead = p as i64 + step; walking &= ahead >= net.way_first[way] as i64 && ahead <= net.way_last[way] as i64; let ahead = if walking { ahead as usize } else { p }; along += hypot(sub(net.vertex_xy[ahead], net.vertex_xy[p])) * unit; if inside && walking && along <= reach { - approached[segment[p.min(ahead)]] = true; + near.push((segment[p.min(ahead)], along)); + } + if ramps && walking && along - hypot(sub(net.vertex_xy[ahead], net.vertex_xy[p])) * unit < RAMP_M { + walked.push(segment[p.min(ahead)]); } p = ahead; let meets = walking && net.vertex_junction[p]; - if meets { + // A side junction ends the walk; past a junction where the way runs through, it goes on. + let back = meets && side_at.contains(&(p, -step)); + let ends = back || meets && side_at.contains(&(p, step)); + if meets && run.is_infinite() { run = along; } + link |= back && along <= 2.0 * reach + 1.0; inside &= walking && !meets && along <= reach; if found.len() <= steps { found.push(Vec::new()); @@ -87,7 +109,14 @@ pub(crate) fn approaches(net: &Network) -> (Pins<3>, Vec) { found[steps].push((sides.len(), p, along)); } steps += 1; - walking &= !meets && along <= 2.0 * reach + 1.0; + walking &= !ends && along <= (2.0 * reach + 1.0).max(RAMP_M); + } + let held: Vec = near.iter().filter(|&&(_, along)| 2.0 * along + 1.0 <= run).map(|&(s, _)| s).collect(); + for &(s, _) in &near { + approached[s] |= link || held.contains(&s); + } + for s in walked { + ramp[s] |= !held.contains(&s); } sides.push((j, q, run)); } @@ -102,7 +131,7 @@ pub(crate) fn approaches(net: &Network) -> (Pins<3>, Vec) { let tau = (dot(sub(net.vertex_xy[p], origin), axis) / dot(axis, axis).max(1e-300)).max(0.0); pins.push([net.vertex_var[p], net.vertex_var[j], net.vertex_var[q]], [1.0, -(1.0 - tau), -tau], 0.0); } - (pins, approached) + (pins, approached, ramp) } /// Rows z_v − (1 − τ)·z_A − τ·z_B per vertex inside a chain of the ways that `members` marks, with A @@ -110,8 +139,9 @@ pub(crate) fn approaches(net: &Network) -> (Pins<3>, Vec) { /// keeps a bridge from sagging. Where the ends of member ways meet, a chain runs on through the two /// that continue most nearly straight, and the others are side tunnels. So a side tunnel or a shaft /// follows the tunnel that it joins and never lifts it: nothing but its ends gives a long tunnel its -/// heights. -pub(crate) fn chains(net: &Network, members: &[bool]) -> Pins<3> { +/// heights. A chain ends at each variable that `stops` marks. The rows, and the vertices of each piece of a +/// chain between two of its ends or stops. +pub(crate) fn chains(net: &Network, members: &[bool], stops: &[bool]) -> (Pins<3>, Vec>) { let chained: Vec = (0..members.len()).filter(|&w| members[w]).collect(); let mut meetings: Vec> = Vec::new(); let mut slot: HashMap = HashMap::new(); @@ -147,7 +177,7 @@ pub(crate) fn chains(net: &Network, members: &[bool]) -> Pins<3> { } } let mut seen = HashSet::new(); - let mut pins = Pins::default(); + let (mut pins, mut pieces) = (Pins::default(), Vec::new()); for &start in &chained { if seen.contains(&start) { continue; @@ -173,33 +203,47 @@ pub(crate) fn chains(net: &Network, members: &[bool]) -> Pins<3> { let Some(&(next, next_end)) = partner.get(&(w, if flipped { 0 } else { 1 })) else { break }; (w, flipped) = (next, next_end == 1); } - let (a, b) = (net.vertex_var[chain[0]], net.vertex_var[chain[chain.len() - 1]]); - if chain.len() < 3 || a == b { - continue; - } - let mut along = vec![0.0]; - for pair in chain.windows(2) { - let (p, q) = (net.vertex_xy[pair[0]], net.vertex_xy[pair[1]]); - along.push(along[along.len() - 1] + hypot(sub(q, p)) * metres((p[1] + q[1]) / 2.0)); - } - let total = along[along.len() - 1]; - for (n, &v) in chain.iter().enumerate().take(chain.len() - 1).skip(1) { - let tau = along[n] / total; - pins.push([net.vertex_var[v], a, b], [1.0, -(1.0 - tau), -tau], 0.0); + let cut = |i: usize| i + 1 < chain.len() && stops.get(net.vertex_var[chain[i]]).copied().unwrap_or(false); + let mut first = 0; + for last in (1..chain.len()).filter(|&i| i + 1 == chain.len() || cut(i)) { + straight(net, &chain[first..=last], &mut pins); + pieces.push(chain[first..=last].to_vec()); + first = last; } } - pins + (pins, pieces) +} + +/// The rows of `chains` for one chain of vertices. +fn straight(net: &Network, chain: &[usize], pins: &mut Pins<3>) { + let (a, b) = (net.vertex_var[chain[0]], net.vertex_var[chain[chain.len() - 1]]); + if chain.len() < 3 || a == b { + return; + } + let mut along = vec![0.0]; + for pair in chain.windows(2) { + let (p, q) = (net.vertex_xy[pair[0]], net.vertex_xy[pair[1]]); + along.push(along[along.len() - 1] + hypot(sub(q, p)) * metres((p[1] + q[1]) / 2.0)); + } + let total = along[along.len() - 1]; + for (n, &v) in chain.iter().enumerate().take(chain.len() - 1).skip(1) { + let tau = along[n] / total; + pins.push([net.vertex_var[v], a, b], [1.0, -(1.0 - tau), -tau], 0.0); + } } -/// Rows z_P − (1 − τ)·z_A − τ·z_B = 0 for each vertex P of a track on the ground and the nearest -/// segment A-B of a track on the ground with a higher way number within PARALLEL_M beside it that -/// runs its way, τ the foot of P on A-B, where the terrain at P and at its foot is known and differs -/// by no more than PARALLEL_RISE_M, here and within PARALLEL_FREE_M along P's way. Each track -/// follows only tracks after it, so no two rows pull against each other, and the tracks of a double -/// line or a station lie at one height. +/// Rows z_P − (1 − τ)·z_A − τ·z_B = 0 for each vertex P of a way on the ground and the nearest +/// segment A-B beside it that runs its way, of a way on the ground of the same layer, of the same +/// group (tracks, or roads and paths) and with a higher way number: within PARALLEL_M of a track, or +/// where the carriageways of two roads or paths overlap. τ is the foot of P on A-B, where the terrain +/// at P and at its foot is known and differs by no more than PARALLEL_RISE_M, here and within +/// PARALLEL_FREE_M along P's way. Each way follows only ways after it, so no two rows pull against +/// each other, and the tracks of a double line or a station, and two ways that share their +/// carriageway, lie at one height. pub(crate) fn parallels(net: &Network, classes: &Classes, terrain: &dyn Terrain) -> Pins<3> { - let rail: Vec = (0..net.rule.len()).map(|w| classes.rows[net.rule[w]].rail && !net.free[w]).collect(); - let segments: Vec = (0..net.segment_way.len()).filter(|&s| rail[net.segment_way[s]]).collect(); + let ground: Vec = net.free.iter().map(|&free| !free).collect(); + let rail = |w: usize| classes.rows[net.rule[w]].rail; + let segments: Vec = (0..net.segment_way.len()).filter(|&s| ground[net.segment_way[s]]).collect(); if segments.is_empty() { return Pins::default(); } @@ -208,14 +252,15 @@ pub(crate) fn parallels(net: &Network, classes: &Classes, terrain: &dyn Terrain) segments.iter().zip(&pa).map(|(&s, &a)| sub(net.vertex_xy[net.segment_start[s] + 1], a)).collect(); let length: Vec = d.iter().map(|&d| hypot(d)).collect(); let unit: Vec = pa.iter().map(|p| metres(p[1])).collect(); - let reach = (PARALLEL_M + VERTEX_M / 2.0) / unit.iter().copied().fold(f64::INFINITY, f64::min); + let widest = (0..ground.len()).filter(|&w| ground[w]).map(|w| net.half[w]).fold(0.0, f64::max); + let reach = (PARALLEL_M.max(2.0 * widest) + VERTEX_M / 2.0) / unit.iter().copied().fold(f64::INFINITY, f64::min); let tree: RTree> = RTree::bulk_load( (0..segments.len()) .map(|k| GeomWithData::new([pa[k][0] + d[k][0] / 2.0, pa[k][1] + d[k][1] / 2.0], k)) .collect(), ); let mut found = Vec::new(); - for w in (0..rail.len()).filter(|&w| rail[w]) { + for w in (0..ground.len()).filter(|&w| ground[w]) { for v in net.way_first[w]..=net.way_last[w] { let p = net.vertex_xy[v]; let u = if v < net.way_last[w] { v + 1 } else { v - 1 }; @@ -230,12 +275,25 @@ pub(crate) fn parallels(net: &Network, classes: &Classes, terrain: &dyn Terrain) let mut best: Option<(f64, usize, f64)> = None; for k in near { let other = net.segment_way[segments[k]]; - if other <= w || (dot(own, d[k]) / length[k].max(1e-300)).abs() < PARALLEL_COS { + if other <= w + || rail(other) != rail(w) + || net.layer[other] != net.layer[w] + || (dot(own, d[k]) / length[k].max(1e-300)).abs() < PARALLEL_COS + { + continue; + } + // A foot past the first or the last vertex of the other way is the way that continues + // this one, not a way beside it. + let t = dot(sub(p, pa[k]), d[k]) / (length[k] * length[k]).max(1e-300); + let first = net.segment_start[segments[k]] == net.way_first[other]; + let last = net.segment_start[segments[k]] + 1 == net.way_last[other]; + if t < 0.0 && first || t > 1.0 && last { continue; } - let t = (dot(sub(p, pa[k]), d[k]) / (length[k] * length[k]).max(1e-300)).clamp(0.0, 1.0); + let t = t.clamp(0.0, 1.0); let gap = hypot([p[0] - pa[k][0] - t * d[k][0], p[1] - pa[k][1] - t * d[k][1]]) * unit[k]; - if gap <= PARALLEL_M && best.is_none_or(|b| gap < b.0) { + let limit = if rail(w) { PARALLEL_M } else { net.half[w] + net.half[other] }; + if gap <= limit && best.is_none_or(|b| gap < b.0) { best = Some((gap, k, t)); } } @@ -282,34 +340,92 @@ pub(crate) fn parallels(net: &Network, classes: &Classes, terrain: &dyn Terrain) pins } -/// The rows of the fords: a road vertex that a waterway shares, and the point where a way tagged as -/// a ford crosses a waterway, lie FORD_M below the water there. A bridge or a tunnel has no ford. -pub(crate) fn fords(net: &Network, rivers: &[&River]) -> Pins<3> { - let mut pins = Pins::default(); - if rivers.is_empty() { - return pins; +/// The arms at a point: per OSM variable, of the ways of roads and paths and of the railways; per +/// point, of the open water. An end of a part is one arm, a vertex inside it two. +struct Arms { + ways: [Vec; 2], + water: HashMap<[u64; 2], u32>, +} + +impl Arms { + fn new(net: &Network, rivers: &[&River], classes: &Classes) -> Self { + let mut ways = [vec![0u32; net.osm_count], vec![0u32; net.osm_count]]; + let ends = |o: usize| { + let w = net.osm_way[o]; + net.osm_first[w] == o || net.osm_first.get(w + 1).map_or(net.osm_xy.len(), |&f| f) == o + 1 + }; + for o in 0..net.osm_xy.len() { + let group = usize::from(classes.rows[net.rule[net.osm_way[o]]].rail); + ways[group][net.osm_var[o]] += if ends(o) { 1 } else { 2 }; + } + let mut water: HashMap<[u64; 2], u32> = HashMap::new(); + for river in rivers { + let last = river.points.len().saturating_sub(1); + for (k, point) in river.points.iter().enumerate() { + *water.entry(key(*point)).or_default() += if k == 0 || k == last { 1 } else { 2 }; + } + } + Arms { ways, water } } + + /// The arms of the group of way `w` at its vertex `v`: two at a vertex that OSM does not have. + fn way(&self, net: &Network, classes: &Classes, w: usize, v: usize) -> u32 { + if !net.vertex_osm[v] { + return 2; + } + self.ways[usize::from(classes.rows[net.rule[w]].rail)][net.vertex_var[v]] + } +} + +/// The OSM vertices that a ford pins, with the level of their water: a vertex of a road or a path on the +/// ground that open water shares, where each passes through it or meets another part of its own there. +/// A railway takes the untagged rule there, a road or a track too where the water is a culvert's +/// (`River::untagged_culvert`), and stepping stones keep their path's height. +fn shared_fords(net: &Network, rivers: &[&River], arms: &Arms, classes: &Classes) -> Vec<(usize, f64)> { let mut levels: HashMap<[u64; 2], f64> = HashMap::new(); - let mut segments = Vec::new(); + let mut wide = HashSet::new(); for river in rivers { for (point, &level) in river.points.iter().zip(&river.levels) { if level.is_finite() { levels.entry(key(*point)).or_insert(level); } + if !river.untagged_culvert { + wide.insert(key(*point)); + } } + } + let wet = |o: usize| arms.water.get(&key(net.osm_xy[o])).is_some_and(|&n| n >= 2); + (0..net.osm_xy.len()) + .filter(|&o| { + let w = net.osm_way[o]; + !net.free[w] && !net.stones[w] && !classes.rows[net.rule[w]].rail && arms.ways[0][net.osm_var[o]] >= 2 + }) + .filter(|&o| net.rule[net.osm_way[o]] >= classes.path || wide.contains(&key(net.osm_xy[o]))) + .filter(|&o| wet(o)) + .filter_map(|o| Some((o, *levels.get(&key(net.osm_xy[o]))?))) + .collect() +} + +/// The rows of the fords: a shared vertex of `shared_fords`, and the point where a way tagged as a ford +/// crosses a waterway, lie FORD_M below the water there; a road or a track tagged as a ford takes the +/// untagged rule over a culvert's water. A bridge or a tunnel has no ford. +pub(crate) fn fords(net: &Network, rivers: &[&River], classes: &Classes) -> Pins<3> { + let mut pins = Pins::default(); + if rivers.is_empty() { + return pins; + } + let mut segments = Vec::new(); + for river in rivers { for k in 1..river.points.len() { let (zp, zq) = (river.levels[k - 1], river.levels[k]); if !zp.is_nan() && !zq.is_nan() { - segments.push((river.points[k - 1], river.points[k], zp, zq)); + segments.push((river.points[k - 1], river.points[k], zp, zq, river.untagged_culvert)); } } } - for o in 0..net.osm_xy.len() { - if !net.free[net.osm_way[o]] { - if let Some(level) = levels.get(&key(net.osm_xy[o])) { - pins.push([net.osm_var[o]; 3], [1.0, 0.0, 0.0], level - FORD_M); - } - } + let arms = Arms::new(net, rivers, classes); + for (o, level) in shared_fords(net, rivers, &arms, classes) { + pins.push([net.osm_var[o]; 3], [1.0, 0.0, 0.0], level - FORD_M); } let fords: Vec = (0..net.ford.len()).filter(|&w| net.ford[w] && !net.free[w]).collect(); if fords.is_empty() { @@ -320,7 +436,10 @@ pub(crate) fn fords(net: &Network, rivers: &[&River]) -> Pins<3> { for v in net.way_first[w]..net.way_last[w] { let (p, q) = (net.vertex_xy[v], net.vertex_xy[v + 1]); for number in grid.near(p, q) { - let (r0, r1, z0, z1) = segments[number]; + let (r0, r1, z0, z1, narrow) = segments[number]; + if narrow && net.rule[w] < classes.path { + continue; + } if let Some((u, tr)) = crossing(p, q, r0, r1) { let variables = [net.vertex_var[v], net.vertex_var[v + 1], net.vertex_var[v]]; pins.push(variables, [1.0 - u, u, 0.0], z0 + (z1 - z0) * tr - FORD_M); @@ -331,19 +450,148 @@ pub(crate) fn fords(net: &Network, rivers: &[&River]) -> Pins<3> { pins } +/// A crossing of a way on the ground with open water that the way crosses on a culvert without a tag: +/// segment `segment` (vertices `segment`, `segment + 1`) of way `way` at `u`, segment `k` (points `k`, +/// `k + 1`) of `rivers[river]` at `tr`, their point, and the sine of their angle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct UntaggedCrossing { + pub way: usize, + pub segment: usize, + pub u: f64, + pub river: usize, + pub k: usize, + pub tr: f64, + pub point: [f64; 2], + pub sin: f64, +} + +/// The crossings of a road, a track or a railway on the ground, tagged as a ford or not, with open water no +/// wider than `culvert_width_m` with known levels, at GRAZE_DEG or more. A crossing as near a ford of its +/// way, along it, as the grade of its class lets the way climb from FORD_M under the water to its cover +/// is none. Where one ends on the other there is no crossing, and a point of both gives one, the first. +/// In the order of the ways, their segments and the water's segments. +pub(crate) fn untagged_crossings(net: &Network, rivers: &[&River], classes: &Classes) -> Vec { + let mut out = Vec::new(); + let mut water: Vec<(usize, usize)> = Vec::new(); + for (r, river) in rivers.iter().enumerate().filter(|(_, r)| r.untagged_culvert) { + let known = |k: usize| !river.levels[k].is_nan() && !river.levels[k + 1].is_nan(); + water.extend((0..river.points.len().saturating_sub(1)).filter(|&k| known(k)).map(|k| (r, k))); + } + if water.is_empty() { + return out; + } + let grid = Grid::new(water.iter().map(|&(r, k)| (rivers[r].points[k], rivers[r].points[k + 1]))); + let arms = Arms::new(net, rivers, classes); + // Metres along its way at each vertex. + let mut along = vec![0.0; net.vertex_xy.len()]; + for (s, &v) in net.segment_start.iter().enumerate() { + along[v + 1] = along[v] + net.length[s]; + } + let mut ford_at: Vec> = vec![Vec::new(); net.free.len()]; + for (o, _) in shared_fords(net, rivers, &arms, classes) { + ford_at[net.osm_way[o]].push(along[net.osm_position[o]]); + } + let graze = GRAZE_DEG.to_radians().sin(); + let mut seen = HashSet::new(); + for w in (0..net.free.len()).filter(|&w| !net.free[w] && !net.tunnel[w] && !net.indoor[w]) { + if net.rule[w] >= classes.path { + continue; + } + let grade = classes.rows[net.rule[w]].grade; + for v in net.way_first[w]..net.way_last[w] { + let (p, q) = (net.vertex_xy[v], net.vertex_xy[v + 1]); + for number in grid.near(p, q) { + let (r, k) = water[number]; + let river = rivers[r]; + let (r0, r1) = (river.points[k], river.points[k + 1]); + let last = k + 2 == river.points.len(); + // A point of both lies at the ends of both segments: by its key, as the parameters of + // `crossing` there can miss the ends by a rounding. + let shared = [(p, 0.0), (q, 1.0)] + .into_iter() + .flat_map(|(x, u)| [(r0, 0.0), (r1, 1.0)].map(|(y, tr)| (key(x) == key(y)).then_some((u, tr)))) + .flatten() + .next(); + let crossed = shared + .or_else(|| crossing(p, q, r0, r1)) + .filter(|&(u, tr)| (u < 1.0 || v + 1 == net.way_last[w]) && (tr < 1.0 || last)); + let Some((u, tr)) = crossed else { continue }; + let (d, e) = (sub(q, p), sub(r1, r0)); + let sin = (d[0] * e[1] - d[1] * e[0]).abs() / (hypot(d) * hypot(e)).max(1e-300); + if sin < graze { + continue; + } + let at = along[v] + u * (along[v + 1] - along[v]); + let reach = if grade.is_finite() { (river.cover + FORD_M) / grade } else { 0.0 }; + if ford_at[w].iter().any(|&f| (at - f).abs() <= reach) { + continue; + } + let point = [p[0] + u * d[0], p[1] + u * d[1]]; + // Where they meet at a point of both, or an end of one lies on the other's vertex chord + // (GP2's exact test, on the tiles' whole units), each needs 2 arms there, and the point + // gives one crossing. + let water_arms = |at: [f64; 2]| arms.water.get(&key(at)).copied().unwrap_or(0); + let meet = if let Some((u, tr)) = shared { + let at = if u == 0.0 { v } else { v + 1 }; + Some(( + arms.way(net, classes, w, at), + water_arms(if tr == 0.0 { r0 } else { r1 }), + net.vertex_xy[at], + )) + } else { + let (a, b) = chord(net, v); + let way_end = [net.way_first[w], net.way_last[w]] + .into_iter() + .filter(|&e| e == v || e == v + 1) + .find(|&e| end_on_chord(grid_point(net.vertex_xy[e]), grid_point(r0), grid_point(r1))) + .map(|e| (arms.way(net, classes, w, e), 2, net.vertex_xy[e])); + let water_end = [(0, r0), (river.points.len() - 1, r1)] + .into_iter() + .filter(|&(i, _)| i == k || i == k + 1) + .map(|(_, at)| at) + .find(|&at| end_on_chord(grid_point(at), grid_point(a), grid_point(b))) + .map(|at| (2, water_arms(at), at)); + way_end.or(water_end) + }; + if let Some((way_arms, water_arms, at)) = meet { + if way_arms < 2 || water_arms < 2 || !seen.insert(key(at)) { + continue; + } + } + out.push(UntaggedCrossing { way: w, segment: v, u, river: r, k, tr, point, sin }); + } + } + } + out +} + +/// A world point at the whole units of the zoom-13 tiles, where a waterway's vertex lies, in the +/// ground plan's frame. +fn grid_point([x, y]: [f64; 2]) -> GlobalPoint { + let units = |v: f64| ((v * (1u64 << 27) as f64).round_ties_even() as i64) << 7; + GlobalPoint { x: units(x), y: units(y) } +} + +/// The vertex chord of the network segment from vertex v: the OSM vertices before and after it. +fn chord(net: &Network, v: usize) -> ([f64; 2], [f64; 2]) { + let a = (0..=v).rev().find(|&i| net.vertex_osm[i]).unwrap_or(v); + let b = (v + 1..net.vertex_xy.len()).find(|&i| net.vertex_osm[i]).unwrap_or(v + 1); + (net.vertex_xy[a], net.vertex_xy[b]) +} + /// The rows of the cover over a culvert, and per row its way: where a road or a track on the ground -/// crosses a culvert part, and where a bridge of one crosses a waterway, z ≥ the water there + the cover -/// of the waterway. The solve holds the rows of a bridge only where it is a culvert. A path, a tunnel, a -/// culvert part without a level and a crossing whose water lies over the terrain have none: the levels -/// there are not those of the pipe, which runs under the ground. Per row, its way and the most that the -/// cover may lift it. +/// crosses a culvert part, where a bridge of one crosses a waterway, and at each `untagged` crossing, +/// z ≥ the water there + the cover of the waterway. The solve holds the rows of a bridge only where it +/// is a culvert. A path, a tunnel, a culvert part without a level and a crossing whose water lies over +/// the terrain have none: the levels there are not those of the pipe, which runs under the ground. Per +/// row, its way and the most that the cover may lift it, and its untagged crossing, None for a tagged row. pub(crate) fn covers( net: &Network, - culverts: &[&River], - rivers: &[&River], + (culverts, rivers): (&[&River], &[&River]), + untagged: &[UntaggedCrossing], classes: &Classes, terrain: &dyn Terrain, -) -> (Pins<3>, Vec<(usize, f64)>) { +) -> (Pins<3>, Vec<(usize, f64)>, Vec>) { // A crossing at a shared vertex counts on the segment that it ends. let water = |list: &[&River]| -> Vec { let pairs = list.iter().flat_map(|r| (1..r.points.len()).map(move |k| (r, k))); @@ -375,13 +623,25 @@ pub(crate) fn covers( } } } - (pins, ways) + let mut crossing_of = vec![None; ways.len()]; + for (n, c) in untagged.iter().enumerate() { + let river = rivers[c.river]; + let (z0, z1) = (river.levels[c.k], river.levels[c.k + 1]); + let water = z0 + (z1 - z0) * c.tr; + if water <= terrain.height(c.point) { + let variables = [net.vertex_var[c.segment], net.vertex_var[c.segment + 1], net.vertex_var[c.segment]]; + pins.push(variables, [1.0 - c.u, c.u, 0.0], water + river.cover); + ways.push((c.way, river.lift)); + crossing_of.push(Some(n)); + } + } + (pins, ways, crossing_of) } /// The rows of the decks over what they cross, and per row its bridge: where a bridge segment /// crosses a waterway, z ≥ water + CLEAR_WATER_M + its deck; where it crosses a road, a path or a /// track on the ground that it does not meet, z − z_below ≥ CLEAR_ROAD_M, CLEAR_PATH_M or -/// CLEAR_RAIL_M + its deck; but a bridge whose end lies on that road, within its half-width, meets it +/// CLEAR_RAIL_M + its deck; but a bridge whose end lies on that road, within its outer half-width, meets it /// there and has no row. Where a bridge lands at a height that it cannot move (`landings`), its deck /// climbs no steeper than it runs: a crossing that asks more lies where the bridge lands and has no row. pub(crate) fn clearances( @@ -458,7 +718,7 @@ pub(crate) fn clearances( continue; } if !((0.0..1.0).contains(&tr) && (0.0..1.0).contains(&u)) - || tips.iter().any(|&tip| (at - tip).abs() <= net.half[other]) + || tips.iter().any(|&tip| (at - tip).abs() <= net.outer[other]) { continue; } @@ -481,8 +741,26 @@ fn clearance(net: &Network, classes: &Classes, lower: usize) -> f64 { } } -/// The variables where a bridge lands at a height that it cannot move: an end that meets no other way -/// stands on the terrain, and one that leaves a junction as a side lies on its through road. +/// Per variable, whether a bridge ends there on the terrain: an end that meets no other way, or one that meets +/// a tunnel. A portal stands on the terrain: a tunnel is a long lever, which would carry a slope or a pass at +/// its other end to a deck that nothing else holds. +pub(crate) fn standing(net: &Network) -> Vec { + let mut tunnel = vec![false; net.count]; + for s in (0..net.a.len()).filter(|&s| net.tunnel[net.segment_way[s]]) { + tunnel[net.a[s]] = true; + tunnel[net.b[s]] = true; + } + let mut out = vec![false; net.count]; + for w in (0..net.free.len()).filter(|&w| net.free[w] && !net.tunnel[w]) { + for v in [net.vertex_var[net.way_first[w]], net.vertex_var[net.way_last[w]]] { + out[v] = !net.junction[v] || tunnel[v]; + } + } + out +} + +/// The variables where a bridge lands at a height that it cannot move: an end that stands on the terrain +/// (`standing`), and one that leaves a junction as a side lies on its through road. pub(crate) fn landings(net: &Network) -> HashSet { let mut ends = HashSet::new(); for w in (0..net.free.len()).filter(|&w| net.free[w] && !net.tunnel[w]) { @@ -490,7 +768,8 @@ pub(crate) fn landings(net: &Network) -> HashSet { ends.insert(net.osm_first[w]); ends.insert(last); } - let loose = ends.iter().filter(|&&o| !net.junction[net.osm_var[o]]); + let standing = standing(net); + let loose = ends.iter().filter(|&&o| standing[net.osm_var[o]]); let sides = net.sides.occurrence.iter().filter(|o| ends.contains(o)); loose.chain(sides).map(|&o| net.osm_var[o]).collect() } @@ -532,30 +811,41 @@ pub(crate) fn passes(net: &Network, classes: &Classes) -> Passes { return; } let above = ([va, vb], [1.0 - u, u]); - let mut places = vec![r]; + let mut places = vec![(k, r)]; let tunnel_under_road = net.tunnel[lower] && !net.free[upper]; if tunnel_under_road { - // Where the tunnel's line meets each edge of the road, on this segment of the tunnel at most. + // Where the tunnel's line meets each edge of the road, on the segment of the tunnel nearest to it. let e = sub(q, p); let (norm, half, unit) = (hypot(e), net.half[upper], metres(p[1])); let side = [-e[1] / norm * half / unit, e[0] / norm * half / unit]; + let (start, end) = (net.vertex_xy[k], net.vertex_xy[k + 1]); for offset in [side, [-side[0], -side[1]]] { - let Some((edge, _)) = - lines(net.vertex_xy[k], net.vertex_xy[k + 1], [p[0] + offset[0], p[1] + offset[1]], e) + let Some((edge, _)) = lines(start, end, [p[0] + offset[0], p[1] + offset[1]], e) else { continue }; + let at = [start[0] + edge * (end[0] - start[0]), start[1] + edge * (end[1] - start[1])]; + let foot = |j: usize| { + let (a, d) = (net.vertex_xy[j], sub(net.vertex_xy[j + 1], net.vertex_xy[j])); + dot(sub(at, a), d) / dot(d, d).max(1e-300) + }; + let gap = |j: usize| { + let (a, d, x) = + (net.vertex_xy[j], sub(net.vertex_xy[j + 1], net.vertex_xy[j]), foot(j).clamp(0.0, 1.0)); + hypot(sub(at, [a[0] + x * d[0], a[1] + x * d[1]])) + }; + let Some(j) = (net.way_first[lower]..net.way_last[lower]).min_by(|&i, &j| gap(i).total_cmp(&gap(j))) else { continue; }; - let x = edge.clamp(0.0, 1.0); + let x = foot(j).clamp(0.0, 1.0); // An edge past a portal would pin the portal, and with it the way on the ground that leaves it. - if x != edge && grounded[under[x as usize]] { + if x != foot(j) && grounded[net.vertex_var[j + x as usize]] { continue; } - places.push(x); + places.push((j, x)); } } - for x in places { + for (j, x) in places { out.upper.push(above); - out.lower.push((under, [1.0 - x, x])); + out.lower.push(([net.vertex_var[j], net.vertex_var[j + 1]], [1.0 - x, x])); out.margin.push(margin); out.lower_way.push(lower); out.moves.push(!tunnel_under_road); diff --git a/host/obc-trailview-features/src/roads/sidewalks.rs b/host/obc-trailview-features/src/roads/sidewalks.rs index 4b8a44dc99..b3d141587e 100644 --- a/host/obc-trailview-features/src/roads/sidewalks.rs +++ b/host/obc-trailview-features/src/roads/sidewalks.rs @@ -13,7 +13,7 @@ use rstar::RTree; use super::align::Curve; use super::network::{dot, hypot, sub, Network}; -use super::rows::{root, union}; +use super::rows::{root, union, UntaggedCrossing}; use super::{Classes, River}; use crate::geometry::{key, Boxes}; use crate::kinds::SIDEWALK_MAX_M; @@ -64,14 +64,16 @@ pub(crate) struct Piece { pub last: usize, } -/// A bed on the ground: a segment, its half-width, its way, None for a waterway, and per end whether it -/// is a culvert's mouth there, where a waterway's bed ends. +/// A bed on the ground: a segment, its half-width, its way, None for a waterway, per end whether it is +/// a culvert's mouth there, where a waterway's bed ends, and the pipes of untagged culverts under it as +/// (point, metres along the water that the pipe runs each way). struct Bed { p: [f64; 2], q: [f64; 2], half: f64, way: Option, mouth: [bool; 2], + pipes: Vec<([f64; 2], f64)>, } /// What the sidewalks of a solve read besides the strokes. @@ -87,9 +89,13 @@ pub(crate) struct Town<'a> { } impl<'a> Town<'a> { + /// The pipe of an untagged culvert runs under its road and the road's sidewalks: as far along the + /// water from the crossing as the road's outer half-width, its widening and the bed's half-width + /// reach at the angle of the crossing. pub fn new( net: &Network, (rivers, culverts): (&[&River], &[&River]), + (untagged, classes): (&[UntaggedCrossing], &Classes), buildings: Option<&'a RTree<[f64; 2]>>, terrain: &'a dyn Terrain, ) -> Self { @@ -98,16 +104,28 @@ impl<'a> Town<'a> { for (s, &w) in net.segment_way.iter().enumerate().filter(|&(_, &w)| !net.free[w]) { let v = net.segment_start[s]; let (p, q) = (net.vertex_xy[v], net.vertex_xy[v + 1]); - beds.push(Bed { p, q, half: net.half[w], way: Some(w), mouth: [false; 2] }); + beds.push(Bed { p, q, half: net.half[w], way: Some(w), mouth: [false; 2], pipes: Vec::new() }); } - for river in rivers { + for (r, river) in rivers.iter().enumerate() { let mouth = |point: &[f64; 2]| mouths.contains(&key(*point)); - let bed = |p: &[[f64; 2]]| Bed { - p: p[0], - q: p[1], - half: river.half, - way: None, - mouth: [mouth(&p[0]), mouth(&p[1])], + let pipes: Vec<([f64; 2], f64)> = untagged + .iter() + .filter(|c| c.river == r) + .map(|c| { + let reach = net.outer[c.way] + classes.rows[net.rule[c.way]].widen_m + river.half; + (c.point, reach / c.sin) + }) + .collect(); + let bed = |p: &[[f64; 2]]| { + let near = |&&(at, reach): &&([f64; 2], f64)| distance(at, p[0], p[1]) * metres(at[1]) < reach; + Bed { + p: p[0], + q: p[1], + half: river.half, + way: None, + mouth: [mouth(&p[0]), mouth(&p[1])], + pipes: pipes.iter().filter(near).copied().collect(), + } }; beds.extend(river.points.windows(2).map(bed)); } @@ -270,7 +288,7 @@ impl<'a> Town<'a> { }) }; self.boxes.overlapping([point[0], point[1], point[0], point[1]]).into_iter().all(|b| { - let Bed { p, q, half, way, mouth } = self.beds[b]; + let Bed { p, q, half, way, mouth, ref pipes } = self.beds[b]; if way.is_some_and(|o| net.way_feature[o].0 == net.way_feature[w].0 || joined(o)) { return true; } @@ -279,11 +297,19 @@ impl<'a> Town<'a> { let foot = [p[0] + t * d[0], p[1] + t * d[1]]; // An open waterway's bed ends at a culvert's mouth: the pipe runs on under the road and its sidewalks. let at_mouth = [p, q].iter().zip(mouth).any(|(&end, m)| m && hypot(sub(foot, end)) * scale < reach); - at_mouth || hypot(sub(foot, point)) * scale >= reach + let piped = pipes.iter().any(|&(at, length)| hypot(sub(foot, at)) * scale < length); + at_mouth || piped || hypot(sub(foot, point)) * scale >= reach }) } } +/// The distance from `point` to the segment p-q, in world units. +fn distance(point: [f64; 2], p: [f64; 2], q: [f64; 2]) -> f64 { + let d = sub(q, p); + let t = (dot(sub(point, p), d) / dot(d, d).max(1e-300)).clamp(0.0, 1.0); + hypot(sub(point, [p[0] + t * d[0], p[1] + t * d[1]])) +} + /// Per segment of a stroke of `n` samples, its piece. fn owners(pieces: &[Piece], n: usize) -> Vec { let mut owner = vec![0; n.saturating_sub(1)]; diff --git a/host/obc-trailview-features/src/roads/tests.rs b/host/obc-trailview-features/src/roads/tests.rs index 1db3893e0f..0726e6336c 100644 --- a/host/obc-trailview-features/src/roads/tests.rs +++ b/host/obc-trailview-features/src/roads/tests.rs @@ -79,11 +79,11 @@ impl Place { } } -/// A way of a class with `half` of a road without a width; `edit` sets its other facts. +/// A way of a class with the half-widths of a road without a width; `edit` sets its other facts. pub(super) fn way(class: &str, points: Vec<[f64; 2]>, edit: impl FnOnce(&mut Feature)) -> Feature { let (names, _) = table(); let rule = names.iter().position(|n| n == class).unwrap(); - let mut feature = Feature { rule, half: 3.0, parts: vec![points], ..Default::default() }; + let mut feature = Feature { rule, half: 3.0, outer: 3.0, parts: vec![points], ..Default::default() }; edit(&mut feature); feature } @@ -148,6 +148,127 @@ fn a_hairpin_climbs_within_the_grade_of_its_class() { assert!((z[z.len() - 1] - (1000.0 + 0.30 * 92.0)).abs() < 0.5); } +#[test] +fn a_road_across_a_steep_slope_keeps_its_grade_where_the_terrain_under_its_line_humps() { + // A slope that rises 2 m per metre north, with a nose 15 m high under the line of the road: the terrain + // across the road's width spans 16 m, and the nose is no bed for the road. + let place = engelberg(); + let height = |e: f64, n: f64| 1000.0 + 2.0 * n + 15.0 * (-((e - 250.0) / 8.0).powi(2)).exp(); + let road = way("primary", place.line(&[(0.0, 0.0), (500.0, 0.0)], Some(20.0)), |f| f.half = 4.0); + let curve = place.curve(&run(&[road], &place.terrain(height), &[]).ways[0][0]); + let z = curve.z.unwrap(); + let at: Vec<(f64, f64)> = curve.points.iter().map(|&p| place.east_north(p)).collect(); + for k in 1..z.len() { + let grade = (z[k] - z[k - 1]) / (at[k].0 - at[k - 1].0).hypot(at[k].1 - at[k - 1].1); + assert!(grade.abs() <= 0.12 + 1e-3, "grade {grade} at {} m east", at[k].0); + } + // Each vertex lies within GROUND_M of the terrain across the road. + for (&(e, n), &z) in at.iter().zip(&z) { + let (low, high) = (height(e, n - 4.0), height(e, n + 4.0)); + assert!(z >= low - GROUND_M - KEEP_M && z <= high + GROUND_M + KEEP_M, "{z} at {e} m east"); + } +} + +#[test] +fn a_side_road_between_two_near_junctions_holds_its_grade() { + // A secondary ends at J on flat ground at 1000 m, where a residential runs on north. 4.4 m on, a + // path leaves the residential on flat ground at 1002 m. The residential is a side at J, but the + // path's junction is too near for a pin: nothing but its grade ties J to the path's junction. + let place = engelberg(); + let terrain = place.terrain(|_, n| 1000.0 + 2.0 * (n / 4.4).clamp(0.0, 1.0)); + let secondary = way("secondary", place.line(&[(-100.0, 0.0), (0.0, 0.0)], Some(20.0)), plain); + let residential = + way("residential", place.line(&[(0.0, -100.0), (0.0, 0.0), (0.0, 4.4), (0.0, 100.0)], Some(20.0)), plain); + let path = way("path", place.line(&[(0.0, 4.4), (60.0, 4.4)], Some(20.0)), plain); + let solved = run(&[secondary, residential, path], &terrain, &[]); + let rise = height_at(&solved.ways[1][0], place.at(0.0, 4.4)) - height_at(&solved.ways[1][0], place.at(0.0, 0.0)); + assert!(rise.abs() <= 0.20 * 4.4 + 0.01, "{rise} m over 4.4 m"); +} + +#[test] +fn a_path_leaves_a_road_as_a_ramp_and_climbs_on_with_the_terrain() { + // A road on a terrace 2 m over flat ground, with its edge 1 m beside it, and a path that leaves it + // north: past the approach, the path runs down as a ramp. On a hillside of 50 % instead, the path + // is back on the terrain at the ramp's end. + let place = engelberg(); + let terrace = place.terrain(|_, n| if n < 1.0 { 1002.0 } else { 1000.0 }); + let hill = place.terrain(|_, n| 1000.0 + 0.5 * n); + for (terrain, steep) in [(&terrace as &dyn Terrain, false), (&hill, true)] { + let road = way("residential", place.line(&[(-100.0, 0.0), (100.0, 0.0)], Some(20.0)), plain); + let path = way("path", place.line(&[(0.0, 0.0), (0.0, 60.0)], Some(2.0)), plain); + let (along, z) = place.profile(&run(&[road, path], terrain, &[]).ways[1][0]); + if steep { + for (&a, &z) in along.iter().zip(&z).filter(|(&a, _)| a >= RAMP_M) { + assert!((z - 1000.0 - 0.5 * a).abs() < 0.3, "{} m at {a} m", z - 1000.0 - 0.5 * a); + } + } else { + let ramp = + (interp(RAMP_M, &along, &z) - interp(APPROACH_M + 1.0, &along, &z)) / (RAMP_M - APPROACH_M - 1.0); + assert!((-RAMP_GRADE - 0.01..-0.05).contains(&ramp), "{ramp}"); + } + } +} + +#[test] +fn a_road_split_on_a_slope_keeps_the_slope() { + // OSM cuts a residential on an 8 % slope into two ways, with a vertex 3 m before the cut: the + // way that continues it is not a way beside it. + let place = engelberg(); + let terrain = place.terrain(|e, _| 1000.0 + 0.08 * e); + let west = way("residential", place.line(&[(-100.0, 0.0), (-3.0, 0.0), (0.0, 0.0)], Some(20.0)), plain); + let east = way("residential", place.line(&[(0.0, 0.0), (100.0, 0.0)], Some(20.0)), plain); + let solved = run(&[west, east], &terrain, &[]); + for (f, start) in [(0, -100.0), (1, 0.0)] { + let (along, z) = place.profile(&solved.ways[f][0]); + assert!(along.iter().zip(&z).all(|(&a, &z)| (z - 1000.0 - 0.08 * (start + a)).abs() < 0.05)); + } +} + +#[test] +fn steps_that_meet_a_footway_below_a_deck_do_not_move_the_deck() { + // A residential bridge 6 m over a valley floor, and steps from its middle that meet a footway on + // the floor some metres on. The smoothing of the steps alone draws the deck down by 0.61 m; their + // ramp bends the steps, and moves neither the deck nor the footway. + let place = engelberg(); + let terrain = place.terrain(|e, _| if e.abs() > 30.0 { 1006.0 } else { 1000.0 }); + for long in [12.0, 16.0, 20.0, 30.0] { + let solve = |steps: bool| { + let mut features = vec![ + way("residential", place.line(&[(-100.0, 0.0), (-30.0, 0.0)], Some(10.0)), plain), + way("residential", place.line(&[(-30.0, 0.0), (0.0, 0.0), (30.0, 0.0)], Some(10.0)), bridge), + way("residential", place.line(&[(30.0, 0.0), (100.0, 0.0)], Some(10.0)), plain), + way("footway", place.line(&[(-20.0, long), (0.0, long), (20.0, long)], Some(2.0)), plain), + ]; + if steps { + features.push(way("steps", place.line(&[(0.0, 0.0), (0.0, long)], Some(2.0)), plain)); + } + let solved = run(&features, &terrain, &[]); + let [(da, dz), (fa, fz)] = [1, 3].map(|f| place.profile(&solved.ways[f][0])); + (interp(30.0, &da, &dz), interp(20.0, &fa, &fz)) + }; + let ((alone, floor), (with, foot)) = (solve(false), solve(true)); + assert!(with - alone > -0.65, "at {long} m the deck moves from {alone} to {with}"); + assert!((foot - floor).abs() < 0.3, "at {long} m the footway moves from {floor} to {foot}"); + } +} + +#[test] +fn a_short_link_with_a_footway_off_its_middle_does_not_move_its_roads() { + // A residential link of 9 m between two secondaries 3 m apart in height, with a footway that + // leaves the link at its middle: the link is a side at both of its ends. + let place = engelberg(); + let terrain = place.terrain(|_, n| 1000.0 + if n > 4.5 { 3.0 } else { 0.0 }); + let features = [ + way("secondary", place.line(&[(-100.0, 0.0), (0.0, 0.0), (100.0, 0.0)], Some(20.0)), plain), + way("secondary", place.line(&[(-100.0, 9.0), (0.0, 9.0), (100.0, 9.0)], Some(20.0)), plain), + way("residential", place.line(&[(0.0, 0.0), (0.0, 4.5), (0.0, 9.0)], None), plain), + way("footway", place.line(&[(0.0, 4.5), (40.0, 4.5)], Some(10.0)), plain), + ]; + let solved = run(&features, &terrain, &[]); + assert!((height_at(&solved.ways[0][0], place.at(0.0, 0.0)) - 1000.0).abs() < 0.05); + assert!((height_at(&solved.ways[1][0], place.at(0.0, 9.0)) - 1003.0).abs() < 0.05); +} + #[test] fn a_side_road_meets_the_through_road_flat_and_on_one_height() { // The through road climbs east at 2 %, and from the junction on at 10 %, on a hillside that rises @@ -216,20 +337,23 @@ fn a_ford_lies_under_the_water_and_a_low_short_bridge_is_a_culvert() { way("track", line(&[(320.0, 80.0), (350.0, 80.0)]), plain), way("track", line(&[(300.0, 80.0), (320.0, 80.0)]), bridge), ]; + // Water wider than a culvert's: a track's ford there stays a ford. let streams = [ River { points: vec![place.at(50.0, -10.0), crossing, place.at(50.0, 10.0)], levels: vec![999.1, 999.0, 998.9], - half: 1.0, + half: 2.0, cover: 1.0, lift: 1.5, + untagged_culvert: false, }, River { points: vec![place.at(70.0, 20.0), place.at(70.0, 40.0)], levels: vec![998.6, 998.4], - half: 1.0, + half: 2.0, cover: 1.0, lift: 1.5, + untagged_culvert: false, }, ]; let solved = run(&features, &terrain, &streams); @@ -289,6 +413,26 @@ fn the_tracks_of_a_double_line_on_noisy_ground_lie_at_one_height() { assert!(sa.iter().zip(&sz).all(|(&a, &z)| (interp(a, &na, &nz) - z).abs() < 0.01)); } +#[test] +fn a_road_whose_carriageway_overlaps_another_lies_at_its_height() { + // A service road and a track 4.5 m apart on a slope across them: their carriageways overlap, and + // the terrain under them differs by 0.45 m. A narrower footway as far from the track does not + // reach it, and keeps its own height. + let place = engelberg(); + let terrain = place.terrain(|e, n| 500.0 + 0.02 * e + 0.1 * n); + let narrow = |f: &mut Feature| f.half = 1.0; + let features = [ + way("service", place.line(&[(0.0, 2.25), (300.0, 2.25)], Some(10.0)), plain), + way("track", place.line(&[(0.0, -2.25), (300.0, -2.25)], Some(10.0)), plain), + way("footway", place.line(&[(0.0, -6.75), (300.0, -6.75)], Some(10.0)), narrow), + ]; + let solved = run(&features, &terrain, &[]); + let [(na, nz), (sa, sz), (fa, fz)] = [0, 1, 2].map(|f| place.profile(&solved.ways[f][0])); + // Without the rule they lie 0.45 m apart; the kept curves leave the solve by a few centimetres. + assert!(sa.iter().zip(&sz).all(|(&a, &z)| (interp(a, &na, &nz) - z).abs() < 0.1)); + assert!(fa.iter().zip(&fz).all(|(&a, &z)| (interp(a, &sa, &sz) - z).abs() > 0.3)); +} + #[test] fn a_track_on_a_ramp_beside_a_level_track_keeps_its_own_height() { // The embankment north of the level track rises 8 m. @@ -347,6 +491,7 @@ fn a_road_over_a_culvert_holds_its_cover_a_path_keeps_its_height_and_no_cover_li half: 0.5, cover: 1.0, lift: 1.5, + untagged_culvert: true, }; let culverts = [culvert(0.0), culvert(200.0), culvert(400.0), River { cover: 2.0, ..culvert(600.0) }]; let refs: Vec<&Feature> = features.iter().collect(); @@ -378,6 +523,7 @@ fn a_culvert_bridge_of_a_road_holds_the_cover_over_its_water() { half: 0.5, cover: 1.0, lift: 1.5, + untagged_culvert: true, }; let solved = run(&features, &flat, &[stream]); assert_eq!(solved.culverts, BTreeSet::from([1])); @@ -402,6 +548,7 @@ fn a_deck_rises_over_the_water_and_the_road_that_it_crosses() { half: 1.0, cover: 1.0, lift: 1.5, + untagged_culvert: true, }; let solved = run(&features, &flat, &[river]); assert_eq!((solved.metrics.clearances, solved.metrics.clearances_low_cm), (2, 0)); @@ -430,6 +577,7 @@ fn a_stream_by_the_end_of_a_footbridge_neither_levers_it_up_nor_lifts_it_off_the half: 1.0, cover: 1.0, lift: 1.5, + untagged_culvert: true, }; let features = [path(line(&[(-50.0, 0.0), (0.0, 0.0)]), plain), path(line(&[(0.0, 0.0), (9.0, 0.0)]), bridge)]; let solved = run(&features, &flat, &[river]); @@ -445,6 +593,7 @@ fn a_stream_by_the_end_of_a_footbridge_neither_levers_it_up_nor_lifts_it_off_the half: 1.0, cover: 1.0, lift: 1.5, + untagged_culvert: true, }; let features = [path(line(&[(-50.0, 0.0), (50.0, 0.0)]), plain), path(line(&[(0.0, 0.0), (0.0, 9.0)]), bridge)]; let solved = run(&features, &flat, &[river]); @@ -475,6 +624,7 @@ fn a_short_bridge_over_a_ditch_clears_its_water_and_one_on_the_ground_is_a_culve half: 1.0, cover: 1.0, lift: 1.5, + untagged_culvert: true, }) .collect(); let solved = run(&features, &terrain, &rivers); @@ -526,33 +676,184 @@ fn a_long_tunnel_runs_straight_between_its_portals_and_a_shaft_does_not_lift_it( way.points.iter().zip(&way.z).map(|(&p, &z)| (place.east_north(p).0, z)).collect::>() }) .collect(); + // The straight line weighs less than the ground (`BORE`): the shaft moves it by a centimetre or two. let (first, last) = (vertices[0].1, vertices[vertices.len() - 1].1); for &(e, z) in &vertices { - assert!((z - interp(e, &[-3000.0, 3000.0], &[first, last])).abs() < 0.01); + assert!((z - interp(e, &[-3000.0, 3000.0], &[first, last])).abs() < 0.02); } assert!(vertices.iter().all(|&(_, z)| z < 1001.0)); } #[test] fn a_tunnel_sinks_under_the_whole_width_of_the_road_over_it_and_the_road_stays() { - // The north portal lies just past the motorway's edge, its half-width from its centreline. + // The north portal lies just past the motorway's edge, its half-width from its centreline. The + // motorway runs on a bank 3 m high, so its tunnel's portals lie within GROUND_M of the terrain. let place = bridges(); let line = |corners: &[(f64, f64)]| place.line(corners, None); let main_half = 6.0; + let bank = place.terrain(move |_, n| if n.abs() <= main_half { 503.0 } else { 500.0 }); let features = [ way("motorway", line(&[(-200.0, 0.0), (200.0, 0.0)]), |f| f.half = main_half), way("unclassified", line(&[(5.0, -200.0), (5.0, -20.0)]), plain), way("unclassified", line(&[(5.0, -20.0), (5.0, 7.0)]), tunnel), way("unclassified", line(&[(5.0, 7.0), (5.0, 200.0)]), plain), ]; - let solved = run(&features, &flat, &[]); + let solved = run(&features, &bank, &[]); assert_eq!(solved.underpasses, BTreeSet::from([2])); let (ra, rz) = place.profile(&solved.ways[0][0]); - assert!((interp(205.0, &ra, &rz) - 500.0).abs() < 0.05); + assert!((interp(205.0, &ra, &rz) - 503.0).abs() < 0.05); let (ta, tz) = place.profile(&solved.ways[2][0]); for north in [-main_half, 0.0, main_half] { - assert!(interp(north + 20.0, &ta, &tz) <= 500.0 - BORE_M - COVER_M + 0.01); + assert!(interp(north + 20.0, &ta, &tz) <= 503.0 - BORE_M - COVER_M + 0.01); + } +} + +/// Whether each vertex of the curve of a solved way lies within GROUND_M of the terrain, and the +/// curve's KEEP_M off the heights of the solve. +fn on_the_ground(place: &Place, part: &Option, terrain: &dyn Terrain) -> bool { + let curve = place.curve(part); + let ground = terrain.heights(&curve.points); + curve.z.unwrap().iter().zip(ground).all(|(z, h)| (z - h).abs() <= GROUND_M + KEEP_M) +} + +#[test] +fn a_road_over_a_tunnel_by_its_portal_does_not_lever_its_far_portal_off_the_terrain() { + // A slope with a mountain over the tunnel; the road crosses 20 m from the lower portal, where the + // tunnel's straight line lies too near it. + let place = bridges(); + let height = |e: f64| { + let inside = (e.clamp(-1000.0, 1000.0) + 1000.0) / 2000.0; + 500.0 + 400.0 * inside + 100.0 * (std::f64::consts::PI * inside).sin() + }; + let terrain = place.terrain(move |e, _| height(e)); + let line = |corners: &[(f64, f64)]| place.line(corners, None); + let features = [ + way("primary", line(&[(-1200.0, 0.0), (-1000.0, 0.0)]), plain), + way("primary", line(&[(-1000.0, 0.0), (1000.0, 0.0)]), tunnel), + way("primary", line(&[(1000.0, 0.0), (1200.0, 0.0)]), plain), + way("unclassified", line(&[(-980.0, -100.0), (-980.0, 100.0)]), plain), + ]; + let solved = run(&features, &terrain, &[]); + for f in [0, 2, 3] { + assert!(on_the_ground(&place, &solved.ways[f][0], &terrain), "way {f}"); + } +} + +#[test] +fn a_bridge_that_meets_a_tunnel_stands_on_the_terrain_at_the_portal() { + // As above, but the upper portal opens onto a bridge: the portal stands on the terrain, and the tunnel's line + // does not lever the deck. + let place = bridges(); + let height = |e: f64| { + let inside = (e.clamp(-1000.0, 1000.0) + 1000.0) / 2000.0; + 500.0 + 400.0 * inside + 100.0 * (std::f64::consts::PI * inside).sin() + }; + let terrain = place.terrain(move |e, _| height(e)); + let line = |corners: &[(f64, f64)]| place.line(corners, None); + let features = [ + way("primary", line(&[(-1200.0, 0.0), (-1000.0, 0.0)]), plain), + way("primary", line(&[(-1000.0, 0.0), (1000.0, 0.0)]), tunnel), + way("primary", line(&[(1000.0, 0.0), (1100.0, 0.0)]), bridge), + way("primary", line(&[(1100.0, 0.0), (1300.0, 0.0)]), plain), + way("unclassified", line(&[(-980.0, -100.0), (-980.0, 100.0)]), plain), + ]; + let solved = run(&features, &terrain, &[]); + let deck = solved.ways[2][0].as_ref().unwrap(); + assert!((deck.z[0] - height(1000.0)).abs() <= GROUND_M + KEEP_M, "{}", deck.z[0]); + for f in [0, 3, 4] { + assert!(on_the_ground(&place, &solved.ways[f][0], &terrain), "way {f}"); + } +} + +#[test] +fn a_path_that_meets_a_tunnel_inside_the_mountain_is_a_portal_and_stays_on_the_ground() { + let place = bridges(); + let terrain = place.terrain(|e, _| if e.abs() < 995.0 { 700.0 } else { 500.0 }); + let line = |corners: &[(f64, f64)]| place.line(corners, None); + let features = [ + way("primary", line(&[(-1200.0, 0.0), (-1000.0, 0.0)]), plain), + way("primary", line(&[(-1000.0, 0.0), (0.0, 0.0), (1000.0, 0.0)]), tunnel), + way("primary", line(&[(1000.0, 0.0), (1200.0, 0.0)]), plain), + way("path", line(&[(0.0, 0.0), (0.0, 200.0)]), plain), + ]; + let solved = run(&features, &terrain, &[]); + assert!(on_the_ground(&place, &solved.ways[3][0], &terrain)); + // The tunnel runs straight from each portal to the path, but for the smoothness of its class, which rounds + // the kink at the path: the straight line weighs less (`BORE`). + let (along, z) = place.profile(&solved.ways[1][0]); + let (low, top) = (interp(0.0, &along, &z), interp(1000.0, &along, &z)); + assert!((interp(500.0, &along, &z) - (low + top) / 2.0).abs() < 0.5); +} + +/// The steepest climb of a solved way over any 10 m of its curve. +fn steepest(place: &Place, part: &Option) -> f64 { + let (along, z) = place.profile(part); + let mut most: f64 = 0.0; + for i in 0..along.len() { + if let Some(j) = (i + 1..along.len()).find(|&j| along[j] - along[i] >= 10.0) { + most = most.max((z[j] - z[i]).abs() / (along[j] - along[i])); + } + } + most +} + +#[test] +fn a_tunnel_on_a_slope_steeper_than_its_grade_keeps_its_portals_on_the_terrain_and_climbs_as_the_terrain() { + // A primary tunnel of 1000 m between two portals that the terrain lifts by 20 %, past the 12 % of its class, + // with a mountain over it: the grade between portals holds the tunnel and never pulls a portal off the terrain. + let place = bridges(); + let height = |e: f64| { + let inside = (e.clamp(-500.0, 500.0) + 500.0) / 1000.0; + 500.0 + 200.0 * inside + 100.0 * (std::f64::consts::PI * inside).sin() + }; + let terrain = place.terrain(move |e, _| height(e)); + let line = |corners: &[(f64, f64)]| place.line(corners, None); + let features = [ + way("primary", line(&[(-700.0, 0.0), (-500.0, 0.0)]), plain), + way("primary", line(&[(-500.0, 0.0), (500.0, 0.0)]), tunnel), + way("primary", line(&[(500.0, 0.0), (700.0, 0.0)]), plain), + ]; + let solved = run(&features, &terrain, &[]); + for f in [0, 2] { + assert!(on_the_ground(&place, &solved.ways[f][0], &terrain), "way {f}"); + } + // The fit rounds the kinks at the portals within the smoothing length of the class, so the curve between them + // climbs a little steeper than the terrain's rise: 0.01 of grade. + let steepest = steepest(&place, &solved.ways[1][0]); + assert!(steepest <= 0.2 + 0.01, "{steepest}"); +} + +#[test] +fn a_road_in_a_gully_by_a_portal_bends_the_tunnel_under_it_within_its_grade() { + // The slope of the lever test, 20 % from portal to portal, and a road across the tunnel 10 m from its lower + // portal in a gully 5 m deep: the pass needs the tunnel lower than its portals' band gives. The grade between + // the portals spreads the drop along the tunnel; without it the tunnel digs a step under the road. + let place = bridges(); + let height = |e: f64| { + let inside = (e.clamp(-1000.0, 1000.0) + 1000.0) / 2000.0; + let gully = 5.0 * (-((e + 990.0) / 4.0).powi(2)).exp(); + 500.0 + 400.0 * inside + 100.0 * (std::f64::consts::PI * inside).sin() - gully + }; + let terrain = place.terrain(move |e, _| height(e)); + let line = |corners: &[(f64, f64)]| place.line(corners, None); + let features = [ + way("primary", line(&[(-1200.0, 0.0), (-1000.0, 0.0)]), plain), + way("primary", line(&[(-1000.0, 0.0), (1000.0, 0.0)]), tunnel), + way("primary", line(&[(1000.0, 0.0), (1200.0, 0.0)]), plain), + way("unclassified", line(&[(-990.0, -100.0), (-990.0, 100.0)]), plain), + ]; + let solved = run(&features, &terrain, &[]); + assert!(on_the_ground(&place, &solved.ways[3][0], &terrain)); + // The portals give way to the pass past GROUND_M, as the ground gives way to every other limit, but not past + // HARD_M. + for f in [0, 2] { + let curve = place.curve(&solved.ways[f][0]); + let ground = terrain.heights(&curve.points); + assert!(curve.z.unwrap().iter().zip(ground).all(|(z, h)| (z - h).abs() <= HARD_M + KEEP_M), "way {f}"); } + // The pass and the grade are costs of one tier, so the grade gives way a little where the pass pushes. + let steepest = steepest(&place, &solved.ways[1][0]); + assert!(steepest <= 0.2 + 0.02, "{steepest}"); } #[test] @@ -598,7 +899,18 @@ fn corner_network(place: &Place) -> (Vec, Vec, impl Fn(f64, f64) way("track", place.line(&near(&[(40.0, 100.0), (46.0, 100.0)]), None), bridge), ]; let stream = near(&[(210.0, -260.0), (180.0, -240.0)]).iter().map(|&(e, n)| place.at(e, n)).collect(); - (features, vec![River { points: stream, levels: vec![990.0, 989.5], half: 1.0, cover: 1.0, lift: 1.5 }], terrain) + ( + features, + vec![River { + points: stream, + levels: vec![990.0, 989.5], + half: 1.0, + cover: 1.0, + lift: 1.5, + untagged_culvert: true, + }], + terrain, + ) } #[test] @@ -667,3 +979,130 @@ fn a_tunnel_runs_straight_to_its_portal_on_a_road_past_the_region_and_one_that_t let (_, cut) = context(&features, &beyond[..1], &|p| place.east_north(p).0 < 5000.0); assert_eq!(cut, BTreeSet::from([1])); } + +/// A stream from (east, north) to (east, north) at 499.7 m, 1 m wide. +fn stream(place: &Place, from: (f64, f64), to: (f64, f64)) -> River { + let points = place.line(&[from, to], None); + River { levels: vec![499.7; points.len()], points, half: 0.5, cover: 1.0, lift: 1.5, untagged_culvert: true } +} + +#[test] +fn a_road_over_a_narrow_stream_holds_its_cover_tagged_as_a_ford_or_not_and_a_path_a_wide_river_and_a_grazing_line_do_not( +) { + let place = bridges(); + let road = |class: &str, north: f64, edit: fn(&mut Feature)| { + way(class, place.line(&[(-100.0, north), (100.0, north)], Some(20.0)), edit) + }; + let shared = |class: &str, north: f64, edit: fn(&mut Feature)| { + way(class, place.line(&[(-100.0, north), (0.0, north), (100.0, north)], None), edit) + }; + let features = [ + road("residential", 0.0, plain), + road("footway", 200.0, plain), + way("residential", place.line(&[(-95.0, 400.0), (100.0, 400.0)], None), |f| f.ford = true), + road("residential", 600.0, plain), + road("residential", 800.0, plain), + // Shares a vertex with a stream, crosses another 4 m on and a third 300 m on. + way("residential", place.line(&[(-100.0, 1000.0), (0.0, 1000.0), (400.0, 1000.0)], None), plain), + shared("rail", 1200.0, plain), + shared("rail", 1400.0, plain), + shared("residential", 1600.0, plain), + shared("footway", 1800.0, |f| f.stones = true), + shared("rail", 2000.0, plain), + road("residential", 2200.0, plain), + ]; + let across = |north: f64| stream(&place, (0.0, north - 10.0), (0.0, north + 10.0)); + let through = |north: f64| River { + points: vec![place.at(0.0, north - 10.0), place.at(0.0, north), place.at(0.0, north + 10.0)], + levels: vec![499.7; 3], + ..across(north) + }; + let rivers = [ + across(0.0), + across(200.0), + across(400.0), + // 10° to the road. + stream(&place, (-100.0, 600.0 - 17.6), (100.0, 600.0 + 17.6)), + River { half: 2.5, untagged_culvert: false, ..across(800.0) }, + through(1000.0), + stream(&place, (4.0, 990.0), (4.0, 1010.0)), + stream(&place, (300.0, 990.0), (300.0, 1010.0)), + through(1200.0), + // Ends on the railway and on the road. + stream(&place, (0.0, 1390.0), (0.0, 1400.0)), + stream(&place, (0.0, 1590.0), (0.0, 1600.0)), + through(1800.0), + stream(&place, (20.0, 1790.0), (20.0, 1810.0)), + // Two parts that meet on the railway. + stream(&place, (0.0, 1990.0), (0.0, 2000.0)), + stream(&place, (0.0, 2000.0), (0.0, 2010.0)), + River { cover: 2.0, ..across(2200.0) }, + ]; + let solved = run(&features, &flat, &rivers); + let at = |f: usize, east: f64| { + let (along, z) = place.profile(&solved.ways[f][0]); + let start = place.east_north(solved.ways[f][0].as_ref().unwrap().points[0]).0; + interp(east - start, &along, &z) + }; + // A limit is a cost: the stiff line of a railway meets its cover within 2 cm. + let lifted = |z: f64| z > 499.7 + 1.0 - 0.02; + let level = |z: f64, want: f64| (z - want).abs() < 0.01; + assert!(lifted(at(0, 0.0)), "{}", at(0, 0.0)); + assert!(level(at(1, 0.0), 500.0) && level(at(3, 0.0), 500.0) && level(at(4, 0.0), 500.0)); + // A road tagged as a ford, and one that shares a vertex with the stream, over narrow water. + assert!(lifted(at(2, 0.0)), "{}", at(2, 0.0)); + assert!(lifted(at(5, 0.0)) && lifted(at(5, 300.0)), "{} {}", at(5, 0.0), at(5, 300.0)); + assert!(lifted(at(6, 0.0)) && level(at(7, 0.0), 500.0) && level(at(8, 0.0), 500.0)); + assert!(level(at(9, 0.0), 500.0) && level(at(9, 20.0), 500.0)); + assert!(lifted(at(10, 0.0)) && level(at(11, 0.0), 500.0)); + let m = &solved.metrics; + // The ford's crossing, the shared vertex and the stream 4 m on: that one lies under the shared one's lift. + assert_eq!((m.covers_untagged, m.covers_untagged_lifted, m.covers_untagged_capped, m.covers_capped), (7, 6, 1, 0)); + assert_eq!((m.covers, m.covers_lifted, m.fords), (7, 6, 0)); + assert!(m.cover_lift_top_m > 0.69 && m.cover_lift_top_m < 0.71, "{}", m.cover_lift_top_m); +} + +#[test] +fn a_sidewalk_runs_on_over_an_untagged_culvert_and_not_along_a_stream_beside_it() { + let place = bridges(); + let road = way("residential", place.line(&[(-100.0, 0.0), (300.0, 0.0)], Some(20.0)), |f| { + (f.half, f.outer, f.sidewalks) = (2.5, 4.0, [Some(true); 2]); + }); + let rivers = [stream(&place, (0.0, -20.0), (0.0, 20.0)), stream(&place, (100.0, 3.5), (160.0, 3.5))]; + let solved = run(&[road], &flat, &rivers); + let way = solved.ways[0][0].as_ref().unwrap(); + // The sides of the kept segment at `east`. + let walk = |east: f64| { + let at = way.points.iter().rposition(|&p| place.east_north(p).0 <= east).unwrap(); + way.plan[at].walk + }; + for east in [-5.0, -1.0, 0.0, 1.0, 5.0] { + assert_eq!(walk(east), crate::WALK_LEFT | crate::WALK_RIGHT, "{east} m"); + } + for east in [110.0, 130.0, 150.0] { + assert_eq!(walk(east), crate::WALK_RIGHT, "{east} m"); + } +} + +#[test] +fn a_slanted_stream_that_ends_on_a_road_vertex_is_no_crossing_and_one_through_a_railway_vertex_is_one() { + let place = bridges(); + let features = [ + way("residential", place.line(&[(-7.0, -18.0 * 0.037), (0.0, 0.0), (7.0, 0.9)], None), plain), + way("rail", place.line(&[(-100.0, 263.1), (0.0, 300.0), (100.0, 338.7)], None), plain), + ]; + let rivers = [ + // The parameters of this pair miss both ends by a rounding. + stream(&place, (-19.0 * 1.3, 61.3), (0.0, 0.0)), + River { + points: place.line(&[(-27.1, 247.9), (0.0, 300.0), (23.3, 352.9)], None), + levels: vec![499.7; 3], + ..stream(&place, (0.0, 0.0), (1.0, 1.0)) + }, + ]; + let solved = run(&features, &flat, &rivers); + let m = &solved.metrics; + assert_eq!((m.covers_untagged, m.covers_untagged_lifted, m.fords), (1, 1, 0)); + assert!((height_at(&solved.ways[0][0], place.at(0.0, 0.0)) - 500.0).abs() < 0.01); + assert!(height_at(&solved.ways[1][0], place.at(0.0, 300.0)) > 499.7 + 1.0 - 0.01); +} diff --git a/host/obc-trailview-features/src/stamps.rs b/host/obc-trailview-features/src/stamps.rs new file mode 100644 index 0000000000..5ba2f4441d --- /dev/null +++ b/host/obc-trailview-features/src/stamps.rs @@ -0,0 +1,193 @@ +//! The step `planner/trailview-stamps` of `obc data`: `trailview-stamps.pmtiles`, the bytes that the TrailView +//! stamp worker posts for the baked nodes of each feature tile of `planner/trailview-features`. The stamp code +//! runs in Node, in processes of `builder/web/scripts/trailview-stamps.mjs`, which state its stamp version. + +use std::io::{BufReader, BufWriter, Read, Write}; +use std::process::{ChildStdout, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use obc_data::engine::Request; +use serde_json::json; + +use crate::pmtiles::{self, Archive, Header}; +use crate::tiles::{Tiles, MAX_ZOOM, MIN_ZOOM}; + +/// The stamp process, from the repository root, where a step starts, with its V8 heap capped. +const STAMP: [&str; 3] = ["node", "--max-old-space-size=1024", "builder/web/scripts/trailview-stamps.mjs"]; +/// The memory that a stamp process may take: the capped heap, the decoded tiles and the meshes outside the heap. +const PROCESS_BYTES: usize = 3 << 29; +/// Stamp processes at most. +const PROCESSES: usize = 8; +/// The time that a stamp process may take for a tile, and for its start, which builds the bake module. +const TILE_TIMEOUT: Duration = Duration::from_secs(300); + +/// The stamp version and the gzip bytes of the nodes by tile id. +type Stamped = (String, Vec<(u64, Vec)>); + +pub fn step(request: &Request) -> Result<(), String> { + let options = &request.options; + let bounds: [f64; 4] = + serde_json::from_value(options["bounds"].clone()).map_err(|_| "option `bounds` is not four numbers")?; + let attribution = options["attribution"].as_str().ok_or("option `attribution` is not a string")?; + let features = request + .layers + .get("planner/trailview-features") + .and_then(|files| files.get("trailview-features.pmtiles")) + .ok_or("the step has no input `planner/trailview-features`")?; + let archive = Archive::open(features)?; + // A feature tile holds what comes within one tile of the region. + let region = Tiles::new(bounds); + let tiles: Vec<(u8, u32, u32)> = (MIN_ZOOM..=MAX_ZOOM) + .flat_map(|z| { + let [c0, r0, c1, r1] = region.span(z); + let side = 1i64 << z; + let columns = (c0 - 1).max(0)..=(c1 + 1).min(side - 1); + columns.flat_map(move |x| ((r0 - 1).max(0)..=(r1 + 1).min(side - 1)).map(move |y| (z, x as u32, y as u32))) + }) + .collect(); + // The process of a step gets the memory that `obc data` reserves for it in its environment. + let reserved = request.memory_bytes.or_else(|| std::env::var("OBC_DATA_MEMORY_BYTES").ok()?.parse().ok()); + let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); + let processes = + (crate::step::free_memory(reserved) / PROCESS_BYTES).min(cores).min(PROCESSES).min(tiles.len()).max(1); + let (queue, stop, first) = (Mutex::new(tiles.into_iter()), AtomicBool::new(false), Mutex::new(None)); + let made = std::thread::scope(|scope| { + let workers: Vec<_> = (0..processes) + .map(|_| { + scope.spawn(|| { + let made = stamp(&archive, &queue, &stop); + // The first process that fails stops the others, and its error is the step's. + if let Err(error) = &made { + first.lock().expect("an unpoisoned error").get_or_insert_with(|| error.clone()); + stop.store(true, Ordering::Relaxed); + } + made.ok() + }) + }) + .collect(); + workers.into_iter().map(|worker| worker.join().ok().flatten()).collect::>() + }); + if let Some(error) = first.into_inner().expect("an unpoisoned error") { + return Err(error); + } + let made = made.into_iter().collect::>>().ok_or("a stamp thread panicked")?; + let version = made[0].0.clone(); + if made.iter().any(|(other, _)| *other != version) { + return Err("the stamp processes state different stamp versions".into()); + } + let mut nodes: Vec<(u64, Vec)> = made.into_iter().flat_map(|(_, nodes)| nodes).collect(); + nodes.sort_by_key(|node| node.0); + let [west, south, east, north] = bounds; + let e7 = |value: f64| (value * 1e7).round_ties_even() as i32; + let header = Header { + tile_type: 0, + tile_compression: 2, + bounds_e7: [e7(west), e7(south), e7(east), e7(north)], + center_zoom: MAX_ZOOM, + center_e7: [e7((west + east) / 2.0), e7((south + north) / 2.0)], + }; + let metadata = json!({"stamp_version": version, "attribution": attribution, "bounds": bounds}); + let output = request.output.join("trailview-stamps.pmtiles"); + let bytes = pmtiles::write(&output, &nodes, &header, &metadata.to_string())?; + let metrics = json!({"nodes": nodes.len(), "processes": processes, "bytes": bytes, "stamp_version": version}); + std::fs::write(&request.metrics, metrics.to_string()).map_err(|e| e.to_string()) +} + +/// The nodes of the feature tiles that one stamp process takes from `queue` until it is empty or `stop` +/// is set, in the frames of `trailview-stamps.mjs`. A process that takes longer than TILE_TIMEOUT, or +/// that runs while `stop` is set, is killed. +fn stamp( + archive: &Archive, + queue: &Mutex>, + stop: &AtomicBool, +) -> Result { + let mut child = Command::new(STAMP[0]) + .args(&STAMP[1..]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .map_err(|e| format!("{}: {e}", STAMP.join(" ")))?; + let input = BufWriter::new(child.stdin.take().expect("a piped input")); + let output = BufReader::new(child.stdout.take().expect("a piped output")); + let (child, since, done, late) = + (Mutex::new(child), Mutex::new(Instant::now()), AtomicBool::new(false), AtomicBool::new(false)); + let made = std::thread::scope(|scope| { + scope.spawn(|| { + while !done.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(200)); + let over = since.lock().expect("an unpoisoned clock").elapsed() > TILE_TIMEOUT; + if over || stop.load(Ordering::Relaxed) { + late.store(over, Ordering::Relaxed); + let _ = child.lock().expect("an unpoisoned child").kill(); + break; + } + } + }); + let made = frames(archive, queue, stop, input, output, &since); + done.store(true, Ordering::Relaxed); + made + }); + let status = child.into_inner().expect("an unpoisoned child").wait().map_err(|e| e.to_string())?; + if late.load(Ordering::Relaxed) { + return Err(format!("a stamp process took more than {} s for a tile", TILE_TIMEOUT.as_secs())); + } + let made = made?; + if !status.success() { + return Err(format!("the stamp process ended with {status}")); + } + Ok(made) +} + +/// The frames of one stamp process: its version, then a tile out and its nodes back, until the queue is +/// empty or `stop` is set. `since` is when the current tile started. +fn frames( + archive: &Archive, + queue: &Mutex>, + stop: &AtomicBool, + mut input: BufWriter, + mut output: BufReader, + since: &Mutex, +) -> Result { + let ended = |e: std::io::Error| format!("the stamp process ended ({e}); its errors are above"); + let length = read_u32(&mut output).map_err(ended)?; + let mut version = vec![0; length as usize]; + output.read_exact(&mut version).map_err(ended)?; + let version = String::from_utf8(version).map_err(|e| e.to_string())?; + let mut nodes = Vec::new(); + while !stop.load(Ordering::Relaxed) { + let Some((z, x, y)) = queue.lock().expect("an unpoisoned queue").next() else { break }; + let Some(body) = archive.get(z, x, y)? else { continue }; + *since.lock().expect("an unpoisoned clock") = Instant::now(); + input.write_all(&head(z, x, y, body.len())).and_then(|()| input.write_all(&body)).map_err(ended)?; + input.flush().map_err(ended)?; + for _ in 0..read_u32(&mut output).map_err(ended)? { + let mut place = [0u8; 13]; + output.read_exact(&mut place).map_err(ended)?; + let word = |at: usize| u32::from_le_bytes(place[at..at + 4].try_into().expect("four bytes")); + let mut bytes = vec![0; word(9) as usize]; + output.read_exact(&mut bytes).map_err(ended)?; + nodes.push((pmtiles::tile_id(place[0], word(1), word(5)), pmtiles::gzip(&bytes))); + } + } + drop(input); + if stop.load(Ordering::Relaxed) { + return Err("another stamp process failed".into()); + } + Ok((version, nodes)) +} + +fn head(z: u8, x: u32, y: u32, length: usize) -> Vec { + let mut out = vec![z]; + for word in [x, y, length as u32] { + out.extend(word.to_le_bytes()); + } + out +} + +fn read_u32(output: &mut BufReader) -> std::io::Result { + let mut word = [0u8; 4]; + output.read_exact(&mut word)?; + Ok(u32::from_le_bytes(word)) +} diff --git a/host/obc-trailview-features/src/step.rs b/host/obc-trailview-features/src/step.rs index a4f804d150..bed4f2ace2 100644 --- a/host/obc-trailview-features/src/step.rs +++ b/host/obc-trailview-features/src/step.rs @@ -1,6 +1,6 @@ //! The step `planner/trailview-features` of `obc data`: `trailview-features.pmtiles` of a region from //! the OSM of `planner/osm`, the master terrain of the grid of `planner/terrain` and the water -//! polygons of `water-polygons`, by the kind table and the road classes of its options. +//! polygons of `water-polygons`, by the kind table, the road classes and the finishes of its options. use obc_data::engine::Request; @@ -11,6 +11,7 @@ pub fn step(request: &Request) -> Result<(), String> { let options = &request.options; let kinds = kinds::validate(&options["kinds"])?; let (class_names, classes) = kinds::classes(&options["roads"])?; + let widths = kinds::widths(&options["roads"], &options["finishes"])?; let waterways = kinds::waterways(&options["waterways"])?; let bounds: [f64; 4] = serde_json::from_value(options["bounds"].clone()).map_err(|_| "option `bounds` is not four numbers")?; @@ -20,7 +21,8 @@ pub fn step(request: &Request) -> Result<(), String> { else { return Err("`water-polygons` is not one file".into()); }; - let options = Options { kinds, bounds, attribution, classes, class_names, waterways, sea: Some(sea.clone()) }; + let sea = Some(sea.clone()); + let options = Options { kinds, bounds, attribution, classes, class_names, widths, waterways, sea }; let layer = |name: &str| request.layers.get(name).ok_or(format!("the step has no input `{name}`")); let [pbf] = layer("planner/osm")?.values().collect::>()[..] else { return Err("`planner/osm` is not one file".into()); @@ -258,6 +260,7 @@ mod tests { options: json!({"bounds": [west, south, east, north], "attribution": "© OSM", "kinds": table(include_str!("../../../data/trailview/kinds.json")), "roads": kinds::solver_rows(&table(include_str!("../../../data/trailview/roads.json"))), + "finishes": kinds::finish_rows(&table(include_str!("../../../data/trailview/finishes.json"))), "waterways": kinds::waterway_rows(&table(include_str!("../../../data/trailview/waterways.json")))}), output: root.join("output"), metrics: root.join("metrics.json"), @@ -327,9 +330,9 @@ mod tests { (MIN_ZOOM..=MAX_ZOOM).collect() ); assert_eq!(find(left, "dam").parts[0].xy.len(), 2, "a closed dam way is an area, not a ring line"); - // A tunnel with no terrain over it runs on the ground, as a road. + // A tunnel with no terrain over it runs on the ground, as a road with its tunnel tag. let tunnel = find(left, "main-road"); - assert_eq!(tunnel.tags, tags(&[("highway", "secondary")])); + assert_eq!(tunnel.tags, tags(&[("highway", "secondary"), ("tunnel", "yes")])); let road = find(left, "road"); assert_eq!(road.tags, tags(&[("highway", "track"), ("surface", "gravel")])); // A cut keeps the segment whole, so both tiles hold the same one, and its heights follow the terrain. @@ -398,5 +401,9 @@ mod tests { assert!(lake.parts[0].xy.contains(river.parts[0].xy.last().unwrap())); let metrics = table(&std::fs::read_to_string(root.join("metrics.json")).unwrap()); assert_eq!(metrics["tiles"], tiles.len()); + assert_eq!( + metrics["roads"]["shallow_tunnels"], 1, + "each way on the ground with a tunnel tag is a shallow tunnel" + ); } } diff --git a/host/obc-trailview-features/src/structures.rs b/host/obc-trailview-features/src/structures.rs index 2312c508f2..4266d4229f 100644 --- a/host/obc-trailview-features/src/structures.rs +++ b/host/obc-trailview-features/src/structures.rs @@ -6,38 +6,26 @@ use std::collections::HashMap; +use obc_ground_plan::sections::is_track; + +use crate::gate::GATE_M; use crate::geometry::{arange, bounds, contains, interp, key, Boxes}; use crate::{metres, Tags, Terrain}; /// OSM bridge values of a way that lies on the ground. -const GROUND: [&str; 3] = ["no", "boardwalk", "low_water_crossing"]; +pub(crate) const GROUND: [&str; 3] = ["no", "boardwalk", "low_water_crossing"]; const KINDS: [&str; 4] = ["main-road", "road", "path", "railway"]; -/// The `railway` values of a track. A tunnel or a gallery of a road can keep another `railway` value. -const TRACKS: [&str; 4] = ["rail", "narrow_gauge", "light_rail", "funicular"]; /// Water crossed for less than CHANNEL_M takes no pier; a pier stands PIER_GAP_M beside it. A pier /// keeps MIN_SPAN_M from another pier and from the bridge's ends. const CHANNEL_M: f64 = 30.0; const PIER_GAP_M: f64 = 2.0; const MIN_SPAN_M: f64 = 6.0; -/// A pier keeps this far from a waterway's edge and a road's. +/// A pier keeps this far from a waterway's edge and from a road's outer half-width. const BANK_M: f64 = 1.0; /// A line farther than this from a bridge does not hold a pier off it. pub const REACH_M: f64 = 50.0; -/// The half-width of a way without a `width` tag, the widest of its class in the engine (PAVED and -/// PATH_HALF of bins.ts). -const MAIN: [&str; 7] = ["motorway", "trunk", "primary", "secondary", "motorway_link", "trunk_link", "primary_link"]; -pub const MAIN_HALF_M: f64 = 6.0; -pub const ROAD_HALF_M: f64 = 3.0; -const RAIL_HALF_M: f64 = 1.9; -const PATH_HALF_M: [(&str, f64); 7] = [ - ("path", 1.0), - ("footway", 1.0), - ("cycleway", 1.5), - ("bridleway", 1.0), - ("steps", 1.0), - ("pedestrian", 3.0), - ("via_ferrata", 0.6), -]; +/// The `highway` values of a path, whose tunnel has a path's bore. +const PATHS: [&str; 7] = ["path", "footway", "cycleway", "bridleway", "steps", "pedestrian", "via_ferrata"]; /// A footbridge longer than CABLE_M that runs more than HIGH_M over the ground hangs from cables, as /// one that OSM tags so. const CABLE_M: f64 = 40.0; @@ -55,7 +43,8 @@ pub(crate) const BORE_RAIL_M: f64 = 6.5; const BORE_STEP_M: f64 = 2.0; /// Farther than PORTAL_M from its ends, a tunnel that rises FLOAT_M over the terrain lies where the /// solver could not put it under the hill: a network of shafts and caverns, or a bore that the -/// terrain misses. +/// terrain misses. A tunnel shorter than twice PORTAL_M has no such sample: it floats where it rises +/// more than the census gate's GATE_M over the terrain anywhere. const FLOAT_M: f64 = 5.0; const PORTAL_M: f64 = 20.0; @@ -67,64 +56,17 @@ pub fn is_bridge(kind: &str, tags: &Tags) -> bool { KINDS.contains(&kind) && !GROUND.contains(&tag(tags, "bridge").unwrap_or("no")) } -/// Whether a way is a track: a `railway` of the tracks and no `highway`. -pub fn is_track(tags: &Tags) -> bool { - tag(tags, "railway").is_some_and(|r| TRACKS.contains(&r)) && !tags.contains_key("highway") -} - -/// The class of a way: `rack` for a rack railway, else the `railway` of a track or its `highway`. -pub fn class_of(tags: &Tags) -> &str { - if is_track(tags) { - return if tag(tags, "rack").unwrap_or("no") != "no" { "rack" } else { &tags["railway"] }; - } - tag(tags, "highway").unwrap_or("") -} - /// The height of a tunnel's bore for a way. pub fn bore(tags: &Tags) -> f64 { if is_track(tags) { BORE_RAIL_M - } else if tag(tags, "highway").is_some_and(|h| PATH_HALF_M.iter().any(|(p, _)| *p == h)) { + } else if tag(tags, "highway").is_some_and(|h| PATHS.contains(&h)) { BORE_PATH_M } else { BORE_M } } -/// The half-width of a way in metres: OSM's `width` where it has one, as halfWidth of bins.ts reads -/// it. -pub fn road_half(tags: &Tags) -> f64 { - if let Some(width) = tag(tags, "width").and_then(leading_number) { - return (width / 2.0).max(0.4); - } - let highway = tag(tags, "highway"); - if is_track(tags) { - return RAIL_HALF_M; - } - if let Some((_, half)) = PATH_HALF_M.iter().find(|(p, _)| Some(*p) == highway) { - return *half; - } - if highway.is_some_and(|h| MAIN.contains(&h)) { - MAIN_HALF_M - } else { - ROAD_HALF_M - } -} - -/// The number at the start of a tag, as JavaScript's parseFloat reads it in the engine: "8 m" is 8. -/// The engine leaves out a number that is not finite. -pub(crate) fn leading_number(text: &str) -> Option { - let text = trim_space(text); - let span = text.find(|c: char| !matches!(c, '0'..='9' | '+' | '-' | '.' | 'e' | 'E')).unwrap_or(text.len()); - (1..=span).rev().find_map(|end| text[..end].parse::().ok()).filter(|v| v.is_finite()) -} - -/// The text without the white space that JavaScript trims before a number: Rust's white space, less -/// U+0085, and U+FEFF. -pub(crate) fn trim_space(text: &str) -> &str { - text.trim_start_matches(|c: char| c.is_whitespace() && c != '\u{85}' || c == '\u{feff}') -} - /// The bridges: lists of (way, reversed) whose parts meet end to end, where exactly two bridge ends /// meet. fn chains(ways: &[&[[f64; 2]]]) -> Vec> { @@ -272,8 +214,8 @@ pub type Pier = ([f64; 2], f64, usize); pub type Way<'a> = (&'a str, &'a Tags, &'a [[f64; 2]], &'a [f64]); /// Per bridge way, the tags that the bake adds: its deck depth in metres, and `bridge:structure` for -/// a cable bridge; and the piers as (point, deck height there, a way of their bridge). `waterways` and -/// `roads` are (half-width, points), `areas` the rings of river areas and lakes. +/// a cable bridge; and the piers as (point, deck height there, a way of their bridge). `waterways` are +/// (half-width, points), `roads` (outer half-width, points), `areas` the rings of river areas and lakes. pub fn bridges( ways: &[Way], waterways: &[(f64, &[[f64; 2]])], @@ -414,19 +356,22 @@ fn cover(points: &[[f64; 2]], z: &[f64], terrain: &dyn Terrain) -> Option<(Vec bool { cover(points, z, terrain).is_some_and(|(depth, _)| { - depth.iter().filter(|d| !d.is_nan()).fold(f64::NEG_INFINITY, |m, &d| m.max(d)) < bore(tags) + let known = || depth.iter().filter(|d| !d.is_nan()); + known().fold(f64::NEG_INFINITY, |m, &d| m.max(d)) < bore(tags) && known().all(|&d| d >= -FLOAT_M) }) } -/// Whether a tunnel rises more than FLOAT_M over the terrain farther than PORTAL_M from its ends. +/// Whether a tunnel rises more than FLOAT_M over the terrain farther than PORTAL_M from its ends, or, +/// with no sample that far from its ends, more than GATE_M anywhere. pub fn floating(points: &[[f64; 2]], z: &[f64], terrain: &dyn Terrain) -> bool { cover(points, z, terrain).is_some_and(|(depth, end)| { - let inner = depth.iter().zip(&end).filter(|(d, &e)| e > PORTAL_M && !d.is_nan()); - inner.fold(f64::INFINITY, |m, (&d, _)| m.min(d)) < -FLOAT_M + let short = end.iter().all(|&e| e <= PORTAL_M); + depth.iter().zip(&end).any(|(&d, &e)| if short { d < -GATE_M } else { e > PORTAL_M && d < -FLOAT_M }) }) } @@ -434,6 +379,17 @@ pub fn floating(points: &[[f64; 2]], z: &[f64], terrain: &dyn Terrain) -> bool { mod tests { use super::*; + #[test] + fn every_class_row_has_the_bore_of_the_bake() { + let rows: serde_json::Value = serde_json::from_str(include_str!("../../../data/trailview/roads.json")).unwrap(); + let sections = obc_ground_plan::sections::Sections::embedded(); + for (class, row) in rows.as_object().unwrap() { + let key = if row["group"] == "rail" { "railway" } else { "highway" }; + let tags = Tags::from([(key.to_string(), class.clone()), ("tunnel".to_string(), "yes".to_string())]); + assert_eq!(sections.way("tunnel", &tags, false).bore_m, bore(&tags), "{class}"); + } + } + /// Metres east and north of a point at about 46.7° N, in world units. const Y: f64 = 0.3218; @@ -451,12 +407,22 @@ mod tests { } #[test] - fn a_tunnel_under_a_mountain_does_not_float_and_over_a_valley_it_does() { + fn a_tunnel_under_a_mountain_does_not_float_and_over_a_valley_or_up_a_cliff_it_does() { let mountain = |x: f64, _: f64| if (x - 0.53).abs() < 2995.0 / metres(Y) { 2500.0 } else { 1000.0 }; let points = [at(-3000.0, 0.0), at(-1000.0, 0.0), at(0.0, 0.0), at(3000.0, 0.0)]; let z = [1000.0; 4]; assert!(!floating(&points, &z, &mountain)); assert!(floating(&points, &z, &flat)); + // A short tunnel has no sample farther than PORTAL_M from its ends. + let short = [at(0.0, 0.0), at(20.0, 0.0)]; + assert!(!floating(&short, &[500.0, 500.0], &|_, _| 510.0)); + assert!(floating(&short, &[500.0, 600.0], &flat)); + // Near the portal of a long tunnel the terrain can miss a cliff: a bore over it there stays. + let long = [at(0.0, 0.0), at(100.0, 0.0)]; + let hill = |x: f64, _: f64| if east([x, Y]) > 4.0 { 600.0 } else { 500.0 }; + for portal in [507.0, 520.0] { + assert!(!floating(&long, &[portal, portal], &hill)); + } } #[test] @@ -477,21 +443,10 @@ mod tests { let none = Tags::new(); let deck = [at(0.0, 0.0), at(80.0, 0.0)]; let road = [at(40.0, -50.0), at(40.0, 50.0)]; - let (_, piers, _) = - bridges(&[("road", &none, &deck, &[510.0, 510.0])], &[], &[], &flat, &[(ROAD_HALF_M, &road)]); - assert!((east(piers[0].0) - 40.0).abs() > ROAD_HALF_M + BANK_M); - } - - #[test] - fn a_width_reads_as_a_number_at_the_start_of_its_tag() { - let width = |w: &str| road_half(&Tags::from([("width".into(), w.into())])); - assert_eq!( - (width(" 8 m"), width("3."), width(".5"), width("-3"), width("wide")), - (4.0, 1.5, 0.4, 0.4, ROAD_HALF_M) - ); - let n = leading_number; - assert_eq!((n(" -2.5e1x"), n("1e"), n("1e+"), n("5-3")), (Some(-25.0), Some(1.0), Some(1.0), Some(5.0))); - assert_eq!((n("m8"), n("."), n(""), n("+-5"), n("inf")), (None, None, None, None, None)); - assert_eq!((n("1e309"), n("\u{feff}2"), n("\u{85}2")), (None, Some(2.0), None)); + let primary = Tags::from([("highway".into(), "primary".into())]); + let outer = + obc_ground_plan::sections::Sections::embedded().widths().way("main-road", &primary, false).outer_m(); + let (_, piers, _) = bridges(&[("road", &none, &deck, &[510.0, 510.0])], &[], &[], &flat, &[(outer, &road)]); + assert!((east(piers[0].0) - 40.0).abs() > outer + BANK_M); } } diff --git a/host/obc-trailview-features/src/terrain.rs b/host/obc-trailview-features/src/terrain.rs index 375234a418..11bfcfca15 100644 --- a/host/obc-trailview-features/src/terrain.rs +++ b/host/obc-trailview-features/src/terrain.rs @@ -165,6 +165,10 @@ impl Terrain for Tiles { self.top.into() } + fn tile(&self, z: u8, x: u32, y: u32) -> Option>> { + Tiles::tile(self, (z, x, y)) + } + fn heights(&self, points: &[[f64; 2]]) -> Vec { // The last tiles that this call read, so that points sorted by tile take the lock of the // cache about once per tile. diff --git a/host/obc-trailview-features/src/tiles.rs b/host/obc-trailview-features/src/tiles.rs index a436c39c9c..446641cc70 100644 --- a/host/obc-trailview-features/src/tiles.rs +++ b/host/obc-trailview-features/src/tiles.rs @@ -4,6 +4,8 @@ use std::collections::{BTreeSet, HashMap}; use std::f64::consts::TAU; +use obc_ground_plan::sections::WATER_KINDS; + use crate::geometry::bounds; use crate::{world, Part, Plan, Tags, EQUATOR_M}; @@ -105,6 +107,22 @@ pub struct Tile { order: Vec, streams: Streams, count: u64, + /// The features that can take more tags after the cut: their position, their id and where their tags start in + /// the tags stream. + ids: Vec<(u32, u32, usize)>, +} + +fn read_varint(bytes: &[u8], mut at: usize) -> (u64, usize) { + let (mut value, mut shift) = (0u64, 0); + loop { + let byte = bytes[at]; + at += 1; + value |= u64::from(byte & 0x7f) << shift; + if byte < 0x80 { + return (value, at); + } + shift += 7; + } } fn varint(out: &mut Vec, mut value: u64) { @@ -130,9 +148,12 @@ impl Tile { at } - /// Add a feature. A height is in metres; a part without heights in a feature with some has an - /// unknown height at each point. - pub fn add(&mut self, kind: &str, tags: &Tags, geometry: Geometry, parts: &[Quantized]) { + /// Add a feature, with `id` where it can take more tags after the cut (`bytes_with`). A height is in metres; a + /// part without heights in a feature with some has an unknown height at each point. + pub fn add(&mut self, kind: &str, tags: &Tags, geometry: Geometry, parts: &[Quantized], id: Option) { + if let Some(id) = id { + self.ids.push((self.count as u32, id, self.streams.tags.len())); + } let kind = self.string(kind); let tags: Vec<(u64, u64)> = tags.iter().map(|(key, value)| (self.string(key), self.string(value))).collect(); let out = &mut self.streams; @@ -174,15 +195,64 @@ impl Tile { /// The bytes of the tile. pub fn bytes(&self) -> Vec { + self.bytes_with(&|_| None) + } + + pub fn has_ids(&self) -> bool { + !self.ids.is_empty() + } + + /// The id of the feature at a position of the tile, where it has one. + pub fn id(&self, position: u32) -> Option { + let k = self.ids.binary_search_by_key(&position, |x| x.0).ok()?; + Some(self.ids[k].1) + } + + /// The bytes of the tile with the tags of `more` on the features of each id: its own keys, which the feature + /// lacks. The tags of a feature stay sorted by key. + pub fn bytes_with<'a>(&self, more: &dyn Fn(u32) -> Option<&'a Tags>) -> Vec { + let (mut strings, mut order) = (self.strings.clone(), self.order.clone()); + let mut string = |order: &mut Vec, text: &str| { + *strings.entry(text.to_string()).or_insert_with(|| { + order.push(text.to_string()); + order.len() as u64 - 1 + }) + }; + let (mut tags, mut at) = (Vec::new(), 0); + for &(_, id, start) in &self.ids { + let Some(more) = more(id).filter(|m| !m.is_empty()) else { continue }; + tags.extend(&self.streams.tags[at..start]); + let (count, mut i) = read_varint(&self.streams.tags, start); + let mut pairs = Vec::new(); + for _ in 0..count { + let (key, next) = read_varint(&self.streams.tags, i); + let (value, next) = read_varint(&self.streams.tags, next); + pairs.push((key, value)); + i = next; + } + at = i; + let own = |key: &str| pairs.iter().any(|p| order[p.0 as usize] == key); + assert!(more.keys().all(|k| !own(k)), "feature {id} has a tag of its own that the bake adds"); + for (key, value) in more { + pairs.push((string(&mut order, key), string(&mut order, value))); + } + pairs.sort_by(|a, b| order[a.0 as usize].cmp(&order[b.0 as usize])); + varint(&mut tags, pairs.len() as u64); + for (key, value) in pairs { + varint(&mut tags, key); + varint(&mut tags, value); + } + } + tags.extend(&self.streams.tags[at..]); let mut out = Vec::new(); - varint(&mut out, self.order.len() as u64); - for text in &self.order { + varint(&mut out, order.len() as u64); + for text in &order { varint(&mut out, text.len() as u64); out.extend(text.as_bytes()); } varint(&mut out, self.count); - let Streams { heads, tags, parts, vertices, along, tangent, grade, bank, words } = &self.streams; - for stream in [heads, tags, parts, vertices, along, tangent, grade, bank, words] { + let Streams { heads, parts, vertices, along, tangent, grade, bank, words, .. } = &self.streams; + for stream in [heads, &tags, parts, vertices, along, tangent, grade, bank, words] { out.extend(stream); } out @@ -217,135 +287,44 @@ impl Streams { pub fn encode(features: &[Feature]) -> Vec { let mut tile = Tile::default(); for feature in features { - tile.add(&feature.kind, &feature.tags, feature.geometry, &feature.parts); + tile.add(&feature.kind, &feature.tags, feature.geometry, &feature.parts, None); } tile.bytes() } -/// The features of a tile. +/// The features of a tile, through the reader of `obc-ground-plan`. #[cfg(test)] pub fn decode(data: &[u8]) -> Result, String> { - let next = |at: &mut usize| -> Result { - let (mut value, mut shift) = (0u64, 0); - loop { - let byte = *data.get(*at).ok_or("a feature tile ends inside a varint")?; - *at += 1; - value |= u64::from(byte & 0x7f) << shift; - shift += 7; - if byte < 0x80 { - return Ok(value); - } - } - }; - let signed = |value: u64| (value >> 1) as i64 ^ -((value & 1) as i64); - let mut at = 0; - let mut table = Vec::new(); - for _ in 0..next(&mut at)? { - let length = next(&mut at)? as usize; - let text = data.get(at..at + length).ok_or("a feature tile ends inside a string")?; - table.push(String::from_utf8(text.to_vec()).map_err(|e| e.to_string())?); - at += length; - } - let text = |index: u64| table.get(index as usize).cloned().ok_or("a string index past the table"); - let heads = (0..next(&mut at)?) - .map(|_| { - let kind = text(next(&mut at)?)?; - let header = next(&mut at)?; - let geometry = [Geometry::Point, Geometry::Line, Geometry::Area] - .get((header & 3) as usize) - .copied() - .ok_or("an unknown geometry")?; - Ok::<_, String>((kind, header, geometry)) - }) - .collect::, _>>()?; - let mut features = Vec::new(); - for (kind, _, geometry) in &heads { - let mut tags = Tags::new(); - for _ in 0..next(&mut at)? { - let key = text(next(&mut at)?)?; - tags.insert(key, text(next(&mut at)?)?); - } - features.push(Feature { kind: kind.clone(), tags, geometry: *geometry, parts: Vec::new() }); - } - // The vertices of each part, which the streams after this one do not name. - let mut counts: Vec> = Vec::new(); - for (feature, (_, header, _)) in features.iter_mut().zip(&heads) { - let (mut sizes, solved) = (Vec::new(), header & 4 != 0); - for _ in 0..header >> 4 { - let code = next(&mut at)?; - sizes.push(code >> 1); - feature.parts.push(Quantized { - outer: code & 1 == 1, - xy: Vec::new(), - z: solved.then(Vec::new), - plan: None, - }); - } - counts.push(sizes); - } - for (feature, sizes) in features.iter_mut().zip(&counts) { - let (mut x, mut y, mut height) = (0i64, 0i64, 0i64); - for (part, &size) in feature.parts.iter_mut().zip(sizes) { - for _ in 0..size { - x += signed(next(&mut at)?); - y += signed(next(&mut at)?); - part.xy.push([x, y]); - if let Some(z) = &mut part.z { - let code = next(&mut at)?; - if code == 0 { - z.push(f64::NAN); - } else { - height += signed(code - 1); - z.push(height as f64 / 100.0); - } - } - } - } - } - // (feature, part, the code of its metres along) of each part with an alignment. - let mut aligned = Vec::new(); - for (f, _) in heads.iter().enumerate().filter(|(_, head)| head.1 & 8 != 0) { - for p in 0..counts[f].len() { - let code = next(&mut at)?; - if code != 0 { - aligned.push((f, p, code)); - } - } - } - let column = |at: &mut usize| -> Result>, String> { - let mut out = Vec::with_capacity(aligned.len()); - for &(f, p, _) in &aligned { - out.push((0..counts[f][p]).map(|_| next(at)).collect::, String>>()?); - } - Ok(out) - }; - let (tangents, grades) = (column(&mut at)?, column(&mut at)?); - let (banks, words) = (column(&mut at)?, column(&mut at)?); - let running = |codes: &[u64]| -> Vec { - let mut sum = 0; - codes - .iter() - .map(|&code| { - sum += signed(code); - sum + use obc_ground_plan::tile::{self, Geometry as Read}; + let features = tile::decode(data).map_err(|e| e.to_string())?; + let feature = |f: tile::RawFeature| Feature { + kind: f.kind, + tags: f.tags, + geometry: match f.geometry { + Read::Point => Geometry::Point, + Read::Line => Geometry::Line, + Read::Area => Geometry::Area, + }, + parts: f + .parts + .into_iter() + .map(|p| Quantized { + outer: p.outer, + xy: p.xy, + z: p.z.map(|z| z.into_iter().map(|cm| cm.map_or(f64::NAN, |cm| cm as f64 / 100.0)).collect()), + plan: p.plan.map(|plan| Aligned { + along: plan.along, + tangent: plan.tangent, + grade: plan.grade, + bank: plan.bank, + widen: plan.widen, + side: plan.side.into_iter().map(u64::from).collect(), + walk: plan.walk.into_iter().map(u64::from).collect(), + }), }) - .collect() + .collect(), }; - for (n, &(f, p, code)) in aligned.iter().enumerate() { - features[f].parts[p].plan = Some(Aligned { - along: code - 1, - tangent: running(&tangents[n]).iter().map(|turn| turn.rem_euclid(TURN)).collect(), - grade: running(&grades[n]), - bank: banks[n].iter().map(|&code| signed(code)).collect(), - widen: words[n].iter().map(|word| word >> 4).collect(), - side: words[n].iter().map(|word| word & 3).collect(), - walk: words[n].iter().map(|word| word >> 2 & 3).collect(), - }); - } - if at != data.len() { - return Err("a feature tile has bytes after its last feature".into()); - } - Ok(features) + Ok(features.into_iter().map(feature).collect()) } /// The box (x0, y0, x1, y1) of the points of the parts, or None when they have none. @@ -359,6 +338,7 @@ struct Named<'a> { kind: &'a str, geometry: Geometry, tags: &'a Tags, + id: Option, } /// The tiles of a region from MIN_ZOOM to MAX_ZOOM that hold at least one feature. @@ -406,8 +386,16 @@ impl Tiles { } /// Add the feature to each tile of `zoom` in the region whose buffered square it meets, cut to - /// that square. Whether a tile took it. - pub fn add(&mut self, zoom: u8, kind: &str, geometry: Geometry, tags: &Tags, parts: &[Part]) -> bool { + /// that square, with its `id` in each (`Tile::add`). Whether a tile took it. + pub fn add( + &mut self, + zoom: u8, + kind: &str, + geometry: Geometry, + tags: &Tags, + parts: &[Part], + id: Option, + ) -> bool { let scale = (1u64 << zoom) as f64 * EXTENT_F; let parts: Vec = parts .iter() @@ -425,7 +413,7 @@ impl Tiles { let [c0, r0, c1, r1] = self.span(zoom); let (c0, r0) = (c0.max(row(box_[0] - margin)), r0.max(row(box_[1] - margin))); let (c1, r1) = (c1.min(row(box_[2] + margin)), r1.min(row(box_[3] + margin))); - let feature = Named { kind, geometry, tags }; + let feature = Named { kind, geometry, tags, id }; c0 <= c1 && r0 <= r1 && self.cut(zoom, &feature, parts, box_, [c0, r0, c1, r1]) } @@ -439,7 +427,7 @@ impl Tiles { mut box_: [f64; 4], [c0, r0, c1, r1]: [i64; 4], ) -> bool { - let Named { kind, geometry, tags } = *feature; + let Named { kind, geometry, tags, id } = *feature; let buffer = self.pad(zoom, r0).max(self.pad(zoom, r1)); let extent_i = i64::from(EXTENT); let rect = [ @@ -452,7 +440,7 @@ impl Tiles { return false; } if !(rect[0] <= box_[0] && box_[2] <= rect[2] && rect[1] <= box_[1] && box_[3] <= rect[3]) { - parts = clipped(geometry, &parts, rect); + parts = clipped(geometry, &parts, rect, reach(kind)); match extent(&parts) { Some(found) => box_ = found, None => return false, @@ -461,7 +449,7 @@ impl Tiles { if (c0, r0) == (c1, r1) { let cut = quantized(geometry, &parts, c0 * extent_i, r0 * extent_i); if !cut.is_empty() { - self.tiles.entry((zoom, c0 as u32, r0 as u32)).or_default().add(kind, tags, geometry, &cut); + self.tiles.entry((zoom, c0 as u32, r0 as u32)).or_default().add(kind, tags, geometry, &cut, id); } return !cut.is_empty(); } @@ -497,13 +485,13 @@ fn meets([ax, ay]: [f64; 2], [bx, by]: [f64; 2], [x0, y0, x1, y1]: [f64; 4]) -> } /// The pieces of a polyline that meet `rect`, as lists of vertex indices. A piece keeps the segments -/// that meet `rect` whole, and one more vertex at each end: the tiles that hold a segment hold the -/// same segment and the same bends at its ends. -fn clip_line(points: &[[f64; 2]], rect: [f64; 4]) -> Vec> { +/// that meet `rect` whole, and `reach` more vertices at each end: the tiles that hold a segment hold the +/// same segment and the same vertices about its ends. +fn clip_line(points: &[[f64; 2]], rect: [f64; 4], reach: usize) -> Vec> { let mut keep = vec![false; points.len()]; for k in 0..points.len().saturating_sub(1) { if meets(points[k], points[k + 1], rect) { - keep[k.saturating_sub(1)..(k + 3).min(points.len())].fill(true); + keep[k.saturating_sub(reach)..(k + 2 + reach).min(points.len())].fill(true); } } let mut pieces: Vec> = Vec::new(); @@ -549,8 +537,20 @@ fn clip_ring(ring: &[[f64; 2]], rect: [f64; 4]) -> Vec { indices } -/// Parts cut to `rect`. The cut makes no new vertex. -fn clipped(geometry: Geometry, parts: &[Part], rect: [f64; 4]) -> Vec { +/// The vertices that a line of `kind` keeps past the segments that meet a square: the ground plan draws +/// the curve of line water from the tile's vertices, and a span's curve reads two vertices on each side +/// of it (`obc_ground_plan::graph::water_spans`); every other line carries its plan. +fn reach(kind: &str) -> usize { + if WATER_KINDS.contains(&kind) { + 2 + } else { + 1 + } +} + +/// Parts cut to `rect`, a line with `reach` vertices past the segments that meet it. The cut makes no +/// new vertex. +fn clipped(geometry: Geometry, parts: &[Part], rect: [f64; 4], reach: usize) -> Vec { let pick = |outer: bool, part: &Part, indices: &[usize]| Part { outer, points: indices.iter().map(|&i| part.points[i]).collect(), @@ -573,7 +573,7 @@ fn clipped(geometry: Geometry, parts: &[Part], rect: [f64; 4]) -> Vec { .collect(), Geometry::Line => parts .iter() - .flat_map(|part| clip_line(&part.points, rect).into_iter().map(move |piece| (part, piece))) + .flat_map(|part| clip_line(&part.points, rect, reach).into_iter().map(move |piece| (part, piece))) .map(|(part, piece)| pick(false, part, &piece)) .collect(), Geometry::Area => parts.iter().map(|part| pick(part.outer, part, &clip_ring(&part.points, rect))).collect(), @@ -864,6 +864,53 @@ mod tests { Part { outer, points, z: None, plan: None } } + #[test] + fn a_feature_with_an_id_takes_more_tags_at_the_write_in_the_order_of_their_keys() { + let vectors = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../specs/vectors"); + let features = decode(&std::fs::read(vectors.join("trailview-features.bin")).unwrap()).unwrap(); + let mut tile = Tile::default(); + for (k, f) in features.iter().enumerate() { + tile.add(&f.kind, &f.tags, f.geometry, &f.parts, (k % 2 == 1).then_some(k as u32)); + } + assert_eq!(tile.bytes(), encode(&features), "no more tags, the same bytes"); + let more = Tags::from([("levels".to_string(), "D".to_string()), ("~".to_string(), "last".to_string())]); + let bytes = tile.bytes_with(&|id| (id == 1).then_some(&more)); + let tagged = decode(&bytes).unwrap(); + for (k, (a, b)) in features.iter().zip(&tagged).enumerate() { + let mut want = a.clone(); + if k == 1 { + want.tags.extend(more.clone()); + } + assert_eq!(as_json(b), as_json(&want), "feature {k}"); + } + // The keys of each feature in the order of the bytes: the strings, the count, two words of each head, then + // the tags. + let (n, mut at) = read_varint(&bytes, 0); + let mut strings = Vec::new(); + for _ in 0..n { + let (len, from) = read_varint(&bytes, at); + at = from + len as usize; + strings.push(String::from_utf8(bytes[from..at].to_vec()).unwrap()); + } + let (count, from) = read_varint(&bytes, at); + at = from; + for _ in 0..2 * count { + at = read_varint(&bytes, at).1; + } + for k in 0..count { + let (pairs, from) = read_varint(&bytes, at); + at = from; + let mut keys = Vec::new(); + for _ in 0..pairs { + let (key, from) = read_varint(&bytes, at); + at = read_varint(&bytes, from).1; + keys.push(strings[key as usize].clone()); + } + assert!(keys.windows(2).all(|w| w[0] < w[1]), "feature {k}: keys {keys:?}"); + assert_eq!(keys.len(), features[k as usize].tags.len() + if k == 1 { more.len() } else { 0 }); + } + } + #[test] fn an_island_near_a_curved_shore_does_not_cross_it_at_any_zoom() { // A lake whose shore curves 45 m over 2 km, with a 200 m island 8 m off the shore. @@ -903,13 +950,30 @@ mod tests { let mut tiles = Tiles::new([lon(column), lat(row + 1.0), lon(column + 1.0), lat(row)]); let at = |x: f64, y: f64| [x / n, y / n]; let line = [part(false, vec![at(column - 3.0, row + 0.5), at(column + 4.0, row + 0.5)])]; - assert!(tiles.add(13, "road", Geometry::Line, &Tags::new(), &line)); + assert!(tiles.add(13, "road", Geometry::Line, &Tags::new(), &line, None)); let tile = decode(&tiles.tiles[&(13, column as u32, row as u32)].bytes()).unwrap(); // The cut keeps the segment whole: no vertex is added at the tile's edges. let width = 7 * i64::from(EXTENT); assert_eq!(tile[0].parts[0].xy[1][0] - tile[0].parts[0].xy[0][0], width); } + #[test] + fn a_stream_keeps_two_vertices_past_the_segments_that_meet_a_tile_and_a_road_one() { + let n = (1u64 << 13) as f64; + let (column, row) = (4286.0, 2889.0); + let lon = |x: f64| x / n * 360.0 - 180.0; + let lat = |y: f64| (std::f64::consts::PI * (1.0 - 2.0 * y / n)).sinh().atan().to_degrees(); + // Two segments meet the tile; the vertices around them lie a tile apart. + let line = + [part(false, [-3.0, -2.0, -1.0, 0.5, 2.0, 3.0, 4.0].map(|x| [(column + x) / n, (row + 0.5) / n]).to_vec())]; + for (kind, vertices) in [("road", 5), ("stream", 7)] { + let mut tiles = Tiles::new([lon(column), lat(row + 1.0), lon(column + 1.0), lat(row)]); + assert!(tiles.add(13, kind, Geometry::Line, &Tags::new(), &line, None)); + let tile = decode(&tiles.tiles[&(13, column as u32, row as u32)].bytes()).unwrap(); + assert_eq!(tile[0].parts[0].xy.len(), vertices, "{kind}"); + } + } + #[test] fn two_tiles_that_hold_a_vertex_hold_one_alignment_and_a_low_zoom_holds_none() { let n = (1u64 << MAX_ZOOM) as f64; @@ -941,7 +1005,7 @@ mod tests { plan: Some(plan), ..Part::default() }; - assert!(tiles.add(MAX_ZOOM, "road", Geometry::Line, &Tags::new(), std::slice::from_ref(&line))); + assert!(tiles.add(MAX_ZOOM, "road", Geometry::Line, &Tags::new(), std::slice::from_ref(&line), None)); let tile = |c: f64| decode(&tiles.tiles[&(MAX_ZOOM, c as u32, row as u32)].bytes()).unwrap().remove(0).parts.remove(0); let (west, east) = (tile(column), tile(column + 1.0)); diff --git a/host/obc-trailview-features/src/water.rs b/host/obc-trailview-features/src/water.rs index 5544dd4caa..dc7f5a9164 100644 --- a/host/obc-trailview-features/src/water.rs +++ b/host/obc-trailview-features/src/water.rs @@ -1,12 +1,13 @@ //! The water levels: each lake at one level, and the rivers and streams as networks whose levels -//! never rise downstream. `specs/trailview-features.md` says what the levels promise. +//! never rise downstream and lie in a channel under their banks. `specs/trailview-features.md` says +//! what the levels promise. use std::collections::HashMap; +use obc_ground_plan::graph::{water_curves, water_grades, water_level, WaterCurve}; use rayon::prelude::*; -use rstar::{RTree, AABB}; -use crate::geometry::{arange, area, bounds, interp, key, percentile, Boxes}; +use crate::geometry::{arange, area, bounds, key, percentile, Boxes}; use crate::{metres, Part, Terrain}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -14,7 +15,7 @@ pub enum Kind { /// A river or a stream. River, Lake, - /// A waterfall, a dam or a dam point: the solver only reads it. + /// A waterfall, a dam or a dam point: it has no level. Mark, } @@ -30,22 +31,46 @@ pub enum Level { pub struct Feature { pub kind: Kind, pub level: Level, - /// The half-width of a waterway in metres. + /// The half-width of a waterway in metres, and its bank top: `freeboard` metres over its level, `bank` + /// metres past its waterline. pub half: f64, + pub bank: f64, + pub freeboard: f64, + /// The reader's curve of its spans, on which the vertices that its levels add lie. + pub curve: Curve, /// The `ele` tag, NaN without one. pub ele: f64, pub parts: Vec, } +/// The rules of the curve that the ground plan draws through the vertices of a waterway +/// (`obc_ground_plan::graph::water_curves`): per span a cubic Hermite, or the chord where a vertex turns by +/// more than `turn_max_deg`, where the curve leaves the chord by more than `off_max_m`, or where it folds +/// back. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Curve { + pub turn_max_deg: f64, + pub off_max_m: f64, +} + /// Per feature, per part: the heights of its points (NaN where unknown), or None. pub type Heights = Vec>>>; +/// A river part's points in the direction of its flow with the vertices that its levels add (`kept`), +/// and their levels. +pub type Line = (Vec<[f64; 2]>, Vec); + +/// Per feature, per part: its `Line` for a river, None for every other part. +pub type Kept = Vec>>; + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Metrics { pub lakes: usize, pub lakes_spilling: usize, pub river_parts: usize, pub turned: usize, + /// The vertices that the levels add to the rivers and streams (`kept`). + pub added: usize, } impl std::ops::AddAssign for Metrics { @@ -54,26 +79,24 @@ impl std::ops::AddAssign for Metrics { self.lakes_spilling += other.lakes_spilling; self.river_parts += other.river_parts; self.turned += other.turned; + self.added += other.added; } } /// A river observes the terrain every STEP_M along it, at its lowest within ±(w/2 + BESIDE_M) /// across it, at the ACROSS points. const STEP_M: f64 = 5.0; +/// A waterway keeps a sample as a vertex where a level drawn between the vertices around it (`kept`) +/// leaves the sample's level by more than this: half the least freeboard (a stream's 0.4 m), so the water +/// between two vertices stays under its banks. +const LEVEL_TOL_M: f64 = 0.2; const BESIDE_M: f64 = 2.0; const ACROSS: [f64; 5] = [-1.0, -0.5, 0.0, 0.5, 1.0]; -/// The fit holds z + LEAST_GRADE × s from rising downstream, so that a pool still falls a little and -/// the smoothing does not stair-step it. -const LEAST_GRADE: f64 = 0.0005; -/// The smoothing: a triangle kernel of this half-width. -const SMOOTH_M: f64 = 25.0; /// A way turns round when its terrain rises by more than this from end to end: OSM draws it uphill. const UPHILL_M: f64 = 5.0; /// A sample in a lake, or this near its shore, holds the lake's level with the weight PIN. const SHORE_M: f64 = 2.0; const PIN: f64 = 1000.0; -/// A fall, a weir or a dam this near a sample splits the smoothing there. -const FALL_M: f64 = 3.0; /// Lakes: the median of the interior holds where FLAT_SHARE of it lies within FLAT_M of it; else a /// shore quantile, INSET_M inside. An `ele` tag within ELE_M of the level wins. const FLAT_M: f64 = 0.3; @@ -91,23 +114,30 @@ const TILE: f64 = 512.0; type Key = [u64; 2]; -/// The levels of `features`, each network apart on the threads of the current rayon pool. A river +/// The levels of `features`, each network apart on the threads of the current rayon pool: at the +/// vertices of the map, and along the rivers with the vertices that their levels add (`Kept`). A river /// part that OSM draws uphill turns round in place; `turned` lists them as (feature, part). -pub fn solve_by_network(features: &mut [Feature], terrain: &dyn Terrain) -> (Heights, Vec<(usize, usize)>, Metrics) { +pub fn solve_by_network( + features: &mut [Feature], + terrain: &dyn Terrain, +) -> (Heights, Kept, Vec<(usize, usize)>, Metrics) { let mut found = groups(features); let size = |group: &Vec| -> usize { group.iter().flat_map(|&i| &features[i].parts).map(|p| p.points.len()).sum() }; found.sort_by_key(|group| std::cmp::Reverse(size(group))); - let marks = Marks::new(features); let shared: &[Feature] = features; let solved: Vec = - found.par_iter().with_max_len(1).map(|group| solve_group(shared, group, &marks, terrain)).collect(); + found.par_iter().with_max_len(1).map(|group| solve_group(shared, group, terrain)).collect(); let mut heights: Heights = features.iter().map(|f| vec![None; f.parts.len()]).collect(); + let mut kept: Kept = features.iter().map(|f| vec![None; f.parts.len()]).collect(); let (mut turned, mut metrics) = (Vec::new(), Metrics::default()); for group in solved { for (index, z) in group.heights { heights[index] = z; } + for ((f, p), points) in group.kept { + kept[f][p] = Some(points); + } turned.extend(group.turned); metrics += group.metrics; } @@ -115,7 +145,7 @@ pub fn solve_by_network(features: &mut [Feature], terrain: &dyn Terrain) -> (Hei for &(f, p) in &turned { features[f].parts[p].points.reverse(); } - (heights, turned, metrics) + (heights, kept, turned, metrics) } /// The indices of the features that solve apart from the others, each list in their order: each @@ -179,31 +209,18 @@ pub fn groups(features: &[Feature]) -> Vec> { /// per feature of the group its heights, the parts that turned round, and the metrics. struct Solved { heights: Vec<(usize, Vec>>)>, + kept: Vec<((usize, usize), Line)>, turned: Vec<(usize, usize)>, metrics: Metrics, } -/// The points of the falls, weirs and dams. -struct Marks(RTree<[f64; 2]>); - -impl Marks { - fn new(features: &[Feature]) -> Self { - let points = features - .iter() - .filter(|f| f.kind == Kind::Mark) - .flat_map(|f| &f.parts) - .flat_map(|p| p.points.iter().copied()); - Self(RTree::bulk_load(points.collect())) - } -} - struct Lake<'a> { rings: Vec<&'a [[f64; 2]]>, bounds: [f64; 4], level: f64, } -fn solve_group(features: &[Feature], group: &[usize], marks: &Marks, terrain: &dyn Terrain) -> Solved { +fn solve_group(features: &[Feature], group: &[usize], terrain: &dyn Terrain) -> Solved { let lakes: Vec<(usize, Lake)> = group .par_iter() .filter(|&&i| features[i].kind == Kind::Lake) @@ -225,12 +242,12 @@ fn solve_group(features: &[Feature], group: &[usize], marks: &Marks, terrain: &d .par_iter() .map(|&(index, n)| { let (feature, part) = (&features[index], &features[index].parts[n]); - let mut way = Way::new(part.points.clone(), feature.half, terrain); + let mut way = Way::new(part.points.clone(), feature, terrain); let uphill = way.uphill(); if uphill { let mut points = part.points.clone(); points.reverse(); - way = Way::new(points, feature.half, terrain); + way = Way::new(points, feature, terrain); } way.feature = index; way.part = n; @@ -242,15 +259,22 @@ fn solve_group(features: &[Feature], group: &[usize], marks: &Marks, terrain: &d let mut ways: Vec = solved.into_iter().map(|(way, _)| way).collect(); pin(&mut ways, &lakes); let boxes = Boxes::new(&ways.iter().map(|w| w.bounds).collect::>()); - let levels = network(&ways, marks); + let levels = network(&ways); let mut heights: HashMap>>> = group.iter().map(|&i| (i, vec![None; features[i].parts.len()])).collect(); for (index, lake) in &lakes { let level = if lake.level.is_finite() { lake.level } else { f64::NAN }; heights.insert(*index, features[*index].parts.iter().map(|p| Some(vec![level; p.points.len()])).collect()); } + let (mut kept_parts, mut added) = (Vec::with_capacity(ways.len()), 0); for (way, z) in ways.iter().zip(&levels) { heights.get_mut(&way.feature).unwrap()[way.part] = Some(way.vertices.iter().map(|&v| z[v]).collect()); + let curve = features[way.feature].curve; + let curves = curves(&way.points, curve); + let samples = kept(way, z, &curves, curve); + added += samples.len() - way.vertices.len(); + let points = samples.iter().map(|&i| way.point(i, &curves)).collect(); + kept_parts.push(((way.feature, way.part), (points, samples.iter().map(|&i| z[i]).collect()))); } let mut spilling = 0; for (_, lake) in &lakes { @@ -264,14 +288,67 @@ fn solve_group(features: &[Feature], group: &[usize], marks: &Marks, terrain: &d spilling += (lake.level.is_finite() && spills(lake.level, &lake.rings, terrain, &near)) as usize; } let metrics = - Metrics { lakes: lakes.len(), lakes_spilling: spilling, river_parts: ways.len(), turned: turned.len() }; + Metrics { lakes: lakes.len(), lakes_spilling: spilling, river_parts: ways.len(), turned: turned.len(), added }; let mut heights: Vec<_> = heights.into_iter().collect(); heights.sort_unstable_by_key(|(i, _)| *i); - Solved { heights, turned, metrics } + Solved { heights, kept: kept_parts, turned, metrics } +} + +/// Metres per world unit along the chord from a to b. +fn chord_metres(a: [f64; 2], b: [f64; 2]) -> f64 { + metres((a[1] + b[1]) / 2.0) +} + +/// Per span of `points` the curve that the ground plan draws, from the span's start. +fn curves(points: &[[f64; 2]], curve: Curve) -> Vec { + water_curves(points, curve.turn_max_deg, curve.off_max_m, chord_metres) +} + +/// The samples of a way that it keeps as vertices: its own vertices, and the samples that a level drawn +/// between the kept ones leaves by more than LEVEL_TOL_M: in each round the farthest of each such span, +/// until none is left. So the levels hold along the line, not only at the vertices of the map. Two readers +/// draw a level, both read at the foot of each sample on the ground plan's curve through the kept vertices +/// (`water_curves`, `WaterCurve::share_near`): the ground plan's cubic `water_level` with `water_grades` +/// over that curve's length, and the straight level of the water ribbons and the stamp's channel. A kept +/// vertex changes the curve and the grades beside it, so the rounds test every span again. +fn kept(way: &Way, z: &[f64], curves: &[WaterCurve], curve: Curve) -> Vec { + let at: Vec<[f64; 2]> = (0..z.len()).map(|i| way.point(i, curves)).collect(); + let level = |i: usize| z[i].is_finite().then_some(z[i]); + let mut out = way.vertices.clone(); + loop { + let points: Vec<[f64; 2]> = out.iter().map(|&i| at[i]).collect(); + let drawn = self::curves(&points, curve); + let grades = water_grades(&points, &out.iter().map(|&i| level(i)).collect::>(), chord_metres); + let mut more = Vec::new(); + for (j, pair) in out.windows(2).enumerate() { + let (a, b) = (pair[0], pair[1]); + let (sa, sb) = (way.along[a], way.along[b]); + if b <= a + 1 || !(z[a].is_finite() && z[b].is_finite()) || sb <= sa { + continue; + } + let (c, p0) = (&drawn[j], points[j]); + let len = c.length() * chord_metres(p0, points[j + 1]); + let off = |i: usize| { + let t = c.share_near([at[i][0] - p0[0], at[i][1] - p0[1]], (way.along[i] - sa) / (sb - sa)); + let cubic = water_level([z[a], z[b]], [grades[j], grades[j + 1]], len, t).0; + (z[i] - cubic).abs().max((z[i] - (z[a] + t * (z[b] - z[a]))).abs()) + }; + let worst = + (a + 1..b).filter(|&i| z[i].is_finite()).map(|i| (i, off(i))).max_by(|x, y| x.1.total_cmp(&y.1)); + more.extend(worst.filter(|w| w.1 > LEVEL_TOL_M).map(|w| w.0)); + } + if more.is_empty() { + return out; + } + out.extend(more); + out.sort_unstable(); + } } /// A river part: its points (world coordinates, y down) in the direction of its flow, the samples -/// along it every STEP_M with the lowest terrain across it, and their weights. +/// along it every STEP_M with the lowest terrain across it, their weights, the most level that keeps +/// the freeboard under the lower bank top (NaN where the terrain is unknown), and how far its bank +/// top lies from its middle. struct Way { points: Vec<[f64; 2]>, xy: Vec<[f64; 2]>, @@ -281,12 +358,15 @@ struct Way { bounds: [f64; 4], low: Vec, weight: Vec, + channel: Vec, + banks: f64, feature: usize, part: usize, } impl Way { - fn new(points: Vec<[f64; 2]>, half: f64, terrain: &dyn Terrain) -> Self { + fn new(points: Vec<[f64; 2]>, feature: &Feature, terrain: &dyn Terrain) -> Self { + let half = feature.half; let d: Vec<[f64; 2]> = points.windows(2).map(|w| [w[1][0] - w[0][0], w[1][1] - w[0][1]]).collect(); let lengths: Vec = points.windows(2).zip(&d).map(|(w, d)| d[0].hypot(d[1]) * metres((w[0][1] + w[1][1]) / 2.0)).collect(); @@ -314,9 +394,7 @@ impl Way { [-d[1] / norm, d[0] / norm] }) .collect(); - let mut low = vec![f64::NAN; xy.len()]; - for o in ACROSS { - let o = o * (half + BESIDE_M); + let beside = |o: f64| -> Vec { let across: Vec<[f64; 2]> = xy .iter() .zip(&sample) @@ -325,15 +403,43 @@ impl Way { [p[0] + normal[k][0] * s, p[1] + normal[k][1] * s] }) .collect(); - for (low, h) in low.iter_mut().zip(terrain.heights(&across)) { - if h < *low || low.is_nan() { - *low = h; + terrain.heights(&across) + }; + let lowest = |offsets: &[f64]| { + let mut low = vec![f64::NAN; xy.len()]; + for &o in offsets { + for (low, h) in low.iter_mut().zip(beside(o)) { + if h < *low || low.is_nan() { + *low = h; + } } } - } + low + }; + let low = lowest(&ACROSS.map(|o| o * (half + BESIDE_M))); + let banks = half + feature.bank; + let channel = lowest(&[-banks, banks]).iter().map(|h| h - feature.freeboard).collect(); let weight = low.iter().map(|h| if h.is_finite() { 1.0 } else { 0.0 }).collect(); let bounds = bounds(&xy); - Self { points, xy, along, vertices, bounds, low, weight, feature: 0, part: 0 } + Self { points, xy, along, vertices, bounds, low, weight, channel, banks, feature: 0, part: 0 } + } + + /// The span of the map that sample i starts or lies in. + fn span_of(&self, i: usize) -> usize { + self.vertices.partition_point(|&v| v <= i) - 1 + } + + /// The point of sample i: a vertex of the map keeps its own point, which other features share. Another + /// sample lies on the curve of its span (`curves`) at its share of the span's length: on the chord, it + /// would pull a curved span to its chord. + fn point(&self, i: usize, curves: &[WaterCurve]) -> [f64; 2] { + if let Ok(j) = self.vertices.binary_search(&i) { + return self.points[j]; + } + let k = self.span_of(i); + let (a, b) = (self.along[self.vertices[k]], self.along[self.vertices[k + 1]]); + let q = curves[k].at_share((self.along[i] - a) / (b - a)); + [self.points[k][0] + q[0], self.points[k][1] + q[1]] } /// Whether the terrain along the way rises by more than UPHILL_M: a straight fit to its lows. @@ -352,7 +458,9 @@ impl Way { } } -/// A sample in a lake, or within SHORE_M of its shore, holds the lake's level with the weight PIN. +/// A sample in a lake, or within SHORE_M of its shore, holds the lake's level with the weight PIN, +/// but not the samples that a way starts with there: water that flows out of a lake, over a dam or a +/// sill, takes its levels from its own fit and channel. A way wholly in a lake keeps them all. fn pin(ways: &mut [Way], lakes: &[(usize, Lake)]) { let lakes: Vec<([f64; 4], f64, Edges)> = lakes .par_iter() @@ -365,19 +473,25 @@ fn pin(ways: &mut [Way], lakes: &[(usize, Lake)]) { .collect(); let boxes = Boxes::new(&lakes.iter().map(|(b, _, _)| *b).collect::>()); ways.par_iter_mut().for_each(|way| { + let mut held = vec![None; way.xy.len()]; for k in boxes.overlapping(way.bounds) { let (b, level, edges) = &lakes[k]; - for s in 0..way.xy.len() { - let [x, y] = way.xy[s]; + for (&[x, y], held) in way.xy.iter().zip(held.iter_mut()) { if !(x >= b[0] && x <= b[2] && y >= b[1] && y <= b[3]) { continue; } if edges.contains(x, y) || edges.distance(x, y, SHORE_M / metres(y)) * metres(y) < SHORE_M { - way.low[s] = *level; - way.weight[s] = PIN; + *held = Some(*level); } } } + let start = held.iter().position(Option::is_none).unwrap_or(0); + for (s, level) in held.into_iter().enumerate().skip(start) { + if let Some(level) = level { + way.low[s] = level; + way.weight[s] = PIN; + } + } }); } @@ -386,13 +500,18 @@ fn pin(ways: &mut [Way], lakes: &[(usize, Lake)]) { /// start, and all reaches at a junction then take one level there. A loop of reaches has no order of /// flow: its reaches go from the highest start down (a spanning DAG), and a reach that flows back /// into a junction solved before it keeps its own end there, a step down to it. -fn network(ways: &[Way], marks: &Marks) -> Vec> { +fn network(ways: &[Way]) -> Vec> { + // Per point, how many ways have it, and the farthest bank top of those ways from it. let mut counts: HashMap = HashMap::new(); + let mut banks: HashMap = HashMap::new(); for way in ways { for &point in &way.points { *counts.entry(key(point)).or_default() += 1; + let far = banks.entry(key(point)).or_insert(0.0); + *far = far.max(way.banks); } } + let skip = |point: Key| if counts[&point] > 1 { banks[&point] } else { 0.0 }; // (way, first sample, last sample, first point, last point), and per junction in the order of // its first reach the reaches into it and out of it. let mut reaches: Vec<(usize, usize, usize, Key, Key)> = Vec::new(); @@ -437,7 +556,7 @@ fn network(ways: &[Way], marks: &Marks) -> Vec> { for r in component { let (w, a, b, first, end) = reaches[r]; let cap = ends.get(&first).map_or(f64::INFINITY, |v| v.iter().copied().fold(f64::INFINITY, f64::min)); - let z = reach_levels(&ways[w], a, b, cap, marks); + let z = reach_levels(&ways[w], (a, b), cap, (skip(first), skip(end))); levels[w][a..=b].copy_from_slice(&z); rank[r] = ranked; ranked += 1; @@ -531,84 +650,42 @@ fn components(after: &[&[usize]]) -> Vec> { out } -/// The levels of the samples a..=b of a way: the fit that never rises to the lows plus LEAST_GRADE -/// per metre, under the cap, smoothed apart at falls, weirs and dams. -fn reach_levels(way: &Way, a: usize, b: usize, cap: f64, marks: &Marks) -> Vec { - let (low, weight, along) = (&way.low[a..=b], &way.weight[a..=b], &way.along[a..=b]); - let known: Vec = (0..low.len()).filter(|&i| weight[i] > 0.0).collect(); - if known.is_empty() { - return vec![f64::NAN; low.len()]; - } - let s: Vec = along.iter().map(|v| v - along[0]).collect(); - let sk: Vec = known.iter().map(|&i| s[i]).collect(); - let y: Vec = known.iter().map(|&i| low[i] + LEAST_GRADE * s[i]).collect(); - let w: Vec = known.iter().map(|&i| weight[i]).collect(); - let fit: Vec = falling(&y, &w).iter().zip(&sk).map(|(f, s)| f - LEAST_GRADE * s).collect(); - let mut z: Vec = s.iter().map(|&x| interp(x, &sk, &fit)).collect(); - let mut least = f64::INFINITY; - for v in &mut z { - least = least.min(v.min(cap)); - *v = least; - } - let mut splits = Vec::new(); - if marks.0.size() > 0 { - let xy = &way.xy[a..=b]; - let [x0, y0, x1, y1] = bounds(xy); - let envelope = AABB::from_corners([x0 - 1e-5, y0 - 1e-5], [x1 + 1e-5, y1 + 1e-5]); - let near: Vec<[f64; 2]> = marks.0.locate_in_envelope(&envelope).copied().collect(); - for (i, p) in xy.iter().enumerate().skip(1) { - if near.iter().any(|&[x, y]| (p[0] - x).hypot(p[1] - y) * metres(y) < FALL_M) { - splits.push(i); - } - } - } - smoothed(&z, &splits) -} - -/// The weighted least-squares fit to y that never rises (pool-adjacent violators). -fn falling(y: &[f64], w: &[f64]) -> Vec { - let (mut means, mut weights, mut counts): (Vec, Vec, Vec) = (Vec::new(), Vec::new(), Vec::new()); - for (&value, &weight) in y.iter().zip(w) { - means.push(value); - weights.push(weight); - counts.push(1); - while means.len() > 1 && means[means.len() - 2] < means[means.len() - 1] { - let n = means.len(); - let weight = weights[n - 2] + weights[n - 1]; - means[n - 2] = (means[n - 2] * weights[n - 2] + means[n - 1] * weights[n - 1]) / weight; - weights[n - 2] = weight; - counts[n - 2] += counts[n - 1]; - means.pop(); - weights.pop(); - counts.pop(); +/// The levels of the samples a..=b of a way: the highest levels that never rise downstream, lie under +/// the cap, and lie at each sample under its low and its channel, so that the water lies in a channel +/// under its banks at its own line. Within `skip` metres of a junction at its (start, end), the bank +/// tops lie in the other waterway's bed and do not count, nor do they at a sample in a lake. A sample +/// with no known terrain takes the level before it, or after it at the start. A reach never goes +/// under a lake that it flows into. +fn reach_levels(way: &Way, (a, b): (usize, usize), cap: f64, (start, end): (f64, f64)) -> Vec { + let (low, channel, weight, along) = (&way.low[a..=b], &way.channel[a..=b], &way.weight[a..=b], &way.along[a..=b]); + let total = along[along.len() - 1] - along[0]; + let banks = |i: usize| { + let s = along[i] - along[0]; + if s < start || total - s < end || weight[i] >= PIN { + f64::NAN + } else { + channel[i] } + }; + let under: Vec = (0..low.len()).map(|i| low[i].min(banks(i))).collect(); + let Some(first) = under.iter().copied().find(|v| v.is_finite()) else { return vec![f64::NAN; low.len()] }; + // The level of a lake that the reach flows into: a pinned sample after a free one. A reach that + // flows out of a lake starts pinned and takes no such floor. + let free = weight.iter().position(|&w| w < PIN).unwrap_or(under.len()); + let mut lake = vec![f64::NEG_INFINITY; under.len()]; + for i in (0..under.len()).rev() { + let below = lake.get(i + 1).copied().unwrap_or(f64::NEG_INFINITY); + lake[i] = if weight[i] >= PIN && i > free { below.max(low[i]) } else { below }; } - means.iter().zip(&counts).flat_map(|(&m, &c)| std::iter::repeat_n(m, c)).collect() -} - -/// z under a triangle kernel of SMOOTH_M, with each end held: a positive kernel keeps a profile that -/// never rises. The pieces between splits are smoothed apart. -fn smoothed(z: &[f64], splits: &[usize]) -> Vec { - let k = (SMOOTH_M / STEP_M).floor() as usize; - let mut kernel: Vec = (0..2 * k + 1).map(|i| 1.0 - (i as f64 - k as f64).abs() / (k + 1) as f64).collect(); - let total: f64 = kernel.iter().sum(); - kernel.iter_mut().for_each(|v| *v /= total); - let mut bounds = vec![0]; - bounds.extend_from_slice(splits); - bounds.push(z.len()); - let mut out = Vec::with_capacity(z.len()); - for pair in bounds.windows(2).filter(|pair| pair[1] > pair[0]) { - let piece = &z[pair[0]..pair[1]]; - let at = |i: usize| piece[i.saturating_sub(k).min(piece.len() - 1)]; - for i in 0..piece.len() { - let mut sum = 0.0; - for (j, weight) in kernel.iter().rev().enumerate() { - sum += at(i + j) * weight; + let mut least = cap.min(first); + (0..under.len()) + .map(|i| { + if under[i].is_finite() { + least = least.min(under[i]); } - out.push(sum); - } - } - out + least.max(lake[i]) + }) + .collect() } /// The level of a lake: the median of its interior where it is flat; else the SHORE_QUANTILE of its @@ -802,6 +879,9 @@ mod tests { kind, level: Level::Natural, half: 1.0, + bank: 0.0, + freeboard: 0.0, + curve: Curve { turn_max_deg: 60.0, off_max_m: 2.0 }, ele: f64::NAN, parts: vec![Part { outer: kind == Kind::Lake, points, z: None, plan: None }], } @@ -814,7 +894,7 @@ mod tests { /// The levels of all rivers and lakes of `features` in one solve. fn solve(features: &mut [Feature], terrain: &dyn Terrain) -> (Heights, Metrics) { let group: Vec = (0..features.len()).filter(|&i| features[i].kind != Kind::Mark).collect(); - let solved = solve_group(features, &group, &Marks::new(features), terrain); + let solved = solve_group(features, &group, terrain); let mut heights: Heights = features.iter().map(|f| vec![None; f.parts.len()]).collect(); for (index, z) in solved.heights { heights[index] = z; @@ -829,6 +909,30 @@ mod tests { heights[feature][0].clone().unwrap() } + /// The kept lines of the first part of each river in one solve. + fn lines_of(features: &[Feature], terrain: &dyn Terrain) -> Vec { + let group: Vec = (0..features.len()).filter(|&i| features[i].kind == Kind::River).collect(); + let mut kept = solve_group(features, &group, terrain).kept; + kept.sort_unstable_by_key(|k| k.0); + kept.into_iter().map(|(_, line)| line).collect() + } + + /// The kept points (metres east of the origin) and levels of the first part of each river in one solve. + fn kept_of(features: &[Feature], terrain: &dyn Terrain) -> Vec<(Vec, Vec)> { + let (x0, _, scale) = origin(); + let lines = lines_of(features, terrain); + lines.into_iter().map(|(p, z)| (p.iter().map(|p| (p[0] - x0) * scale).collect(), z)).collect() + } + + /// The points of the curve through `points`, 64 per span, and its end. + fn drawn(points: &[[f64; 2]]) -> Vec<[f64; 2]> { + let spans = curves(points, Curve { turn_max_deg: 60.0, off_max_m: 2.0 }); + let at = |(c, p): (&WaterCurve, &[f64; 2])| -> Vec<[f64; 2]> { + (0..64).map(|j| c.at_share(f64::from(j) / 64.0)).map(|q| [p[0] + q[0], p[1] + q[1]]).collect() + }; + spans.iter().zip(points).flat_map(at).chain(points.last().copied()).collect() + } + fn falls(z: &[f64]) -> bool { z.windows(2).all(|w| w[1] <= w[0] + 1e-9) } @@ -858,12 +962,77 @@ mod tests { assert!(z.iter().zip(bottom).all(|(a, b)| (a - b).abs() < 2.0)); } + #[test] + fn a_long_span_keeps_vertices_where_the_drawn_level_leaves_the_terrain_and_a_plane_keeps_none() { + // A stream with two vertices 400 m apart: the meadow falls 40 m over its first 100 m, then 4 m. On flat + // ground across it, its level is the terrain less its freeboard. + let fall = |e: f64| if e < 100.0 { 1000.0 - 0.4 * e } else { 960.0 - 0.0133 * (e - 100.0) }; + let stream = Feature { half: 0.5, bank: 0.6, freeboard: 0.4, ..river(vec![at(0.0, 0.0), at(400.0, 0.0)]) }; + let (east, z) = kept_of(std::slice::from_ref(&stream), &terrain(move |e, _| fall(e))).remove(0); + assert!(east.len() > 2 && east.len() < 10, "{east:?}"); + assert!(falls(&z)); + // The map's vertices keep their levels: the roads read those. + let mut map = vec![stream.clone()]; + let at_map = levels(&solve(&mut map, &terrain(move |e, _| fall(e))).0, 0); + assert_eq!([z[0], z[z.len() - 1]], [at_map[0], at_map[1]]); + // Every 5 m both levels drawn between the kept vertices, the ground plan's cubic and the straight one, + // lie within the tolerance of the level there. + let points: Vec<[f64; 2]> = east.iter().map(|&e| [e, 0.0]).collect(); + let grades = water_grades(&points, &z.iter().map(|&z| Some(z)).collect::>(), |_, _| 1.0); + for e in (0..=400).step_by(5).map(f64::from) { + let k = east.partition_point(|&x| x <= e).clamp(1, east.len() - 1); + let (len, t) = (east[k] - east[k - 1], (e - east[k - 1]) / (east[k] - east[k - 1])); + let cubic = water_level([z[k - 1], z[k]], [grades[k - 1], grades[k]], len, t).0; + for level in [cubic, z[k - 1] + t * (z[k] - z[k - 1])] { + assert!((level - (fall(e) - 0.4)).abs() <= LEVEL_TOL_M + 0.01, "{e} m: {level} over {}", fall(e)); + } + } + let plane = kept_of(&[stream], &terrain(|e, _| 1000.0 - 0.1 * e)).remove(0); + assert_eq!(plane.0.len(), 2); + } + + #[test] + fn the_added_vertices_lie_on_the_curve_that_the_reader_draws_through_the_map_s_vertices() { + // A meander of 800 m and a corner of 90° over the meadow that falls steeply, then gently. The spans + // before 400 m east are curves beside curves; the span to the corner is a curve beside a chord. + let fall = + |e: f64, s: f64| if e + s < 100.0 { 1000.0 - 0.4 * (e + s) } else { 960.0 - 0.0133 * (e + s - 100.0) }; + let map = + vec![at(0.0, 0.0), at(200.0, 12.0), at(400.0, 0.0), at(600.0, 12.0), at(800.0, 0.0), at(800.0, 200.0)]; + let stream = Feature { half: 0.5, bank: 0.6, freeboard: 0.4, ..river(map.clone()) }; + let (kept, _) = lines_of(&[stream], &terrain(fall)).remove(0); + assert!(kept.len() > map.len(), "{} vertices", kept.len()); + let (before, after) = (drawn(&map), drawn(&kept)); + let (_, _, scale) = origin(); + // The distance of each point of the new curve to the old one, a polyline of 64 chords per span. + let to = |q: &[f64; 2], a: [f64; 2], b: [f64; 2]| { + let (d, e) = ([b[0] - a[0], b[1] - a[1]], [q[0] - a[0], q[1] - a[1]]); + let t = ((e[0] * d[0] + e[1] * d[1]) / (d[0] * d[0] + d[1] * d[1]).max(1e-30)).clamp(0.0, 1.0); + (e[0] - t * d[0]).hypot(e[1] - t * d[1]) + }; + let off_of = |points: &[[f64; 2]]| { + let near = |q: &[f64; 2]| before.windows(2).map(|w| to(q, w[0], w[1])).fold(f64::INFINITY, f64::min); + points.iter().map(|q| near(q) * scale).fold(0.0, f64::max) + }; + // The added vertices lie on the curve through the map's vertices. + assert!(off_of(&kept) < 0.01, "a kept vertex lies {} m off the curve", off_of(&kept)); + // The reader takes the tangents at the kept vertices from their new, nearer neighbours: a curve beside + // curves moves by decimetres (most where a long sub-span leaves an added vertex along the bisector of + // its new chords), where vertices on the chords would move it by its bulge (here 1.5 m). On a + // span that it drew as its chord, a sub-span next to a vertex that is no corner can become a curve, and + // the curve beside it then leaves that chord's direction: by up to `curve_off_max_m`. + let (x0, _, _) = origin(); + let (curved, rest): (Vec<[f64; 2]>, Vec<[f64; 2]>) = after.iter().partition(|q| (q[0] - x0) * scale < 400.0); + assert!(off_of(&curved) < 0.5, "a curve beside curves moves {} m", off_of(&curved)); + assert!(off_of(&rest) <= 2.0, "the line beside a chord moves {} m", off_of(&rest)); + } + #[test] fn a_way_drawn_uphill_turns_round() { let slope = terrain(|e, _| 1000.0 + 0.02 * e); let mut features = vec![Feature { half: 1.0, ..river((0..=1000).step_by(100).map(|e| at(e as f64, 0.0)).collect()) }]; - let (heights, turned, metrics) = solve_by_network(&mut features, &slope); + let (heights, _, turned, metrics) = solve_by_network(&mut features, &slope); assert_eq!(features[0].parts[0].points[0], at(1000.0, 0.0), "the way runs downstream now"); assert!(falls(&levels(&heights, 0))); assert_eq!((turned, metrics.turned), (vec![(0, 0)], 1)); @@ -938,6 +1107,104 @@ mod tests { assert!(z[11] < 1000.5, "at 550 m"); } + #[test] + fn a_meadow_stream_lies_in_a_channel_and_a_flat_after_a_steep_reach_does_not_lift_it() { + // The terrain falls 10 % to 300 m, then 0.1 %; the stream runs in no channel of the terrain. + let ground = terrain(|e, _| if e < 300.0 { 1030.0 - 0.1 * e } else { 1000.0 - 0.001 * (e - 300.0) }); + let points: Vec<[f64; 2]> = (0..=1000).step_by(50).map(|e| at(e as f64, 0.0)).collect(); + let stream = Feature { half: 0.5, bank: 0.6, freeboard: 0.4, ..river(points) }; + let z = levels(&solve(&mut [stream], &ground).0, 0); + assert!(falls(&z)); + for (n, level) in z.iter().enumerate() { + let e = 50.0 * n as f64; + let banks = if e < 300.0 { 1030.0 - 0.1 * e } else { 1000.0 - 0.001 * (e - 300.0) }; + assert!(*level <= banks - 0.4 + 0.01, "{e} m: {level} over {banks}"); + assert!(*level > banks - 1.0, "{e} m: {level} sinks too far under {banks}"); + } + } + + #[test] + fn a_steep_stream_lies_its_freeboard_under_the_terrain_at_its_line_from_the_head_of_its_reach_on() { + // A mountain stream that falls 50 %, then 80 %. + let height = |e: f64| if e < 40.0 { 1176.0 - 0.5 * e } else { 1156.0 - 0.8 * (e - 40.0) }; + let ground = terrain(move |e, _| height(e)); + let points: Vec<[f64; 2]> = (0..=150).step_by(10).map(|e| at(e as f64, 0.0)).collect(); + let stream = Feature { half: 0.5, bank: 0.6, freeboard: 0.4, ..river(points) }; + let z = levels(&solve(&mut [stream], &ground).0, 0); + assert!(falls(&z)); + for (n, level) in z.iter().enumerate() { + let line = height(10.0 * n as f64); + assert!((level - (line - 0.4)).abs() < 0.01, "{n}: {level} against {line}"); + } + } + + #[test] + fn a_stream_below_a_dam_takes_its_own_levels_and_not_the_reservoirs() { + // A reservoir at 1900 m whose outline holds its dam; its outflow starts on the dam's crest and + // falls 20 m down its face into a valley. + let ground = terrain(|e, s| { + if e < 404.0 { + if e > 5.0 && s > 5.0 && s < 395.0 { + 1850.0 + } else { + 1900.0 + } + } else { + 1880.0 - 0.05 * (e - 404.0) + } + }); + let outline = vec![at(0.0, 0.0), at(408.0, 0.0), at(408.0, 400.0), at(0.0, 400.0)]; + let mut features = vec![ + Feature { level: Level::Reservoir, ..feature(Kind::Lake, outline) }, + Feature { + half: 0.5, + bank: 0.6, + freeboard: 0.4, + ..river(vec![at(408.0, 200.0), at(600.0, 200.0), at(800.0, 200.0)]) + }, + ]; + let heights = solve(&mut features, &ground).0; + let (level, z) = (levels(&heights, 0)[0], levels(&heights, 1)); + assert!(level > 1890.0); + assert!(falls(&z) && z[0] < 1880.0, "{z:?}"); + assert!(z[2] <= 1880.0 - 0.05 * (800.0 - 404.0) - 0.4 + 0.01, "{z:?}"); + } + + #[test] + fn a_stream_into_a_river_channel_does_not_cap_the_river() { + // A river 10 m wide in a channel 2 m under a meadow that falls 0.1 % east; a stream from the + // north ends on it, and its last bank tops lie in the river's channel. + let ground = terrain(|e, s| 1000.0 - 0.001 * e - if s.abs() < 5.0 { 2.0 } else { 0.0 }); + let main = + || Feature { bank: 2.0, freeboard: 0.8, ..river(vec![at(-400.0, 0.0), at(0.0, 0.0), at(600.0, 0.0)]) }; + let stream = Feature { half: 0.5, bank: 0.6, freeboard: 0.4, ..river(vec![at(0.0, -300.0), at(0.0, 0.0)]) }; + let alone = levels(&solve(&mut [main()], &ground).0, 0); + let heights = solve(&mut [main(), stream], &ground).0; + let (joined, stream) = (levels(&heights, 0), levels(&heights, 1)); + assert!(falls(&joined) && falls(&stream)); + assert_eq!(stream[1], joined[1]); + for (a, b) in alone.iter().zip(&joined) { + assert!((a - b).abs() < 0.05, "{alone:?} {joined:?}"); + } + } + + #[test] + fn a_stream_into_a_lake_keeps_the_lake_level_at_its_shore() { + // A lake on flat ground at 1000 m; a stream comes down from the west onto its shore. + let ground = terrain(|e, _| 1000.0 + 0.01 * (-e).max(0.0)); + let stream = Feature { + half: 0.5, + bank: 0.6, + freeboard: 0.4, + ..river(vec![at(-300.0, 200.0), at(-150.0, 200.0), at(0.0, 200.0), at(50.0, 200.0)]) + }; + let heights = solve(&mut [feature(Kind::Lake, square()), stream], &ground).0; + let (lake, z) = (levels(&heights, 0)[0], levels(&heights, 1)); + assert_eq!(lake, 1000.0); + assert!(falls(&z) && z.iter().all(|&v| v >= lake - 0.02), "{z:?}"); + assert!((z[3] - lake).abs() < 0.02 && z[1] < 1001.5 - 0.39, "{z:?}"); + } + fn square() -> Vec<[f64; 2]> { vec![at(0.0, 0.0), at(400.0, 0.0), at(400.0, 400.0), at(0.0, 400.0)] } @@ -1020,7 +1287,7 @@ mod tests { let (mut whole, mut apart) = (features.clone(), features.clone()); let (heights, metrics) = solve(&mut whole, &slope); let pool = rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap(); - let (by_network, turned, metrics_by_network) = pool.install(|| solve_by_network(&mut apart, &slope)); + let (by_network, _, turned, metrics_by_network) = pool.install(|| solve_by_network(&mut apart, &slope)); assert_eq!(format!("{heights:?}"), format!("{by_network:?}")); assert_eq!((metrics, turned), (metrics_by_network, vec![(5, 0)])); let points = |f: &[Feature]| f.iter().map(|f| f.parts.clone()).collect::>(); diff --git a/host/obc-trailview-features/tests/census.rs b/host/obc-trailview-features/tests/census.rs new file mode 100644 index 0000000000..e914a022ed --- /dev/null +++ b/host/obc-trailview-features/tests/census.rs @@ -0,0 +1,84 @@ +//! The census over three cells of the TrailView fixture: a worker that panics and one that hangs each +//! end on their cell and the run goes on, and the cell between them builds as the viewer builds it. A +//! resume ends a partial last line, builds the timed-out cell once more and the panicked one never. +//! Workers that end before their first cell stop the run. + +#[path = "../../obc-ground-plan/tests/fixture/mod.rs"] +mod fixture; + +use std::collections::BTreeMap; +use std::io::Write; +use std::path::Path; +use std::process::{Command, Output}; + +use obc_ground_plan::cell::build_cell; +use obc_ground_plan::faces::Rules; +use obc_ground_plan::frame::CellKey; +use obc_ground_plan::transport::Flat; +use serde_json::Value; + +/// Three cells in a row: the first panics, the third hangs; the middle one has ways. +const ROW: [CellKey; 3] = + [CellKey { x: 34304, y: 23104 }, CellKey { x: 34305, y: 23104 }, CellKey { x: 34306, y: 23104 }]; + +fn census(out: &Path, fail: &[String]) -> Output { + let cells = ROW.map(|k| format!("{}/{}", k.x, k.y)).join(","); + let mut command = Command::new(env!("CARGO_BIN_EXE_census")); + command.args(["--fixture", fixture::default_dir().to_str().unwrap(), "--out", out.to_str().unwrap()]); + command.args([ + "--memory", + "none", + "--workers", + "1", + "--timeout-s", + "3", + "--min-available-gb", + "0", + "--cells", + &cells, + ]); + command.args(fail.iter().flat_map(|f| ["--fail", f.as_str()])).output().unwrap() +} + +/// The lines of `census.jsonl` that parse, by cell, and the count of all lines. +fn lines(out: &Path) -> (BTreeMap, usize) { + let text = std::fs::read_to_string(out.join("census.jsonl")).unwrap(); + let parsed = text.lines().filter_map(|l| serde_json::from_str::(l).ok()).filter(|v| v["cell"].is_array()); + (parsed.map(|v| (format!("{}/{}", v["cell"][0], v["cell"][1]), v)).collect(), text.lines().count()) +} + +#[test] +fn a_failed_cell_ends_its_worker_not_the_census_and_a_cell_builds_as_in_the_viewer() { + let out = tempfile::tempdir().unwrap(); + let fail = [format!("{}/{}=panic", ROW[0].x, ROW[0].y), format!("{}/{}=hang", ROW[2].x, ROW[2].y)]; + let run = census(out.path(), &fail); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + let (first, count) = lines(out.path()); + let state = |l: &BTreeMap, k: CellKey| l[&format!("{}/{}", k.x, k.y)]["state"].clone(); + assert_eq!(ROW.map(|k| state(&first, k)), ["panic", "ok", "timeout"], "{first:#?}"); + let panic = &first["34304/23104"]["panic"]; + assert!( + panic["message"].as_str().unwrap().contains("made-up") && panic["at"].as_str().unwrap().contains("worker.rs") + ); + // The viewer's build of the fixture's request: the census reads and builds the cell alike. + let request = fixture::Fixture::open(&fixture::default_dir()).request(ROW[1]).encode(); + let built = build_cell(&request, Rules::embedded(), &mut || 0.0).unwrap(); + assert_eq!(first["34305/23104"]["digest"].as_str(), Some(Flat::of(&built).digest(&built).unwrap().as_str())); + // A driver that died in a line left part of it: the resume ends it, so the next line stays whole. + let mut file = std::fs::OpenOptions::new().append(true).open(out.path().join("census.jsonl")).unwrap(); + file.write_all(br#"{"cell":[34305,2"#).unwrap(); + let run = census(out.path(), &fail); + assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr)); + let (second, total) = lines(out.path()); + assert_eq!(total, count + 2, "the partial line and one retry of the timed-out cell"); + assert_eq!( + (second["34306/23104"]["state"].as_str(), second["34306/23104"]["attempt"].as_u64()), + (Some("timeout"), Some(2)) + ); + assert_eq!(second["34304/23104"], first["34304/23104"], "a panic is the cell's own: no retry"); + // Workers that cannot start stop the run after a few tries. + let gone = tempfile::tempdir().unwrap(); + let run = census(gone.path(), &["start".to_string()]); + let stderr = String::from_utf8_lossy(&run.stderr); + assert!(!run.status.success() && stderr.contains("before their first cell"), "{stderr}"); +} diff --git a/specs/obc-data.md b/specs/obc-data.md index 2c32ac1566..6709e61288 100644 --- a/specs/obc-data.md +++ b/specs/obc-data.md @@ -759,7 +759,8 @@ The `obc data` binary declares each layer beside the steps that make it: | `device/catalog` | `device/catalog` | | `planner/basemap` | `planner/basemap`, `planner/assets` and their grids | | `planner/terrain` | `planner/reference`, `planner/terrain` and its grid | -| `planner/places`, `planner/climate`, `planner/snow`, `planner/trailview-features`, `planner/trailview-rules`, `planner/trailview-colour` | The step of the same name and its grids | +| `planner/places`, `planner/climate`, `planner/snow`, `planner/trailview-rules`, `planner/trailview-colour` | The step of the same name and its grids | +| `planner/trailview-features` | `planner/trailview-features`, `planner/trailview-stamps` and their grids | | `planner/trailview-ground` | `planner/trailview-material`, `planner/trailview-lithology`, `planner/trailview-region`, `planner/trailview-ground` and its grid | | `planner/routing-source`, `planner/routing-roads`, `planner/routing-costs` | The step of the same name. Internal, `cache`. Their files hold router types, so their format is the router `FORMAT` plus 1 | | `planner/routing` | `planner/routing`, `planner/overlays` and their grids | @@ -1213,6 +1214,7 @@ reads their maximum: the blocks `mean/18//.tif` that hold the arch | `planner/climate` | The files of [`climate`](#climate) of the blocks of the outline of the region, as `climate` defines the blocks of a region: the orography and the ten years from `climate.first_year`. A version that lacks one of them refuses | `bounds`, `first_year`, and `attribution` of `era5-land`, whose `{year}` is the year after the ten years, `first_year` + 10; `climate`: the version that it reads | `climate.pmtiles`: [the climate archive](planner-climate-tiles.md). A cell of a block that the step does not read is missing | | `planner/snow` | The files of [`snow`](#snow) of the blocks of the outline of the region, as `snow` defines the blocks of a region, for each season of `snow.seasons`. A version that lacks one of them refuses | `bounds`, `seasons`; `attribution`: the credits of `hr-wsi` when its `extent` meets the bounds, `modis-snow` and `hansen-gfc`; `year`: the year of the `snow` version, which fills the `{year}` of `hr-wsi` | `snow.pmtiles`, `snow-levels.pmtiles` and `snow-seasons.pmtiles`: [the snow archives](planner-snow-tiles.md). A tile of zoom 6 or more of `snow` and `snow-levels`, and of zoom 8 or more of `snow-seasons`, that lies inside the bounds has the same bytes in each region whose step reads its block | | `planner/trailview-features` | `planner/osm`, `planner/terrain/grid`, `water-polygons` | `bounds`; `kinds`: the kind table of `data/trailview/kinds.json`; `roads`: the name, the grade, the smoothing length, the alignment fields and the sidewalk fields (`sidewalk_m`, `sidewalk_steep`, `sidewalk_margin_m`) of each class of `data/trailview/roads.json`, as an array in its order; `waterways`: `width_m`, `cover_m`, `cover_lift_max_m` and `culvert_max_m` of each `waterway` value of `data/trailview/waterways.json`; `attribution` of `osm-planet` | `trailview-features.pmtiles`: [the feature archive](trailview-features.md) at zooms 8 to 13 | +| `planner/trailview-stamps` | `planner/trailview-features` | `bounds`; `attribution` of `osm-planet`; `stamp_sources`: the digest of the files that the stamp code can read, so a change of them bakes the step again | `trailview-stamps.pmtiles`: [the stamp archive](trailview-tiles.md#stamps), made by the TrailView stamp code in Node | | `planner/trailview-rules` | `data/trailview/` of the repository | `ruleset`: the digest of its JSON files by their paths in it. The step fails when the files differ | `rules.json`: [the TrailView rules](trailview-tiles.md#rules); `regions.json`, `materials.json` and `ground.json`: the region ids, the region areas, the ecoregions, the places, the vocabulary and the ground sources that the ground steps read | | `planner/trailview-material` | `materials.json` and `ground.json` of `planner/trailview-rules`; `lithology.pmtiles` of `planner/trailview-lithology`; each [material source](trailview-tiles.md#ground-sources) that meets the bounds: `osm.pbf` of `planner/osm` for `osm-planet`; `esa-worldcover`, `tile=` of each 3° tile that the bounds touch and that `esa-worldcover-grid` lists; the files of [`colour`](#colour) of `trailview.colour_year` of the blocks that the outline of the region meets, for `colour`. A version that lacks one of them refuses; a `capture` source with `bbox=`, another without params | `layer`: `material`; `bounds`; `year`: `trailview.colour_year` | `material.pmtiles`: the material bytes and the barren shares of [the ground](trailview-tiles.md#ground) | | `planner/trailview-lithology` | `materials.json` and `ground.json` of `planner/trailview-rules`; each lithology source that meets the bounds, as for the material | `layer`: `lithology`; `bounds` | `lithology.pmtiles`: the lithology bytes | @@ -1222,8 +1224,8 @@ reads their maximum: the blocks `mean/18//.tif` that hold the arch | `planner/trailview-canopy` | The blocks of [`forest`](#forest) that the outline of the region meets, as `forest` defines them. A version that lacks one of those blocks refuses | `bounds`; `attribution`: the credits of the canopy models with a tile in those blocks and of the leaf type | `trailview-canopy.pmtiles`: [the canopy archive](trailview-tiles.md#canopy) | Each map producer has a `planner//grid` step, where `` is `basemap`, `places`, -`terrain`, `overlays`, `climate`, `trailview-features`, `trailview-ground` or -`trailview-canopy`. It reads only the archive of its producer. +`terrain`, `overlays`, `climate`, `trailview-features`, `trailview-stamps`, +`trailview-ground` or `trailview-canopy`. It reads only the archive of its producer. `planner/trailview-colour//grid` reads one archive of the colour step, as the kind `trailview-colour-`. `planner/snow//grid` reads one archive of the snow step, as the kind `snow`, `snow-levels` or `snow-seasons`. It converts terrain MBTiles with the pinned Python @@ -1245,6 +1247,7 @@ The parts of the planner are `map`, `routing`, `search`, `climate`, `snow`, part that is on makes it or reads it: `map` makes the basemap, places, assets and terrain grids, `routing` the routing and overlays grids, `search` the model and the two search grids; the other parts make their own steps. The fonts, the offline grid, the index and the catalog read only the grids that stay. +`trailview-features` makes the stamps step too. `trailview-ground` makes the material, lithology and region steps, and needs `trailview-rules`. All producers are intermediate layers. Grid steps select their `objects/` and their `index.json`. diff --git a/specs/trailview-features.md b/specs/trailview-features.md index 405f49f83c..aa8154cdea 100644 --- a/specs/trailview-features.md +++ b/specs/trailview-features.md @@ -8,11 +8,11 @@ the features and the tags that the tiles keep. - Writers: the bake `host/obc-trailview-features`. Its step reads the OSM of `planner/osm` and the master terrain of the grid of `planner/terrain` in the same release, and the water polygons of the source `water-polygons`. -- Readers: the TrailView engine (`builder/web/src/lib/trailview/stream/features.ts`), - `tools/planner_verify.py`. +- Readers: the TrailView engine (`builder/web/src/lib/trailview/stream/features.ts`), the ground + plan (`host/obc-ground-plan/src/tile.rs`), `tools/planner_verify.py`. - Test vectors: [`vectors/trailview-features.json`](vectors/trailview-features.json) and [`vectors/trailview-features.bin`](vectors/trailview-features.bin): one tile in its decoded form - and its bytes. The encoder of the bake and the two decoders of the readers read both. + and its bytes. The encoder of the bake and the decoders of the readers read both. - Related: [obc-data.md](obc-data.md), [TrailView tiles](trailview-tiles.md). ## Archive @@ -40,7 +40,9 @@ nearer the pole, so it is at least `buffer_m` at every point of the tile. 40 m h and fill cone of a road up to 30 m wide, which reaches 25 m past the road edge. The cut makes no vertex. A piece of a line keeps the segments that meet the buffered square whole, -and one more vertex at each end, so that both tiles know the bend at each end of such a segment. +and one more vertex at each end, so that both tiles know the bend at each end of such a segment. A +piece of a `river` or a `stream` keeps two more vertices at each end: the curve that the ground plan +draws through a span of water reads two vertices on each side of it. A ring keeps each edge that crosses a side of the square whole, and joins the vertices outside the side directly. Such a join lies outside the square. Thus inside the buffered square, the tiles that hold a feature hold the same vertices and edges, and a stamp near a tile edge gets @@ -131,42 +133,77 @@ grade and a smoothing length. A track is a way with a `railway` of `rail`, `narr `light_rail` or `funicular` and no `highway`. The class of a track is its `railway`, or `rack` when it has a `rack` tag other than `no`; the class of another way is its `highway`. The table lists the tracks first, so at a level crossing the road meets the track. The options of the step hold the -grade, the smoothing length and the fields of the alignment (see Alignment) of each class, in the -order of the table. The other fields of the table are the stamp profile of the engine. They are not -options of the step, so a change to them does not bake the features again. The road solver: +grade, the smoothing length, the half-width, the shoulder and the fields of the alignment (see +Alignment) of each class, in the order of the table, and the half-width and the shoulder of each +finish of [`data/trailview/finishes.json`](../data/trailview/finishes.json). The other fields of the +table are the stamp profile and the cross-section of the engine. They are not options of the step, +so a change to them does not bake the features again. + +Half-widths: the half-width of a way is that of its carriageway: for a way that is not a track, +half its `width` (the number at the start of the tag, at least 0.4 m) where it has one; else +`half_m` of its class, at most `half_m` of its finish; at most 15 m. Its outer half-width adds the +wider of its shoulder (`shoulder_m` of its class, at most that of its finish) and `sidewalk_m` of +its class. The finish of a way is `Finish::of` of `host/obc-ground-plan/src/sections.rs`, with no +town. The engine reads the same rules. A bridge is a way with a `bridge` tag other than `no`, +`boardwalk` and `low_water_crossing`. + +The road solver: - samples the master terrain every 2 m along each way, - fits a smooth height line to the samples, with weights that let a spike or a gully of the terrain go, so that it does not move the road, +- holds each vertex of a way on the ground within 5 m of the terrain across the way at each sample: + of the range from the lowest to the highest terrain at the sample and at ± the half-width of the + way, square to it. On a slope the terrain under the centre line is not the bed of the road. Past + 5 m the bound gives way to the other limits, and past 8 m only to the pins of the approaches, the + fords and the ways side by side, which cost as much, so a segment can pass the grade of its class + there. A sample of a segment that ends where a bridge runs through has no bound: steps or a ramp + that meet a deck there take its height. The end of a bridge that meets no way or a tunnel (a + portal) stands on the terrain the same way, - holds each segment within the grade of its class on the line of OSM, but not the approach of a - side road, so that a side road does not move the through road. The fit of the plan can shorten the - tip of a hairpin, and the heights stay, so the curve can pass the grade there, + side road where the through roads give it its heights: on the surface of the through road, or on + a link that is a side road at both of its junctions, past any junction where it runs through. So + a side road does not move the through road. The fit of the plan can shorten the tip of a hairpin, + and the heights stay, so the curve can pass the grade there. A tunnel between two portals holds the + grade of its class too, or 1:1 for a class without one, so a road that crosses it near a portal + does not dig a step into it; but never less than the terrain's rise from portal to portal over its + length, so the grade does not pull a portal off the terrain. A side tunnel or a shaft that ends on + another tunnel has the grade that its ends give it, so it never lifts that tunnel. A tunnel that + branches inside the mountain holds the grade only on its straightest line from portal to portal, +- holds a way of a class without a grade, where it leaves a road of a class with one, as a ramp: + for 15 m from the junction, where no pin of the approach holds it, its grade differs from the + terrain's under it by at most 25 %. The ramps are solved last, with every other height fixed, so a + ramp bends its way and moves no road and no junction. Over unknown terrain, a way has no ramp, - gives ways that share a vertex one height there, and puts the first 4 m of a side road on the surface of the through road of a junction (1.5 m where paths meet), but not past the middle of a way between two junctions. The through road is the first class of the table at the junction, and of two ways of that class, the pair that runs most nearly straight on, -- puts each vertex of a track on the ground at the height of the nearest track on the ground that - runs the same way within 6 m beside it, so that the tracks of a double line lie at one height. A - track follows only a track after it in the bake's order. A vertex keeps its own height where the - terrain under the two tracks differs by more than 0.5 m, there or within 100 m along its way: a - ramp or a flyover, -- ignores the terrain under a bridge and in a tunnel: these run between their ends. A tunnel runs in +- puts each vertex of a way on the ground at the height of the nearest way on the ground of the same + layer that runs the same way beside it, not past the first or the last vertex of that way: a track + within 6 m of a track, so that the tracks of a double line lie at one height, and a road or path + where its carriageway overlaps that of another road or path, so that the two have one surface. A way follows only a way after it in the bake's + order. A vertex keeps its own height where the terrain under the two ways differs by more than + 0.5 m, there or within 100 m along its way: a ramp or a flyover, +- ignores the terrain under a bridge and in a tunnel: these run between their ends. A tunnel keeps to a straight line between the two ends of its chain of tunnel ways that meet end to end, so a side - tunnel or a shaft that joins it follows it and does not lift it. A tunnel chain with an end that + tunnel or a shaft that joins it follows it and does not lift it. The line weighs less than the + ground: the ground at a portal and the limits along the tunnel bend it. A way on the ground that + meets a tunnel ends its chain there: a portal, on the ground. A tunnel chain with an end that meets no way runs level from its other end, or on the grade of the road that runs on into it there. A bridge never sags under the straight line between the two ends of its chain of bridge ways, - raises a bridge that is not a culvert where it crosses a waterway, or a road, a path or a track on the ground that it does not meet: its road lies at least 1.5 m (water), 4.5 m (road), 2.5 m (path) or 6 m (track) over it, plus a deck of 1 m, or 0.4 m for a path. The way below may sink to give - the room. A bridge whose end lies on the road that it crosses, within that road's half-width, - meets it there and does not rise, + the room. A bridge whose end lies on the road that it crosses, within that road's outer + half-width, meets it there and does not rise, - lets a bridge rise from where it lands at a height that it cannot move no more steeply than 1:1: - an end that meets no other way stands on the terrain, and an end that leaves a junction as a side - lies on the through road. A crossing that asks more lies where the bridge lands and does not raise + an end that meets no other way or a tunnel stands on the terrain, and an end that leaves a junction + as a side lies on the through road. A crossing that asks more lies where the bridge lands and does not raise it, - sinks a tunnel where a road, a path or a track crosses over it without meeting it: the tunnel's - road lies at least its bore and 1 m under that road's middle and both its edges. A road on the + road lies at least its bore and 1 m under that road's middle and both its edges, each on the + segment of the tunnel under it. A road on the ground over a tunnel does not move, - passes one way over the other where two bridges cross that no bridge joins or that both tag a different `layer`, and where two ways on the ground with a different `layer` cross, without @@ -175,8 +212,13 @@ options of the step, so a change to them does not bake the features again. The r Both ways may move to give the room. A way on the ground of a negative `layer` without a `tunnel` tag, such as a corridor of a station, runs under something that the solver leaves out: no way on the ground passes over or under it, -- puts a vertex that a road shares with a river or a stream, and the crossing of a way tagged `ford` - with a waterway, 0.2 m below the water, +- puts a vertex that a road or a path shares with a river or a stream, where each passes through it + or meets another part of its own there (only open water counts: a culvert part that starts there + makes no ford), and the crossing of a way tagged `ford` or + `bridge=low_water_crossing` with a waterway, 0.2 m below the water. A road or a track does so only + over water wider than `culvert_width_m`: over narrower water it takes the culvert's cover below, + tagged as a ford or not. A path tagged + `ford=stepping_stones` is no ford and gets no such vertex: it keeps its height, - lifts a road or a track on the ground where it crosses a culvert (see below), so that it lies at least `cover_m` of the waterway's kind in `data/trailview/waterways.json` over the water there. The water of a culvert (see below) lies on the straight line between the levels of the waterways @@ -184,8 +226,28 @@ options of the step, so a change to them does not bake the features again. The r crossing whose water lies over the terrain there, have no cover: those levels are not the pipe's, which runs under the ground. Nor has a crossing where the cover would lift the way by more than - `cover_lift_max_m` of the kind over its height after the first solve. The crossing holds its - height from the second solve on. A path keeps its height. + `cover_lift_max_m` of the kind over its height after the first solve. A path keeps its height. It also lifts a road, a track or a + railway on the ground, tagged as a ford or not, where it crosses a river or a stream no wider than + `culvert_width_m` of its kind at 20° or more, unless a ford of that way lies within + `(cover_m + 0.2 m) / grade` of its class, along the way. A way of a negative `layer` without a + `tunnel` tag (see below) and water tagged `bridge` have no such crossing. Where one ends on the + other, there is no crossing, and a point that both pass through gives one crossing, whatever + number of parts meet there. The rules of the water over the terrain and of `cover_lift_max_m` + hold for these crossings too: where the lift would pass the most, the way keeps its height. + +The grades, the ground, the decks, the sags, the covers and the passes are limits. The solve seeks +the minimum of the fit plus, per limit, a cost times the square of its distance past its band, so a +limit only pushes, and only where the heights pass it. Its rounds stop where no vertex alone would +move by 1 cm, which on a long stiff deck can leave the heights metres from that minimum. The ground past 5 m costs the least, the other +limits 100 times more, and the ground past 8 m 100 times more again. A first solve without limits +gives the weights of the fit, the culverts and the covers that hold; the ramps act after the rest. + +The bake fails when a vertex of a way on the ground (not a bridge and not a tunnel, and not where a +deck runs through it) lies more than 10 m past the terrain across its way, the range of the ground +bound above: the owner's gate; the message names the worst places. Its metrics hold this census, and +the same one of the rivers and streams, which does not fail the bake. The bake log and the metrics +also count the places (one per position, where several ways share a vertex) more than 10 m off the +terrain under their centre line, which the gate does not. The road solver works by area: an area is a tile of zoom 10. The solve of an area holds each way within 500 m of the area, along the ways from the nearest vertex of OSM of a way in a straight line. @@ -207,11 +269,13 @@ its parts meet end to end, and stops where open water has a level. A longer chai stream: it has no cover, and the roads over it keep their heights. A culvert is also a bridge shorter than 8 m whose deck lies no more than 1 m above the terrain after the first solve. The tiles keep such a bridge without its `bridge` tag, as a road on the ground, and it holds the cover over the water that it crosses. A tunnel whose terrain lies less -than its bore (5 m, 2.6 m for a path, 6.5 m for a track) over it everywhere runs under something -that the terrain leaves out, such as a building: the tiles keep it without its `tunnel` tag, as a -way of its class. A `building_passage` and a tunnel under a road, a path or a track stay tunnels. +than its bore (5 m, 2.6 m for a path, 6.5 m for a track) over it everywhere, and that rises nowhere +more than 5 m over the terrain, runs under something that the terrain leaves out, such as a +building: the tiles keep it as a way of its class, with its `tunnel` tag. A tunnel under a road, +a path or a track stays a tunnel. The tiles leave out a part of a tunnel that rises more than 5 m over the terrain anywhere farther -than 20 m from its ends. +than 20 m from its ends, tested every 2 m. A shorter tunnel part, with no such sample, is left +out where it rises more than 10 m over the terrain anywhere. ### Alignment @@ -316,13 +380,16 @@ A way is paved when it has no `surface` tag or one other than `gravel`, `compact 3. A gap under 40 m along the stroke between two such pieces closes, where no tag decides it. 4. A side has no sidewalk where the ground from 2 m to 6 m past the road's edge rises or falls by more than `sidewalk_steep` of the class per metre, unless a tag puts one there. The road's edge - lies its half-width (see Structures) and its widening from its middle. + lies its half-width (see Heights) and its widening from its middle. 5. A side has no sidewalk inside a bend whose radius is less than the road's edge, the sidewalk's width and `sidewalk_margin_m` of the class. 6. A side has no sidewalk where its middle lies on the bed of another way on the ground or of a river or a stream: within that way's half-width and half the sidewalk's width. A way that meets the road does not count within 12 m of their junction, and a waterway's bed does not - count within that distance of a vertex that it shares with a culvert part: the pipe runs on. + count within that distance of a vertex that it shares with a culvert part, or where the water + lies under a road or a track that crosses it on a culvert by the rule of Heights and holds its + cover there: within the road's outer half-width, its widening and the bed's half-width, over + the sine of their angle, along the water from the crossing. The pipe runs on. 7. A piece that ends within 15 m of a junction, a point that three segments of ways or more leave, runs on to it where rules 4 to 6 let it. 8. A piece under 50 m goes, after rules 1 to 7 have decided every way of the solve. A piece is a @@ -350,6 +417,32 @@ The bake adds these to the features of the road solver: | point `bridge-pier` | each pier of a bridge | Its height is the bridge's road there, on the curve of its deck (see Alignment). Its kind has the `min_zoom` of its bridge | | tag `stations` | each `aerialway` with an end that has no station of its own | `start`, `end` or `none`: the ends that have one | | point `catenary-mast` | each mast of the contact wire of a `railway` tagged `electrified` `contact_line` or `yes`, but not a funicular | Its height is its track's rail there. Tag `on` `deck` on a bridge | +| tag `levels` | each way of the road solver with a state (see below), at zoom 13 | `S` then `m K S` per end line: the state where the way's metres along begin, then per end line in rising metres its metres along, its kind (`A` a deck's end, `P` a portal, `C` a closed end) and the state past it. A state is `D` on a deck, `B` in a bore, `O` on the ground, `H` not drawn | +| tag `storey` | each way of a deck that lies over another deck, at zoom 13 | Its storey over the ground, 2 or more. A deck without the tag lies on storey 1 | +| tag `slab` | each way of a deck whose room gives less than its full depth (ladder step 2), at zoom 13 | The depth of its slab in metres | + +The bake decides `levels`, `storey` and `slab` by the levels of the ground plan (`graph::levels` of +`host/obc-ground-plan`, and `graph::level_tags` for the tags) with the rule tables of its own build. The options +of the step hold the rule values that the levels read (`level_rows` of `kinds.rs`: the graph's fields of each +class and waterway kind, and the `structures` of `plan.json`), so a change of them bakes the layer again; a change +of the code of the levels takes a new revision. The bake builds each zoom-16 cell of each zoom-13 tile that holds a +way of the road solver as the viewer does: from the zoom-13 tiles of the bake and the terrain tiles of zooms 13 and +12 of the grid. Each cell decides the ways inside its square. A way has a state where it is a bridge or a tunnel, or +where it ends at the body of a way that it crosses. A station of a tunnel is `B` where the ground over it gives +the least room of its class (`bore_least_m` and `roof_least_m`, less `lift_max_m` where no paved way lies on that +ground). Else it is `O` within `open_max_m` (30 m) of a tag end and before the first `B` from its nearer tag end, +also where its floor lies over the terrain (the way goes on as a way on the ground until the cover holds), but `H` +where a paved way lies on top of it: more than the lower `snap_height_m` of the two ways over its floor. Else it is +`H`. The A lines of one deck group that cross or lie within +`edge_band_m` of each other move in together: each A moves in along its way to where its centre line meets the line +normal to their mean direction into the decks through the farthest one in, and each end line stays square to its own +way. One pass merges them; a cell merges the A lines that it sees. The storey is one per deck group, the deck ways that share a +point, joined over all cells: 1, and one more than each group under it at a crossing that a cell owns and whose +ladder gives a deck (full or thin). A crossing of a group over itself lifts nothing. The metres along of a way are +those of its stroke (see Alignment): `along_code` at the first vertex of each part, and the length of the ground +plan's curve of each span (`graph::curve`) from there, in the tile that owns the span. Every zoom-13 copy of a way +holds the lines of the whole way. Two lines at one metre come in the order A, portal, closed. A number is the +shortest decimal that gives the same 64-bit float. A way with a part that has no alignment has none of these tags. The masts of a track stand evenly along each of its ways, at most 50 m apart, 3 m beside its middle, or 2.5 m for a narrow gauge (`gauge` below 1200 mm, else `narrow_gauge` and `funicular`). On a @@ -367,9 +460,7 @@ spans of at most 45 m, or 30 m for a path. A pier that falls in water which the less than 30 m moves 2 m past the nearer bank of it, and one that falls on a road, a path or a tunnel moves 2 m past its nearer side; one that comes within 6 m of another pier or of an end goes. Water is a waterway within its half-width and 1 m, a river area or a lake. A road is its line within -1 m and its half-width: half its `width` (at least 0.4 m), else 6 m for a main road, 3 m for a road -or a `pedestrian` way, 1.5 m for a `cycleway`, 0.6 m for a `via_ferrata` and 1 m for another path. A -cable bridge has no piers. +1 m and its outer half-width (see Heights). A cable bridge has no piers. Each vertex of an `aerialway` between its ends is a pylon. A way splits at each vertex where another `aerialway` ends: there is a mid-station. Where a span is longer than its rig allows, or where a @@ -384,24 +475,44 @@ A `building` in an area `landuse=industrial` or `landuse=farmyard` has the tag ` area: of the smallest such area that holds the mean of the vertices of its first outer ring. The tiles do not hold these areas. -A `building` has the tag `use`, `pharmacy`, `hospital` or `shop`, when it, a node that lies inside -or on its first outer ring, or an area that holds the mean of that ring's vertices has that use. -`amenity` or `healthcare` `pharmacy` is a pharmacy, `amenity` or `healthcare` `hospital` a hospital, -and any `shop` a shop. Of several uses, the first in that order wins. The tiles do not hold these -nodes and areas. - Each vertex of a `river` or `stream` that is not in a tunnel has a water level, never higher than a vertex before it: the vertices run in the direction of the flow. OSM draws a waterway that way; the -bake turns a way whose terrain rises by more than 5 m from end to end. The level is the fit that -never rises (pool-adjacent violators) to the lowest terrain within ±(w/2 + 2 m) across the line, -every 5 m, with a fall of at least 0.05 % in a pool, smoothed over ±25 m. The width w of a waterway -is its `width` tag, else `width_m` of its `waterway` value in `data/trailview/waterways.json`, and its -half-width is half of w. The smoothing does not -cross a `waterfall`, a `dam` or a `dam-point`. Waterways that share a vertex are one network: a +bake turns a way whose terrain rises by more than 5 m from end to end. The level comes from the +terrain at the waterway's own line, every 5 m: the highest level that never rises downstream and lies +under the lowest terrain within ±(w/2 + 2 m) across the line and at least `freeboard_m` of the kind +under the lower terrain at ±(w/2 + `bank_m`), so that the water lies in a channel under its banks. +Where the terrain is unknown, a sample takes the level before it. Between two vertices of the OSM way, +the bake adds vertices at samples until both drawn levels between the kept vertices lie within 0.2 m +of the level of every sample, so the level holds along the line and not only at the vertices of the map. +In each round, each span between two kept vertices where a drawn level lies more than 0.2 m off a +sample keeps its farthest sample. An added vertex lies on the curve of its span +that the ground plan draws through the vertices of the map, at the sample's share of the span along the +chords of the map, taken as a share of the curve's length. The drawn level is read on the curve that the +ground plan draws through the kept vertices: a span of that curve of length L (metres along the curve) +has at share t of its length the cubic Hermite of the levels z0, z1 and the grades g0, g1 of its +vertices: z0·(2t³ − 3t² + 1) + L·g0·(t³ − 2t² + t) + z1·(3t² − 2t³) + L·g1·(t³ − t²); a reader +without the ground plan draws the straight level z0 + t·(z1 − z0) at the same t. The grade at a +vertex is the harmonic mean of the grades of its two chords where they fall the same way, else 0, and at +an end of the way or beside an unknown level its one chord's. A sample reads the level at the point of +that curve nearest to its own point. The curve of a span is the cubic Hermite whose tangents are the +bisectors of the unit chords at each vertex, and the chord at an end of the way; the chord where a vertex +turns by more than `curve_turn_max_deg`, where the curve leaves the chord by more than `curve_off_max_m` +of the kind in `data/trailview/waterways.json`, or where it folds back. A curve beside a chord takes that +chord's direction at their shared vertex, and its tangents shorten until it leaves its chord by at most +`curve_off_max_m`. The bake works on the points and levels before the tiles round them to tile units and +centimetres. The rules of the ways at water (fords, covers, culverts) read the +levels at the vertices of the map and the straight line between them: at a crossing between two of +them, that level can lie off the level of the tiles. Near a junction, within the bank +top's distance of the widest waterway there, the bank tops lie in the other waterway's bed and do +not count. A pit on the line lowers the level there and after it, until the terrain falls under it. +The width w of a waterway is its `width` tag where it is above 0, else `width_m` of its `waterway` +value in `data/trailview/waterways.json`, and its half-width is half of w. Waterways that share a vertex are one network: a level never rises through a junction, and the waterways at a junction have one level there. In a loop of waterways, the waterways go from the highest start down, and one that flows back into a junction before it ends below that junction's level. A point in a lake, or within 2 m of its shore, -holds the lake's level. +holds the lake's level, but not the points that a waterway starts with there: water that flows out +of a lake, over a dam or a sill, takes its own levels. A waterway never goes under a lake that it +flows into. Each vertex of a `lake` has one level. It is the median of the terrain inside the lake when 80 % of that terrain lies within 0.3 m of it; else the 15th percentile of the terrain 2 m inside the shore. @@ -444,7 +555,9 @@ and a selector that matches its tags. An object that no entry takes is not in th The bake validates the table before it reads OSM, and a test of `host/obc-trailview-features` validates the committed table. A `path` keeps `sac_scale` and `surface`: a reader takes the look of -steps from them. The table is part of the options of the step, so a change to it +steps from them. A `road` keeps `service`, and a `main-road`, a `road` and a `path` keep `lit`: a +reader tells a driveway from them and lights a way. A kind needs no engine module: `street-lamp` +and `level-crossing` are for the ground plan's placement. The table is part of the options of the step, so a change to it bakes the layer again. ### Add a kind diff --git a/specs/trailview-tiles.md b/specs/trailview-tiles.md index e10f5bf2f9..768ec69da7 100644 --- a/specs/trailview-tiles.md +++ b/specs/trailview-tiles.md @@ -2,12 +2,13 @@ The raster layers of the planner release that TrailView reads: the ground, the colour and the canopy of each texel or cell, and the ruleset that the ground indexes. TrailView reads the snow of -a date from `snow` of [the planner snow tiles](planner-snow-tiles.md). +a date from `snow` of [the planner snow tiles](planner-snow-tiles.md). The stamp layer holds what +the stamp worker makes of the feature tiles for some terrain nodes. - Version: `trailview_format` 3 (ground) and 2 (colour); `canopy_format` 1; `format` 3 - of `rules.json`. A reader reads only the format that it knows. + of `rules.json`; `stamp_version` of the stamp layer. A reader reads only the format that it knows. - Writers: `tools/trailview/rules.py`, `tools/trailview/ground.py`, `tools/trailview/colour.py`, - `tools/planner_trailview_canopy.py`. + `tools/planner_trailview_canopy.py`, `host/obc-trailview-features/src/stamps.rs`. - Readers: the TrailView engine (`builder/web/src/lib/trailview/`), `tools/planner_verify.py`. - Related: the optional planner layers `trailview-*` of [obc-data.md](obc-data.md), [the planner snow tiles](planner-snow-tiles.md), [TrailView feature tiles](trailview-features.md). @@ -288,3 +289,58 @@ bits are never 15. The leaf type comes from the conifer share of the cell: 25 % or less is broadleaved, 75 % or more is coniferous, and a share in between is mixed. A cell without a share is unknown. + +## Stamps + +`trailview-stamps` holds, for each terrain node of zooms 9 to 12, the whole result that the stamp +worker (`builder/web/src/lib/trailview/terrain/stamp-worker.ts`) posts for it with the ground plan, +and for each node of zoom 15 its structure meshes. Its bake runs the stamp code of the viewer in +Node on each tile of `trailview-features`, so a node is equal to what the worker makes of the same +feature tile. + +| Field | Value | +| --- | --- | +| Format | PMTiles v3 | +| Tiles | Web Mercator XYZ: tile z/x/y is terrain node z/x/y at zooms 9 to 12 and 15, and the mask of feature tile z/x/y at zoom 13 | +| Tile type | `unknown` (0) | +| Tile compression | gzip | +| Bounds | The region bounds | + +The archive holds each node of zooms 9 to 12 whose feature tile `trailview-features` holds. At zoom +13 it holds, for each zoom 13 feature tile, a u16 little-endian mask of its 16 nodes of zoom 15: bit +(x mod 4) + 4 × (y mod 4) is set when the archive holds node 15/x/y. It holds only the nodes of +zoom 15 that have a structure mesh; the structure meshes of the others are `EMPTY_MESHES` of +`node-bytes.ts`. A node that the archive does not hold, or whose bytes do not decode, the viewer +makes in the stamp worker. The release packs the archive in [map +packs](planner-offline.md#grid-publication-and-selection): +`maps/tiles/trailview-stamps/--.pmtiles`, with the TileJSON `maps/trailview-stamps.json`. + +| Metadata | Value | +| --- | --- | +| `stamp_version` | 16 lowercase hex digits: the start of the SHA-256 of the bake module, which `builder/web/vite/stamp-bundle.ts` makes of the stamp code and the tables that it reads | +| `attribution` | Text to show with the layer | +| `bounds` | The region bounds | + +A viewer reads the nodes only when `stamp_version` is the version of its own stamp code. + +The bytes of a node (`builder/web/src/lib/trailview/terrain/node-bytes.ts`) are, in this order: + +| Bytes | Value | +| --- | --- | +| 4 | The length n of the JSON, u32 little-endian | +| n | UTF-8 JSON of the value. A binary value is an object `{"$": tag, "at": offset, "n": bytes}`; the tag is `ArrayBuffer`, `Uint8Array`, `Uint16Array`, `Uint32Array`, `Int32Array`, `Float32Array` or `Float64Array` | +| 0–7 | Zero bytes to a multiple of 8 | +| rest | The binary values, little-endian, each at its `at` from the start of this part, which is a multiple of 8 | + +In the value, each water mesh (zooms 9 to 12) and each structure and anchored mesh (zoom 15) is the +object `{"$mesh": packed, ...}`: the other keys of the mesh follow, in their order, and `vertices` +and `indices` come first again when the viewer unpacks it. `packed` holds: + +| Key | Value | +| --- | --- | +| `n` | The number of vertices | +| `w`, `s` | The number of distinct vertices, in the order of their first use, and the bytes of each in `v` | +| `xy` | Null, or a world point: then the first two int32 of each vertex are int16 from that point in `v` | +| `v` | The distinct vertices, coded with `encodeVertexBuffer` of meshoptimizer | +| `r` | Null when `w` is `n`; else, for each vertex, its distinct vertex, coded with `encodeIndexSequence` (4 bytes) | +| `ni`, `i` | The number of indices, and the indices, coded with `encodeIndexSequence` (4 bytes) | diff --git a/tools/ci/test.sh b/tools/ci/test.sh index e2cdb00b53..8df3fdfbd3 100644 --- a/tools/ci/test.sh +++ b/tools/ci/test.sh @@ -17,10 +17,13 @@ set -euo pipefail cd "$(dirname "$0")/../.." +# CI sets OBC_SELECTED_SUITES to the plan's suites; unset or empty, the targets of every suite run. +# `--tests` leaves the examples out: no test runs one, and clippy --all-targets compiles them. nextest_fast() { export NEXTEST_PROFILE=ci rm -f target/nextest/ci/junit.xml - cargo nextest run --workspace --all-features --locked --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fast)" + # shellcheck disable=SC2086 # suite IDs hold no spaces + cargo nextest run --workspace --all-features --locked --tests --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fast ${OBC_SELECTED_SUITES:+--suites $OBC_SELECTED_SUITES})" } nextest_fixtures() { @@ -29,7 +32,7 @@ nextest_fixtures() { python3 tools/fixtures.py sync test OBC_FIXTURE_ROOT="$(python3 tools/fixtures.py root)" export OBC_FIXTURE_ROOT - cargo nextest run --workspace --all-features --locked --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fixtures)" + cargo nextest run --workspace --all-features --locked --tests --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fixtures)" } # nextest runs no doctests, so they run here rather than falling out of the gate. diff --git a/tools/dev_cleanup.py b/tools/dev_cleanup.py index 7a84143a16..3d66cceeb1 100644 --- a/tools/dev_cleanup.py +++ b/tools/dev_cleanup.py @@ -6,6 +6,7 @@ import argparse import contextlib import fcntl +import hashlib import os import re import shutil @@ -152,13 +153,16 @@ def temp_candidates( def cargo_target(value: str | None) -> Path | None: if not value: return None - target = Path(value).resolve() + own = target = Path(value).resolve() + # Under `obc` the value is the target of this checkout (tools/obc-dev.sh); prune the shared one. + if own.parent.name == "checkouts" and UNIT_HASH.fullmatch(own.name): + target = own.parent.parent if not target.is_dir(): return None if target in (Path("/"), Path.home().resolve()) or (target / ".git").exists(): raise CleanupError(f"refusing to prune CARGO_TARGET_DIR={target}") # Cargo writes this tag; without it the globs below could match a real project folder. - if not (target / "CACHEDIR.TAG").is_file(): + if not any((path / "CACHEDIR.TAG").is_file() for path in (target, own)): print(f"warning: CARGO_TARGET_DIR={target} has no CACHEDIR.TAG; not pruning it") return None return target @@ -221,8 +225,18 @@ def build_lock(lock: Path, apply: bool) -> Iterator[bool]: os.close(fd) +def checkout_key(checkout: Path) -> str: + """The name of a checkout's own target in `checkouts/`, as `obc_checkout_target` makes it.""" + return hashlib.sha256(str(checkout).encode()).hexdigest()[:16] + + +def profile_locks(root: Path) -> list[Path]: + # Cargo creates `.cargo-lock` before it writes a profile; a dir without one is not a profile. + return sorted([*root.glob("*/.cargo-lock"), *root.glob("*/*/.cargo-lock")]) + + def prune_cargo_target( - target: Path, cutoff: float, apply: bool + target: Path, cutoff: float, apply: bool, live: set[Path] ) -> tuple[dict[Path, tuple[int, int]], list[Path]]: """Return ({artifact dir: (entries, bytes)} unused since cutoff, busy profiles). @@ -230,11 +244,38 @@ def prune_cargo_target( fingerprint on every build that includes the unit but only stats the other outputs, so the fingerprint dates the whole unit, and the unit goes whole: a lost part rebuilds the unit and everything downstream. An incremental crate dir is dated by its newest file. + + `checkouts//` is the target of one checkout. It goes whole, under the locks of its + profiles, once it is unused since cutoff and no worktree of `live` has its key. """ pruned: dict[Path, tuple[int, int]] = {} busy: list[Path] = [] - # Cargo creates `.cargo-lock` before it writes a profile; a dir without one is not a profile. - for lock in sorted([*target.glob("*/.cargo-lock"), *target.glob("*/*/.cargo-lock")]): + keys = {checkout_key(path) for path in live} + checkouts = target / "checkouts" + owns = sorted(checkouts.iterdir()) if checkouts.is_dir() and not checkouts.is_symlink() else [] + gone: list[Path] = [] + for own in owns: + if own.name in keys or own.is_symlink() or not own.is_dir(): + continue + try: + used, size = last_use(own) + except OSError: + continue + if used > cutoff: + continue + with contextlib.ExitStack() as stack: + if not all(stack.enter_context(build_lock(lock, apply)) for lock in profile_locks(own)): + busy.append(own) + continue + if apply: + try: + remove_path(own) + except OSError: + continue + pruned[own] = (1, size) + gone.append(own) + kept = (lock for own in owns if own not in gone and not own.is_symlink() for lock in profile_locks(own)) + for lock in sorted([*profile_locks(target), *kept]): profile = lock.parent fingerprints = profile / ".fingerprint" # A symlink anywhere in the path could lead out of the target. @@ -304,7 +345,8 @@ def main(argv: list[str] | None = None) -> int: repo = (args.repo or Path.cwd()).resolve() root = Path(tempfile.gettempdir()).resolve() - scratch = temp_candidates(time.time(), args.days, root, registered_worktrees(repo)) + worktrees = registered_worktrees(repo) + scratch = temp_candidates(time.time(), args.days, root, worktrees) sizes = directory_sizes(scratch) print(f"OBC test scratch cleanup ({'APPLY' if args.apply else 'DRY RUN'})") print(f"age>={args.days}d temp={root}") @@ -312,13 +354,18 @@ def main(argv: list[str] | None = None) -> int: print(f" REMOVE {format_size(sizes.get(path, 0)):>10} {path}") target = cargo_target(os.environ.get("CARGO_TARGET_DIR")) cutoff = time.time() - args.days * SECONDS_PER_DAY - artifacts, busy = prune_cargo_target(target, cutoff, args.apply) if target else ({}, []) + artifacts, busy = prune_cargo_target(target, cutoff, args.apply, worktrees) if target else ({}, []) if target: print(f"cargo target={target}") for path, (entries, size) in artifacts.items(): print(f" REMOVE {format_size(size):>10} {entries} entries in {path}") for profile in busy: print(f" SKIP {profile}: cargo holds its lock") + cache = Path(os.environ.get("SCCACHE_DIR", "")) + if cache.name and cache.is_dir(): + size = directory_sizes([cache]).get(cache, 0) + limit = os.environ.get("SCCACHE_CACHE_SIZE") or "10G" + print(f"sccache={cache}: {format_size(size)}; sccache keeps it below {limit} itself") # An upper bound: a hard link outside the removed entries keeps its inode. reclaimable = sum(sizes.values()) + sum(size for _, size in artifacts.values()) print(f"Potentially reclaimable: up to {format_size(reclaimable)}") diff --git a/tools/justfile b/tools/justfile index 694129c3db..1df2269378 100644 --- a/tools/justfile +++ b/tools/justfile @@ -201,7 +201,7 @@ debug *args: set -euo pipefail source "{{lib}}"; obc_init; ensure_riscv || exit 1; ensure_probe || exit 1 gpx="${1:-}" - elf="$OBC_ROOT/firmware/obc-fw-nrf54l/target/thumbv8m.main-none-eabihf/release/obc-fw-nrf54l" + elf="${CARGO_TARGET_DIR:-$OBC_ROOT/firmware/obc-fw-nrf54l/target}/thumbv8m.main-none-eabihf/release/obc-fw-nrf54l" _say "building debug-uart firmware…" ( cd "$OBC_ROOT/firmware/obc-fw-nrf54l" && _run cargo build --release --features debug-uart ) _say "flashing over J-Link…" @@ -226,7 +226,7 @@ rtt *args: #!/usr/bin/env bash set -euo pipefail source "{{lib}}"; obc_init; ensure_probe || exit 1 - elf="$OBC_ROOT/firmware/obc-fw-nrf54l/target/thumbv8m.main-none-eabihf/release/obc-fw-nrf54l" + elf="${CARGO_TARGET_DIR:-$OBC_ROOT/firmware/obc-fw-nrf54l/target}/thumbv8m.main-none-eabihf/release/obc-fw-nrf54l" if [[ $# -gt 0 && "$1" != --* ]]; then elf="$(_abspath "$1")"; shift; fi [[ -f "$elf" ]] || { _err "no matching board ELF — pass it to: obc rtt ELF"; exit 1; } _run python3 "$OBC_TOOLS/board.py" attach "$elf" "$@" @@ -260,7 +260,7 @@ pack *args: else base="$(basename "$pbf")"; base="${base%.osm.pbf}"; base="${base%.pbf}"; out="$OBC_ROOT/${base}.obcm"; fi ( cd "$OBC_ROOT" && _run cargo build --release -p obc-bake --bin obc-pack ) _say "preset $preset" - cmd=("$OBC_ROOT/target/release/obc-pack" "$pbf" "$preset" "$out") + cmd=("${CARGO_TARGET_DIR:-$OBC_ROOT/target}/release/obc-pack" "$pbf" "$preset" "$out") (( ${#_EXTRA[@]} )) && cmd+=("${_EXTRA[@]}") _run "${cmd[@]}" _say "wrote $out" @@ -279,7 +279,7 @@ inspect *args: set -euo pipefail source "{{lib}}"; obc_init ( cd "$OBC_ROOT" && _run cargo build --release --quiet -p obc-inspect ) - _run "$OBC_ROOT/target/release/obc-inspect" "$@" + _run "${CARGO_TARGET_DIR:-$OBC_ROOT/target}/release/obc-inspect" "$@" # Data targets and the store: a bare `obc data` shows what each target serves and what to run # next. `obc data update TARGET` bakes what is stale and switches the target to the new release; @@ -329,7 +329,7 @@ bake *args: source "{{lib}}"; obc_init; ensure_geos export OBC_LANDMARK_CAPTURE_TOOL="${OBC_LANDMARK_CAPTURE_TOOL:-$OBC_ROOT/tools/landmark_capture.py}" ( cd "$OBC_ROOT" && _run cargo build --release -p obc-bake ) - bin="$OBC_ROOT/target/release/obc-bake" + bin="${CARGO_TARGET_DIR:-$OBC_ROOT/target}/release/obc-bake" tree="${OBC_BAKE_TREE:-$HOME/obc-bake}" # The terrain stage reads the reference archive for its crest lifts. A run that forgets # `--reference` re-bakes every lifted cell without lifts, so obc.local names the archive @@ -450,7 +450,7 @@ web *args: set -euo pipefail source "{{lib}}"; obc_init; ensure_geos cd "$OBC_ROOT" - export OBC_PACK_BIN="$OBC_ROOT/target/release/obc-pack" + export OBC_PACK_BIN="${CARGO_TARGET_DIR:-$OBC_ROOT/target}/release/obc-pack" _run uv sync --locked --inexact --group builder if [[ "${1:-}" == preview-source ]]; then shift @@ -614,9 +614,9 @@ test *args: case "$mode" in full) shift - _run cargo nextest run --workspace --all-features --locked --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fast)" "$@" + _run cargo nextest run --workspace --all-features --locked --tests --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fast)" "$@" fixture_env - _run cargo nextest run --workspace --all-features --locked --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fixtures)" "$@" + _run cargo nextest run --workspace --all-features --locked --tests --no-tests fail --filter-expr "$(python3 tools/test_plan.py cargo-filter --tier fixtures)" "$@" _run cargo test --workspace --all-features --locked --doc ;; affected) @@ -805,8 +805,8 @@ clean *args: source "{{lib}}"; obc_init _run python3 "$OBC_TOOLS/dev_cleanup.py" "$@" -# A raw shell has neither `obc.local` (the tools on PATH, the shared Cargo target) nor GEOS, so a -# command that no task covers runs here: +# A raw shell has neither `obc.local` (the tools on PATH, the Cargo target of the checkout) nor +# GEOS, so a command that no task covers runs here: # obc exec cargo clippy -p obc-data --all-targets -- -D warnings # obc exec npx vitest run src/lib/trailview/roads [doc("Run one command in the environment of the obc tasks. Args: COMMAND [ARGS…]")] diff --git a/tools/obc-dev.sh b/tools/obc-dev.sh index 9b57aaf63c..18864a1e84 100755 --- a/tools/obc-dev.sh +++ b/tools/obc-dev.sh @@ -55,6 +55,7 @@ obc_init() { source "$local_file" set +a fi + obc_checkout_target # The task and every process it starts inherit this priority, so no command needs its own `nice`. if [[ -n "${OBC_NICE:-}" ]]; then [[ "$OBC_NICE" =~ ^[0-9]+$ ]] && (( 10#$OBC_NICE <= 19 )) || { _err "OBC_NICE must be 0 to 19, not '$OBC_NICE'"; return 1; } @@ -66,6 +67,22 @@ obc_init() { return 0 } +# Cargo takes a workspace crate as fresh when its sources are older than its last build, so a +# target that several checkouts share gives one checkout the build of another. With +# CARGO_TARGET_DIR set, each checkout builds in `checkouts//` of it. `obc clean` +# (tools/dev_cleanup.py) computes the same key from the canonical path of the checkout. +obc_checkout_target() { + [[ -n "${CARGO_TARGET_DIR:-}" ]] || return 0 + local base="$CARGO_TARGET_DIR" + # A nested task inherits the target of its parent task. + [[ "$base" =~ ^(.*)/checkouts/[0-9a-f]{16}$ ]] && base="${BASH_REMATCH[1]}" + CARGO_TARGET_DIR="$base/checkouts/$(printf '%s' "$OBC_ROOT" | sha256sum | cut -c1-16)" + export CARGO_TARGET_DIR + if [[ "/${RUSTC_WRAPPER:-}" == */sccache ]]; then + export OBC_SCCACHE="$RUSTC_WRAPPER" RUSTC_WRAPPER="$OBC_ROOT/tools/sccache-rustc.sh" + fi +} + # Expose the locally-built GEOS to obc-pack / the workspace build. ensure_geos() { [[ -f "$HOME/.obc-geos-env.sh" ]] && source "$HOME/.obc-geos-env.sh" diff --git a/tools/obc.local.example b/tools/obc.local.example index 74c86979cf..e1e768a55d 100644 --- a/tools/obc.local.example +++ b/tools/obc.local.example @@ -44,6 +44,17 @@ OBC_R2_PREFIX="cell-catalog" # RISC-V gcc for the board's FLPR blob, if it isn't on your PATH. #RISCV_GCC="$HOME/.local/xPacks/riscv-none-elf-gcc/14.2.0-3/bin/riscv-none-elf-gcc" +# One Cargo target for every checkout: each checkout builds in `checkouts//` of it, so no +# checkout takes the build of another. `obc clean` removes the target of a removed worktree. +#CARGO_TARGET_DIR="$HOME/.cache/obc-cargo-target" +# sccache gives a new checkout the compiled dependencies of the other checkouts. A workspace crate +# never hits across checkouts, because its key holds the path of the checkout. Cargo builds the +# workspace crates incrementally, and sccache passes them through; CARGO_INCREMENTAL=0 makes every +# edit rebuild a crate whole. +#RUSTC_WRAPPER="sccache" +#SCCACHE_DIR="$HOME/.cache/sccache" +#SCCACHE_CACHE_SIZE="30G" + # Run every task, and what it starts, at this nice value (0 to 19). On a machine that also runs # other work, 19 keeps test runs out of its way; a command then needs no `nice` of its own. #OBC_NICE=19 diff --git a/tools/planner_runtime.py b/tools/planner_runtime.py index 44fcab4dc1..970121080c 100644 --- a/tools/planner_runtime.py +++ b/tools/planner_runtime.py @@ -14,7 +14,7 @@ TRAILVIEW = ("ground", "colour-q1", "colour-q2", "colour-q3", "colour-q4") DATA_LAYERS = { "snow": "snow_format", "snow-levels": "snow_format", "snow-seasons": "snow_format", "climate": "years", - "trailview-features": "features_format", "trailview-canopy": "canopy_format", + "trailview-features": "features_format", "trailview-stamps": "stamp_version", "trailview-canopy": "canopy_format", **{f"trailview-{name}": "trailview_format" for name in TRAILVIEW}, } # The format of the offline catalog, of its cell files and of `search/.grid.json`: the format of diff --git a/tools/planner_verify.py b/tools/planner_verify.py index 84808fa3ae..16e122e48b 100644 --- a/tools/planner_verify.py +++ b/tools/planner_verify.py @@ -137,7 +137,7 @@ def archive(path, kind, vector=None): reader = Reader(read) header, metadata = reader.header(), reader.metadata() colour = kind.startswith('trailview-colour-q') - expected = (TileType.UNKNOWN if kind in {'snow-seasons', 'climate', 'trailview-features'} or colour + expected = (TileType.UNKNOWN if kind in {'snow-seasons', 'climate', 'trailview-features', 'trailview-stamps'} or colour else TileType.WEBP if kind in {'terrain', 'snow', 'snow-levels'} or kind.startswith('trailview-') else TileType.MVT) if header['tile_type'] != expected: diff --git a/tools/sccache-rustc.sh b/tools/sccache-rustc.sh new file mode 100755 index 0000000000..54de09c654 --- /dev/null +++ b/tools/sccache-rustc.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# The rustc wrapper of `obc` when obc.local sets RUSTC_WRAPPER to sccache. sccache puts almost +# every CARGO_* variable into its key, and CARGO_TARGET_DIR names the target of the checkout, so +# with it no checkout gets a hit from another one. rustc does not read CARGO_TARGET_DIR. +exec env -u CARGO_TARGET_DIR "${OBC_SCCACHE:-sccache}" "$@" diff --git a/tools/test_plan.py b/tools/test_plan.py index da50038f78..acec3bdb2b 100644 --- a/tools/test_plan.py +++ b/tools/test_plan.py @@ -64,7 +64,7 @@ class Job: "wasm": Job(needs=("selection",), packages=("obc-web-demo", "obcm-assemble")), "wasm-bridges": Job( needs=("selection",), - packages=("obc-builder-bridge",), + packages=("obc-builder-bridge", "obc-ground-plan-bridge"), ), "docs": Job(needs=("selection",)), "ios-unit": Job(needs=("selection",)), @@ -332,13 +332,16 @@ def load_document(root: Path) -> dict[str, Any]: raise PlanError("tools/testing/suites.toml: schema must be 2") return document -def carved_targets(document: Mapping[str, Any]) -> set[tuple[str, str]]: - """Targets a manual, weekly or live suite owns, so no tier compiles them.""" +def carved_targets(document: Mapping[str, Any], running: Iterable[str] | None = None) -> set[tuple[str, str]]: + """Targets a suite owns, which no tier runs. An ordinary or required suite in `running` (every + one when `running` is None) gives its targets back to the fast tier: one build, one result file.""" + running = None if running is None else set(running) return { (suite["package"], target) for suite in document.get("suite", []) if suite.get("package") + and not (suite.get("route", "ordinary") in CI_ROUTES and (running is None or suite["id"] in running)) for target in suite.get("targets", ()) } @@ -739,8 +742,12 @@ def host_platform() -> str: "verification": ("tools/verification",), "planner-search": ("planner/search", "planner/tiles"), } -BRIDGES = ("builder/web/src/lib/core/pkg", "builder/web/test-support/flat-device/pkg") -BRIDGE_PACKAGE = "obc-builder-bridge" +BRIDGES = ( + "builder/web/src/lib/core/pkg", + "builder/web/test-support/flat-device/pkg", + "builder/web/src/lib/trailview/plan/pkg", +) +BRIDGE_PACKAGES = ("obc-builder-bridge", "obc-ground-plan-bridge") NPM_STAMP = "node_modules/.obc-lock" def _lock_digest(project: Path) -> str: @@ -755,7 +762,7 @@ def local_setup(root: Path, jobs: Iterable[str], bridge_changed: bool) -> list[t stamp = root / project / NPM_STAMP if not stamp.is_file() or stamp.read_text() != _lock_digest(root / project): setup.append((project, ["npm", "ci", "--no-audit", "--no-fund"])) - needed = any("wasm-bridges" in JOBS[job].needs for job in jobs if job in JOBS) + needed = any(job == "wasm-bridges" or "wasm-bridges" in JOBS[job].needs for job in jobs if job in JOBS) if needed and (bridge_changed or not all(any((root / pkg).glob("*.wasm")) for pkg in BRIDGES)): setup.append((".", ["bash", "builder/build-wasm-bridges.sh"])) return setup @@ -780,7 +787,8 @@ def run_plan( ) -> int: """Run the selected Rust binaries once, then every selected suite command.""" - packages = list(plan.packages) + # A selected suite that owns targets runs them in its package's fast run. + packages = sorted(set(plan.packages) | {unit.package for unit in plan.selected if unit.declared and unit.package}) commands: list[list[str]] = [] if packages: # Package flags narrow compilation; the tier filter narrows execution. An empty @@ -791,7 +799,7 @@ def run_plan( # workspace run in `tools/ci/test.sh` keeps `fail`, where an empty run really does # mean the filter is wrong. commands.append( - ["cargo", "nextest", "run", "--locked", "--all-features", "--no-tests", "warn"] + ["cargo", "nextest", "run", "--locked", "--all-features", "--tests", "--no-tests", "warn"] + [argument for name in packages for argument in ("-p", name)] + ["--filter-expr", cargo_filter(graph, "fast", packages, carved)] ) @@ -799,7 +807,7 @@ def run_plan( setup = local_setup( root, (job for unit in suites if not unit.platforms or host_platform() in unit.platforms for job in unit.jobs), - BRIDGE_PACKAGE in packages, + any(package in packages for package in BRIDGE_PACKAGES), ) print(f"selected {len(plan.selected)} of {len(plan.units)} units, {len(packages)} Cargo package(s)") for unit in plan.selected: @@ -827,10 +835,15 @@ def run_plan( print("running " + shlex.join(command), flush=True) if subprocess.run(command, cwd=root).returncode != 0: return 1 + # A suite whose command the setup just ran at the root, such as the bridge build, runs once. + prepared = {shlex.join(command) for directory, command in setup if directory == "."} for unit in suites: if unit.platforms and host_platform() not in unit.platforms: print(f"skipped {unit.id}: runs only on {', '.join(unit.platforms)}") continue + if unit.command in prepared: + print(f"done {unit.id}: the setup ran it") + continue print(f"running {unit.id}: {unit.command}", flush=True) if subprocess.run(["bash", "-c", unit.command], cwd=root).returncode != 0: print(f"failed {unit.id}", file=sys.stderr) @@ -1039,7 +1052,8 @@ def command_run(args: argparse.Namespace) -> int: deleted.update(path for path in changed if not (root / path).exists()) definitions = changed_suite_ids(root, args.base, document, args.head) if "tools/testing/suites.toml" in changed else () plan = select(units, graph, changed, deleted=deleted, changed_suites=definitions, base=args.base, head=args.head) - return run_plan(plan, graph, root, carved_targets(document), dry_run=args.dry_run) + running = (unit.id for unit in plan.selected) + return run_plan(plan, graph, root, carved_targets(document, running), dry_run=args.dry_run) def command_prepare(args: argparse.Namespace) -> int: root = (args.root or repository_root()).resolve() @@ -1048,7 +1062,7 @@ def command_prepare(args: argparse.Namespace) -> int: def command_cargo_filter(args: argparse.Namespace) -> int: root = (args.root or repository_root()).resolve() graph, document, _ = load(root) - print(cargo_filter(graph, args.tier, args.packages or None, carved_targets(document))) + print(cargo_filter(graph, args.tier, args.packages or None, carved_targets(document, args.suites))) return 0 def command_gates(args: argparse.Namespace) -> int: @@ -1131,6 +1145,7 @@ def build_parser() -> argparse.ArgumentParser: filter_parser = subparsers.add_parser("cargo-filter", help="a nextest expression over whole test binaries") filter_parser.add_argument("--tier", choices=["fast", "fixtures"], required=True) filter_parser.add_argument("--packages", nargs="*", help="narrow to these packages") + filter_parser.add_argument("--suites", nargs="*", help="the selected suites whose targets join the fast tier (default: all)") filter_parser.set_defaults(func=command_cargo_filter) gates_parser = subparsers.add_parser("gates", help="report what `obc check` gates reproduce") diff --git a/tools/testing/suites.toml b/tools/testing/suites.toml index c39b85173c..0707db814a 100644 --- a/tools/testing/suites.toml +++ b/tools/testing/suites.toml @@ -32,10 +32,17 @@ name = "obc-formats" route = "required" triggers = ["specs/**"] -# The bake embeds the kind table and the road classes, and its codec test reads the shared vectors. +# The bake embeds the kind table and the road classes, its codec test reads the shared vectors, and +# the census test reads the TrailView fixture. [[package]] name = "obc-trailview-features" -triggers = ["data/trailview/kinds.json", "data/trailview/roads.json", "specs/vectors/trailview-features.*"] +triggers = ["data/trailview/kinds.json", "data/trailview/roads.json", "data/trailview/finishes.json", "data/trailview/waterways.json", "specs/vectors/trailview-features.*", "builder/web/tests/browser/trailview/fixture/**"] + +# The ground plan embeds the cross-section tables, and its tests read the shared vectors, the +# TrailView fixture and the viewer's mask reach: Cargo cannot see these inputs. +[[package]] +name = "obc-ground-plan" +triggers = ["data/trailview/plan.json", "data/trailview/roads.json", "data/trailview/finishes.json", "data/trailview/waterways.json", "specs/vectors/trailview-features.*", "builder/web/tests/browser/trailview/fixture/**", "builder/web/src/lib/trailview/terrain/features.wgsl"] [[package]] name = "obc-link" @@ -208,15 +215,14 @@ triggers = [ "builder/web/**/*.test.ts", "builder/web/src/**", "builder/web/test-support/**", - # mesh.test.ts counts the census of the fixture's feature tiles. + # mesh.test.ts meshes the fixture's feature tiles. "builder/web/tests/browser/trailview/fixture/**", "builder/web/package.json", "builder/web/package-lock.json", "tools/planner_mvt_verify.mjs", - # bins.test.ts reads the path widths of the bake. - "host/obc-trailview-features/src/structures.rs", - # bins.test.ts checks the stamp profiles of the road classes. + # bins.test.ts checks the stamp profiles of the road classes and the cross-section tables. "data/trailview/roads.json", + "data/trailview/finishes.json", "builder/web/vite.config.ts", "host/obc-map-core/schema/config.schema.json", "specs/vectors/**", @@ -310,11 +316,10 @@ jobs = ["web"] platforms = ["linux", "macos"] triggers = ["builder/web/src/lib/trailview/**/*.wgsl", "builder/web/src/lib/trailview/gpu/include.ts", "builder/web/scripts/check-wgsl.mjs", "builder/web/package.json"] -# The TrailView page on the checked-in fixture tiles, in Chromium with SwiftShader: one page load that -# draws with no WebGPU error and whose probe gives the height of an instance shader, and the snow mark of -# the ground worker. A test that draws for minutes on SwiftShader takes the tag @gpu (the crack and -# surface audits, the invariant audits of the stamps along the roads of a village and in a lake, -# debug=mask): pull requests skip it, `web.trailview-weekly` runs it. +# The TrailView ground worker in Chromium: the ground bytes under a low alpha and the snow mark. A test +# that draws on SwiftShader takes minutes, so it takes the tag @gpu (the page load with its probe, the +# crack and surface audits, the stamp audits of a village and a lake): pull requests skip it, +# `web.trailview-gpu` runs it on a GPU. [[suite]] id = "web.trailview-smoke" route = "ordinary" @@ -339,12 +344,13 @@ triggers = [ "builder/web/vite.config.ts", ] -# Every TrailView browser test, the @gpu ones too. `test-weekly.yml` runs it each Monday. +# The @gpu TrailView browser tests on the machine's GPU, where they take seconds. A CI runner has no +# GPU, and SwiftShader takes minutes per test. [[suite]] -id = "web.trailview-weekly" +id = "web.trailview-gpu" route = "manual" -command = "npm run test:trailview --prefix builder/web/tests/browser" -platforms = ["linux", "macos"] +command = "OBC_TRAILVIEW_GPU=1 flock /tmp/trailview-gpu.lock npm run test:trailview --prefix builder/web/tests/browser -- --grep @gpu" +platforms = ["linux"] triggers = ["builder/web/tests/browser/trailview/**"] # The job table is not derived from the builders it describes, so the unit tests that pin @@ -410,12 +416,13 @@ triggers = ["host/obc-dem/reference/**", ".python-version", "pyproject.toml", "u # The TrailView tools need rasterio, pyogrio and osmium, which no other suite wants, so the suite runs # under the locked uv group `trailview`. The tests write their own rasters, read the ruleset of # data/trailview/, the engine's tree and plant models that a pack may name and the captured service -# answers of fixtures/sources/trailview-ground/: no service. +# answers of fixtures/sources/trailview-ground/: no service. They take seconds and build no Rust, so +# they ride the unconditional `guards` job. [[suite]] id = "python.trailview" -route = "ordinary" +route = "required" command = "rm -rf .artifacts/python/trailview && uv run --locked --group trailview --group dev python -m xmlrunner discover -s tools/trailview/tests -v -o .artifacts/python/trailview" -jobs = ["test"] +jobs = ["guards"] triggers = ["tools/trailview/**", "data/trailview/**", "fixtures/sources/trailview-ground/**", "tools/planner_geo.py", "tools/step_pool.py", "tools/step_request.py", "tools/data_registry.py", "tools/planner_runtime.py", "data/sources.toml", "builder/web/src/lib/trailview/models/trees/**", "builder/web/src/lib/trailview/models/plants/**", "pyproject.toml", "uv.lock"] @@ -598,6 +605,37 @@ triggers = [ "docs/index.html", ] +# The fixture census of the ground plan: every cell's faces, records, heights, mesh and graph. Its +# inputs are the crate, the rule tables and the TrailView fixture. The fast tier runs its targets +# when the suite is selected. +[[suite]] +id = "ci.ground-plan-census" +route = "ordinary" +jobs = ["test"] +package = "obc-ground-plan" +targets = ["faces", "records", "heights_fixture", "mesh", "graph"] +foundation = true +triggers = [ + "host/obc-ground-plan/**", + "data/trailview/**", + "specs/vectors/trailview-features.*", + "builder/web/tests/browser/trailview/fixture/**", +] + +# Check 7 of the ground plan: every fixture cell gives the same plan digest natively and in WASM. +[[suite]] +id = "ci.ground-plan-bytes" +route = "ordinary" +command = "bash builder/ground-plan-wasm/check-bytes.sh" +jobs = ["wasm-bridges"] +rust_packages = ["obc-ground-plan-bridge"] +triggers = [ + "builder/ground-plan-wasm/**", + "host/obc-ground-plan/**", + "data/trailview/**", + "builder/web/tests/browser/trailview/fixture/**", +] + [[suite]] id = "ci.web-build" route = "ordinary" diff --git a/tools/tests/test_dev_cleanup.py b/tools/tests/test_dev_cleanup.py index daef010a44..4b2a2207fd 100644 --- a/tools/tests/test_dev_cleanup.py +++ b/tools/tests/test_dev_cleanup.py @@ -3,6 +3,7 @@ import importlib.util import io import os +import subprocess import sys import tempfile import time @@ -191,6 +192,9 @@ def test_prune_cargo_target_removes_unused_units_whole_inside_the_target(self): now = time.time() old = now - 8 * cleanup.SECONDS_PER_DAY wasm = "wasm32-unknown-unknown/debug" + # The own target of a registered checkout. + live = Path("/wt/live") + bridges = f"checkouts/{cleanup.checkout_key(live)}/{wasm}" target = self.make_target( Path(scratch), { @@ -213,6 +217,8 @@ def test_prune_cargo_target_removes_unused_units_whole_inside_the_target(self): "debug/incremental/live-4444444444444444/s-2/object.o": (old, old), f"{wasm}/.cargo-lock": (old, old), f"{wasm}/.fingerprint/w-5555555555555555/lib-w": (old, old), + f"{bridges}/.cargo-lock": (old, old), + f"{bridges}/.fingerprint/b-7777777777777777/lib-b": (old, old), # A profile without `.cargo-lock` is not cargo's. "doc/.fingerprint/d-6666666666666666/lib-d": (old, old), "doc/deps/libd-6666666666666666.rlib": (old, old), @@ -231,14 +237,15 @@ def test_prune_cargo_target_removes_unused_units_whole_inside_the_target(self): target / "debug" / "deps": (2, 2), target / "debug" / "incremental": (1, 1), target / wasm / ".fingerprint": (1, 1), + target / bridges / ".fingerprint": (1, 1), }, [], ) - self.assertEqual(cleanup.prune_cargo_target(target, cutoff, apply=False), expected) + self.assertEqual(cleanup.prune_cargo_target(target, cutoff, False, {live}), expected) self.assertTrue((target / "debug" / "deps" / "libstale-2222222222222222.rlib").exists()) - self.assertEqual(cleanup.prune_cargo_target(target, cutoff, apply=True), expected) + self.assertEqual(cleanup.prune_cargo_target(target, cutoff, True, {live}), expected) for gone in ( "debug/.fingerprint/stale-2222222222222222", "debug/build/stale-2222222222222222", @@ -246,6 +253,7 @@ def test_prune_cargo_target_removes_unused_units_whole_inside_the_target(self): "debug/deps/stale-2222222222222222.d", "debug/incremental/stale-3333333333333333", f"{wasm}/.fingerprint/w-5555555555555555", + f"{bridges}/.fingerprint/b-7777777777777777", ): self.assertFalse((target / gone).exists(), gone) for kept in ( @@ -262,6 +270,51 @@ def test_prune_cargo_target_removes_unused_units_whole_inside_the_target(self): self.assertTrue((target / kept).exists(), kept) self.assertTrue(outside_file.exists()) + def test_prune_cargo_target_removes_the_idle_target_of_a_gone_checkout_whole(self): + live, gone = Path("/wt/live"), Path("/wt/gone") + script = MODULE_PATH.parent / "obc-dev.sh" + # A nested task keeps the target of its checkout. + nested = "obc_checkout_target; obc_checkout_target" + own = f"/t/checkouts/{cleanup.checkout_key(live)}" + # The recipes run under `set -u`, with or without a wrapper. + wrappers = ( + ("RUSTC_WRAPPER=/bin/sccache", f"{live}/tools/sccache-rustc.sh"), + ("unset RUSTC_WRAPPER", "none"), + ) + for wrapper, expected in wrappers: + shell = ( + f"{wrapper}; OBC_ROOT={live} CARGO_TARGET_DIR=/t; source {script}; {nested}; " + 'printf "%s %s" "$CARGO_TARGET_DIR" "${RUSTC_WRAPPER:-none}"' + ) + command = ["bash", "-euo", "pipefail", "-c", shell] + run = subprocess.run(command, check=True, text=True, stdout=subprocess.PIPE) + self.assertEqual(run.stdout, f"{own} {expected}") + with tempfile.TemporaryDirectory() as scratch: + now = time.time() + old = now - 8 * cleanup.SECONDS_PER_DAY + used = "checkouts/0123456789abcdef" + target = self.make_target( + Path(scratch), + { + f"checkouts/{cleanup.checkout_key(live)}/release/.cargo-lock": (old, old), + f"checkouts/{cleanup.checkout_key(live)}/release/deps/libbridge.rlib": (old, old), + f"checkouts/{cleanup.checkout_key(gone)}/release/.cargo-lock": (old, old), + f"checkouts/{cleanup.checkout_key(gone)}/release/deps/libbridge.rlib": (old, old), + f"{used}/release/.cargo-lock": (old, old), + f"{used}/release/deps/libbridge.rlib": (now, now), + }, + ) + cutoff = now - 7 * cleanup.SECONDS_PER_DAY + own = target / "checkouts" / cleanup.checkout_key(gone) + expected = ({own: (1, 2)}, []) + self.assertEqual(cleanup.prune_cargo_target(target, cutoff, False, {live}), expected) + self.assertTrue(own.exists()) + self.assertEqual(cleanup.prune_cargo_target(target, cutoff, True, {live}), expected) + self.assertFalse(own.exists()) + mine = target / "checkouts" / cleanup.checkout_key(live) + self.assertTrue((mine / "release/deps/libbridge.rlib").exists()) + self.assertTrue((target / used / "release/deps/libbridge.rlib").exists()) + def test_prune_cargo_target_skips_a_profile_that_a_build_holds(self): with tempfile.TemporaryDirectory() as scratch: old = time.time() - 8 * cleanup.SECONDS_PER_DAY @@ -277,11 +330,11 @@ def test_prune_cargo_target_skips_a_profile_that_a_build_holds(self): with open(target / "debug" / ".cargo-lock") as lock: fcntl.flock(lock, fcntl.LOCK_EX) self.assertEqual( - cleanup.prune_cargo_target(target, cutoff, apply=True), ({}, [target / "debug"]) + cleanup.prune_cargo_target(target, cutoff, True, set()), ({}, [target / "debug"]) ) self.assertTrue((target / "debug" / "deps" / "libold-1111111111111111.rlib").exists()) self.assertEqual( - cleanup.prune_cargo_target(target, cutoff, apply=True)[0], + cleanup.prune_cargo_target(target, cutoff, True, set())[0], {target / "debug" / ".fingerprint": (1, 1), target / "debug" / "deps": (1, 1)}, ) @@ -300,6 +353,9 @@ def test_cargo_target_refuses_root_home_and_repositories_and_skips_untagged_dirs self.assertIn("no CACHEDIR.TAG", output.getvalue()) (untagged / "CACHEDIR.TAG").write_text("Signature: 8a477f597d28d172789f06886806bc55") self.assertEqual(cleanup.cargo_target(str(untagged)), untagged.resolve()) + own = untagged / "checkouts" / cleanup.checkout_key(repo) + own.mkdir(parents=True) + self.assertEqual(cleanup.cargo_target(str(own)), untagged.resolve()) self.assertIsNone(cleanup.cargo_target("")) self.assertIsNone(cleanup.cargo_target(str(root / "missing"))) diff --git a/tools/tests/test_selection_plan.py b/tools/tests/test_selection_plan.py index 6a34335935..1898fbfc4e 100644 --- a/tools/tests/test_selection_plan.py +++ b/tools/tests/test_selection_plan.py @@ -8,6 +8,7 @@ from __future__ import annotations import re +import shlex import subprocess import sys import tempfile @@ -20,6 +21,8 @@ import test_plan as plan +BUILD = (".", ["bash", "builder/build-wasm-bridges.sh"]) + def package(name, root, dependencies=(), product_root=".", ordinary=("main",), fixtures=(), examples=()): return plan.Package( @@ -295,13 +298,28 @@ def test_a_local_run_installs_what_a_new_worktree_lacks_and_nothing_twice(self) (root / pkg).mkdir(parents=True) (root / pkg / "bridge.wasm").write_bytes(b"") self.assertEqual(plan.local_setup(root, ["web-browser"], bridge_changed=False), []) - self.assertEqual( - plan.local_setup(root, ["web"], bridge_changed=True), - [(".", ["bash", "builder/build-wasm-bridges.sh"])], - ) + self.assertEqual(plan.local_setup(root, ["web"], bridge_changed=True), [BUILD]) (root / "builder/web/package-lock.json").write_text("a new lock") self.assertEqual([d for d, _ in plan.local_setup(root, ["web"], bridge_changed=False)], ["builder/web"]) + def test_the_bridge_job_itself_builds_the_bridges(self) -> None: + with tempfile.TemporaryDirectory() as directory: + self.assertEqual(plan.local_setup(Path(directory), ["wasm-bridges"], bridge_changed=False), [BUILD]) + for pkg in plan.BRIDGES: + (Path(directory) / pkg).mkdir(parents=True, exist_ok=True) + (Path(directory) / pkg / "bridge.wasm").write_bytes(b"") + self.assertEqual(plan.local_setup(Path(directory), ["wasm-bridges"], bridge_changed=False), []) + + def test_a_suite_whose_command_the_setup_ran_runs_once(self) -> None: + bridges = plan.Unit(id="ci.wasm-size", jobs=["wasm-bridges"], command=shlex.join(BUILD[1]), reasons=["x"]) + chosen = plan.Plan(base="a", head="b", changed_paths=[], units=[bridges], packages=[], errors=[]) + ran = [] + with patch.object(plan, "local_setup", return_value=[BUILD]), \ + patch.object(plan.subprocess, "run", side_effect=lambda command, **_: ran.append(command) or subprocess.CompletedProcess([], 0)), \ + patch("builtins.print"): + self.assertEqual(plan.run_plan(chosen, self.graph, Path(".")), 0) + self.assertEqual(ran, [BUILD[1]]) + def test_gates_name_jobs_and_a_ci_only_suite_is_never_claimed(self) -> None: units = [ plan.Unit(id="rust.core", jobs=["test"], package="core"), @@ -707,6 +725,13 @@ def test_explicitly_invoked_targets_are_in_no_tier(self) -> None: for carved in ("binary(=decode)", "binary(=real_tile)", "binary(=assistant_places)"): self.assertNotIn(carved, expression) + def test_an_ordinary_suites_targets_join_the_fast_tier_only_when_it_runs(self) -> None: + census = "(package(=obc-ground-plan) & binary(=heights_fixture))" + running = plan.cargo_filter(self.graph, "fast", carved=plan.carved_targets(self.document, ["ci.ground-plan-census"])) + idle = plan.cargo_filter(self.graph, "fast", carved=plan.carved_targets(self.document, [])) + self.assertIn(census, running) + self.assertNotIn(census, idle) + def test_every_required_suite_a_full_local_run_misses_is_named(self) -> None: covered = {item.id for item in plan.reproduced(self.units, sorted(plan.GATES))} missing = sorted(item.id for item in self.units if item.route == "required" and item.id not in covered) @@ -718,6 +743,7 @@ def test_every_required_suite_a_full_local_run_misses_is_named(self) -> None: "ci.ios-host-portability", "ci.prose", "python.repository-tools", + "python.trailview", ], )