maps: DEM ingest, terrain and S3DB in the tiler, --dem in harden
- Commit
e650d533c5be0f5dfe67da96688fe78ebbf09b19- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-10 05:19 UTC (2 months ago)
- Parents
1afb65e
Diff
scripts/maps/build_all.ps1
diff --git a/scripts/maps/build_all.ps1 b/scripts/maps/build_all.ps1index d1ae489939..7789ef3e73 100644--- a/scripts/maps/build_all.ps1+++ b/scripts/maps/build_all.ps1@@ -63,6 +63,17 @@ param( [switch] $Force, [switch] $DryRun, + # Terrain (WS-G): fetch AWS Terrain Tiles (terrarium, ~30 m) for -Bbox and decode+ # them into heightmaps.mdem, a per-tile u16 grid dataset for the v6 heightmap side+ # table. Opt-in and bbox-scoped (the California test build first). Needs a bbox and+ # a network reach to the terrarium source. See dem_ingest.+ [string] $Bbox = "",+ [switch] $Dem,+ [int] $DemZoom = 12,+ [int] $DemOutZoom = 14,+ [int] $DemDim = 17,+ [string] $DemSource = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium",+ # Engines, per layer, so a ported layer rolls back with a flag. A 'rust' value # is refused until that layer is actually ported. [ValidateSet("rust", "legacy")] [string] $EnginePois = "rust",@@ -472,6 +483,63 @@ if (Test-Stage "tiles") { } } +# --- stage: dem (heightmaps.mdem) ---+# The terrain half of WS-G: fetch terrarium tiles for -Bbox and decode them into a per-tile u16+# heightmap grid dataset. Opt-in via -Dem, and it needs -Bbox: fetching terrarium tiles for a+# continent is a different order of magnitude, so this is scoped to the California test region+# first. Network I/O (the download loop) lives here; dem_ingest does only the decode + downsample.+if ($Dem) {+ if (Test-Stamp "dem") {+ Write-Host "=== dem: stamp present, skipping (-Force to redo) ==="+ } else {+ if (-not $Bbox) { throw "-Dem needs -Bbox (the region to fetch terrain for)" }+ $DemTiles = Join-Path $Work "dem\tiles"+ $DemOut = Join-Path $OutDir "heightmaps.mdem"+ Write-Host "=== dem -> $DemOut (terrarium z$DemZoom over $Bbox) ==="+ $parts = $Bbox -split ','+ if ($parts.Count -ne 4) { throw "-Bbox is minlon,minlat,maxlon,maxlat" }+ $minLon = [double]$parts[0]; $minLat = [double]$parts[1]+ $maxLon = [double]$parts[2]; $maxLat = [double]$parts[3]+ $n = [math]::Pow(2, $DemZoom)+ function LonToX([double]$lon) { [math]::Floor(($lon + 180.0) / 360.0 * $n) }+ function LatToY([double]$lat) {+ $r = $lat * [math]::PI / 180.0+ [math]::Floor((1.0 - [math]::Log([math]::Tan($r) + 1.0 / [math]::Cos($r)) / [math]::PI) / 2.0 * $n)+ }+ $x0 = [int](LonToX $minLon); $x1 = [int](LonToX $maxLon)+ $y0 = [int](LatToY $maxLat); $y1 = [int](LatToY $minLat)+ if ($x1 -lt $x0) { $t = $x0; $x0 = $x1; $x1 = $t }+ if ($y1 -lt $y0) { $t = $y0; $y0 = $y1; $y1 = $t }+ Write-Host "[all] terrarium z$DemZoom tiles x $x0..$x1, y $y0..$y1"+ if ($DryRun) {+ $count = ($x1 - $x0 + 1) * ($y1 - $y0 + 1)+ Write-Host "[dry-run] would fetch $count terrarium tile(s) and run dem_ingest"+ } else {+ for ($tx = $x0; $tx -le $x1; $tx++) {+ $dir = Join-Path $DemTiles "$DemZoom\$tx"+ New-Item -ItemType Directory -Force -Path $dir | Out-Null+ for ($ty = $y0; $ty -le $y1; $ty++) {+ $dest = Join-Path $dir "$ty.png"+ if (Test-Path $dest) { continue }+ $url = "$DemSource/$DemZoom/$tx/$ty.png"+ try {+ Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing -ErrorAction Stop+ } catch {+ Write-Host "[all] no terrarium tile at $DemZoom/$tx/$ty (ocean?), skipping"+ if (Test-Path $dest) { Remove-Item $dest -Force }+ }+ }+ }+ $DemCargo = Join-Path $Here "dem_ingest\Cargo.toml"+ Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $DemCargo,+ "--bin", "dem_ingest", "--", "--tiles-dir", $DemTiles, "--bbox", $Bbox,+ "--out", $DemOut, "--dem-zoom", "$DemZoom", "--out-zoom", "$DemOutZoom",+ "--dim", "$DemDim", "--skip-flat")+ Set-Stamp "dem"+ }+ }+}+ # --- the graph barrier --- # With -OverlapGraph the graph stage has been running alongside everything above. It # must be finished, and finished SUCCESSFULLY, before the manifest hashes its outputs:
scripts/maps/build_all.sh
diff --git a/scripts/maps/build_all.sh b/scripts/maps/build_all.shindex 259431c370..abedaa29df 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -77,6 +77,15 @@ set -euo pipefail # Stage control # --skip-graph --skip-pois --skip-transit --skip-tiles # --only STAGE run exactly one of graph|pois|transit|tiles+# --dem extra terrain stage: fetch AWS Terrain Tiles (terrarium,+# ~30 m) for --bbox and decode them into heightmaps.mdem, a+# per-tile u16 grid dataset for the v6 heightmap side table.+# Opt-in and bbox-scoped (the California test build first);+# needs curl. See dem_ingest.+# --dem-zoom Z terrarium zoom to fetch (default 12, ~30 m)+# --dem-out-zoom Z map tile zoom to sample one grid per (default 14)+# --dem-dim N grid side length, N x N samples per tile (default 17)+# --dem-source URL terrarium z/x/y.png prefix (default AWS elevation-tiles-prod) # --force ignore stamps and redo every requested stage # --jobs N how many layer builds (tiles) and feed unzips (transit) run # at once. Default 3. Peak memory is roughly N x the largest@@ -151,6 +160,15 @@ SKIP_TRANSIT=0 SKIP_TILES=0 ONLY="" FORCE=0+# The DEM/terrain stage (WS-G): fetch AWS Terrain Tiles for the bbox and decode them into a+# per-tile heightmap grid dataset. Opt-in, because it reaches a second network source and only+# makes sense for a bounded region — the California test build first, per the plan.+DEM=0+DEM_ZOOM=12+DEM_DIM=17+DEM_OUT_ZOOM=14+# AWS Terrain Tiles, terrarium encoding. z/x/y.png under this prefix.+DEM_SOURCE="https://s3.amazonaws.com/elevation-tiles-prod/terrarium" # Fanned out to the tiles stage's layer builds and the transit stage's unzip loop. # Peak memory is roughly JOBS x the largest concurrent job, so this is a memory dial # as much as a speed one -- see build_v5_pmtiles.sh's own note.@@ -199,6 +217,11 @@ while [[ $# -gt 0 ]]; do --skip-pois) SKIP_POIS=1; shift ;; --skip-transit) SKIP_TRANSIT=1; shift ;; --skip-tiles) SKIP_TILES=1; shift ;;+ --dem) DEM=1; shift ;;+ --dem-zoom) DEM_ZOOM="$2"; shift 2 ;;+ --dem-dim) DEM_DIM="$2"; shift 2 ;;+ --dem-out-zoom) DEM_OUT_ZOOM="$2"; shift 2 ;;+ --dem-source) DEM_SOURCE="$2"; shift 2 ;; --only) ONLY="$2"; shift 2 ;; --force) FORCE=1; shift ;; --jobs) JOBS="$2"; shift 2 ;;@@ -458,6 +481,60 @@ if want_stage tiles; then fi fi +# --- stage: dem (heightmaps.mdem) ---+# Fetch AWS Terrain Tiles (terrarium PNG, ~30 m) covering the bbox and decode them into a+# per-tile u16 heightmap grid dataset — the build half of WS-G's 3D terrain relief. Opt-in via+# --dem, and it needs a --bbox: fetching terrarium tiles for a whole continent (let alone the+# planet) is a different order of magnitude, so this is scoped to the California test region+# first and turned on deliberately.+#+# Network I/O (the curl loop) lives here, as it does for every other source; dem_ingest itself+# does only the bytes-to-bytes decode + downsample.+if [[ "$DEM" == "1" ]]; then+ if stage_done dem; then+ echo "=== dem: stamp present, skipping (--force to redo) ==="+ else+ [[ -n "$BBOX" ]] || { echo "ERROR: --dem needs --bbox (the region to fetch terrain for)" >&2; exit 1; }+ command -v curl >/dev/null || { echo "ERROR: --dem needs curl" >&2; exit 1; }+ DEM_TILES="$WORK/dem/tiles"+ DEM_OUT="$OUT_DIR/heightmaps.mdem"+ echo "=== dem -> $DEM_OUT (terrarium z$DEM_ZOOM over $BBOX) ==="+ # The terrarium tile x/y range the bbox covers at the DEM zoom. Web-mercator, in awk+ # because it is four numbers and belongs beside the curl that uses them.+ read -r DX0 DX1 DY0 DY1 < <(awk -v b="$BBOX" -v z="$DEM_ZOOM" 'BEGIN{+ split(b, p, ",");+ pi=3.141592653589793; n=2^z;+ x0=int((p[1]+180)/360*n); x1=int((p[3]+180)/360*n);+ latr=p[4]*pi/180; y0=int((1-log((sin(latr)+1)/cos(latr))/pi)/2*n);+ latr=p[2]*pi/180; y1=int((1-log((sin(latr)+1)/cos(latr))/pi)/2*n);+ if(x1<x0){t=x0;x0=x1;x1=t}; if(y1<y0){t=y0;y0=y1;y1=t};+ print x0, x1, y0, y1;+ }')+ [[ -n "${DX0:-}" ]] || { echo "ERROR: could not compute terrarium tile range from $BBOX" >&2; exit 1; }+ echo "[all] terrarium z$DEM_ZOOM tiles x $DX0..$DX1, y $DY0..$DY1"+ if [[ "$DRY_RUN" == "1" ]]; then+ echo "[dry-run] would fetch $(( (DX1-DX0+1)*(DY1-DY0+1) )) terrarium tile(s) and run dem_ingest"+ else+ for ((tx=DX0; tx<=DX1; tx++)); do+ mkdir -p "$DEM_TILES/$DEM_ZOOM/$tx"+ for ((ty=DY0; ty<=DY1; ty++)); do+ dest="$DEM_TILES/$DEM_ZOOM/$tx/$ty.png"+ [[ -f "$dest" ]] && continue+ curl -fsSL --retry 3 -o "$dest.partial" \+ "$DEM_SOURCE/$DEM_ZOOM/$tx/$ty.png" \+ && mv "$dest.partial" "$dest" \+ || { echo "[all] no terrarium tile at $DEM_ZOOM/$tx/$ty (ocean?), skipping"; rm -f "$dest.partial"; }+ done+ done+ run cargo run --release --quiet --manifest-path "$HERE/dem_ingest/Cargo.toml" \+ --bin dem_ingest -- \+ --tiles-dir "$DEM_TILES" --bbox "$BBOX" --out "$DEM_OUT" \+ --dem-zoom "$DEM_ZOOM" --out-zoom "$DEM_OUT_ZOOM" --dim "$DEM_DIM" --skip-flat+ mark_done dem+ fi+ fi+fi+ # --- the graph barrier --- # With --overlap-graph the graph stage has been running alongside everything above. # It must be finished, and finished SUCCESSFULLY, before the manifest hashes its
scripts/maps/dem_ingest/Cargo.lock
diff --git a/scripts/maps/dem_ingest/Cargo.lock b/scripts/maps/dem_ingest/Cargo.locknew file mode 100644index 0000000000..33130ce074--- /dev/null+++ b/scripts/maps/dem_ingest/Cargo.lock@@ -0,0 +1,33 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "dem_ingest"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+ "tilecodec",+]++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+]++[[package]]+name = "tilecodec"+version = "0.1.0"+dependencies = [+ "miniz_oxide",+]
scripts/maps/dem_ingest/Cargo.toml
diff --git a/scripts/maps/dem_ingest/Cargo.toml b/scripts/maps/dem_ingest/Cargo.tomlnew file mode 100644index 0000000000..159ffd7feb--- /dev/null+++ b/scripts/maps/dem_ingest/Cargo.toml@@ -0,0 +1,37 @@+# The DEM-ingest sub-tool: AWS Terrain Tiles (terrarium PNG) in, a per-map-tile+# `u16` heightmap grid dataset out — the build half of WS-G's 3D terrain relief.+#+# DETACHED from both workspaces (the empty `[workspace]` table below), like every+# other host tool under `scripts/maps`: it is built for the host with the host+# toolchain, and being a member of either workspace would drag that workspace's+# toolchain, profiles and lockfile into the other's build.+#+# NETWORK I/O LIVES IN build_all.sh, not here — the same division of labour every+# tool under scripts/maps keeps: the shell curls the terrarium tiles into a local+# directory and this crate does the bytes-to-bytes work (PNG decode, terrarium+# height decode, downsample). So the only dependency is `miniz_oxide`, pure Rust,+# for the zlib INFLATE a PNG's IDAT needs — the same crate `tilecodec` already+# builds with. `tilecodec` comes along for its slippy/pmtiles tile id math and the+# `Heightmap` grid layout this dataset mirrors on the wire.++[package]+name = "dem_ingest"+version = "0.1.0"+edition = "2021"+publish = false+license = "GPL-2.0-only"+description = "Decode AWS Terrain Tiles into per-tile u16 heightmap grids for the .mamaps terrain side table"++[[bin]]+name = "dem_ingest"+path = "src/main.rs"++[dependencies]+tilecodec = { path = "../../../library/tilecodec/src/main/rust" }+miniz_oxide = "0.8"++[profile.release]+opt-level = 3++# Detach from both the repo-root Android workspace and the other host tools'.+[workspace]
scripts/maps/dem_ingest/src/main.rs
diff --git a/scripts/maps/dem_ingest/src/main.rs b/scripts/maps/dem_ingest/src/main.rsnew file mode 100644index 0000000000..fb5f260038--- /dev/null+++ b/scripts/maps/dem_ingest/src/main.rs@@ -0,0 +1,494 @@+//! Decode AWS Terrain Tiles ("terrarium" PNG) into a per-map-tile `u16` heightmap grid dataset —+//! the build half of WS-G's 3D terrain relief and the second of the two v6 `.mamaps` side tables.+//!+//! # What it does+//!+//! Given a directory of terrarium PNG tiles (fetched by `build_all.sh`, laid out `<z>/<x>/<y>.png`+//! in the usual slippy convention) and a bounding box, it produces one small square `u16` grid per+//! output map tile by sampling the DEM at each grid point. A sample is metres above sea level+//! **biased by 32768** — `stored = metres + 32768` — which is exactly the number the terrarium+//! encoding already carries before its `-32768`, so no precision is lost round-tripping it, and it+//! is the same convention [`tilecodec::mamaps::body::Heightmap`] stores on the wire.+//!+//! terrarium decode: `elevation_m = R*256 + G + B/256 - 32768`, so `stored = round(R*256 + G ++//! B/256)`.+//!+//! # Why the network is not here+//!+//! `build_all.sh` owns network I/O for every stage; this crate does the bytes-to-bytes work alone+//! (PNG decode, height decode, downsample), which is why its only dependency is the pure-Rust+//! `miniz_oxide` a PNG's zlib IDAT needs to inflate.+//!+//! # Output+//!+//! A single `.mdem` dataset: a header, then per non-empty tile a pmtiles tile id and its+//! `dim * dim` samples, row-major from the tile's top-left. Ocean/flat tiles are omitted with+//! `--skip-flat`, matching the wire format's rule that an elevation-free tile carries no section.+//! Wiring this dataset into the archive's `BODY_FLAG_HEIGHTMAP` section is a small follow-up step+//! (or WS-G's, at render integration); this tool produces the grids the format is already able to+//! carry and round-trip.++use std::collections::HashMap;+use std::f64::consts::PI;+use std::path::PathBuf;++use tilecodec::pmtiles::tile_id;++const OUT_MAGIC: &[u8; 4] = b"MDEM";+const OUT_VERSION: u8 = 1;++fn main() {+ if let Err(e) = run() {+ eprintln!("dem_ingest: {e}");+ std::process::exit(1);+ }+}++struct Args {+ tiles_dir: PathBuf,+ out: PathBuf,+ out_zoom: u8,+ dem_zoom: u8,+ dim: u16,+ bbox: (f64, f64, f64, f64),+ skip_flat: bool,+}++fn run() -> Result<(), String> {+ let args = parse_args()?;+ if args.dim < 2 {+ return Err("--dim must be at least 2".to_string());+ }+ let n = 1u64 << args.out_zoom;+ // The output tile range the bbox covers, clamped to the world.+ let (min_lon, min_lat, max_lon, max_lat) = args.bbox;+ let x0 = lon_to_tile_x(min_lon, args.out_zoom).floor().max(0.0) as u64;+ let x1 = lon_to_tile_x(max_lon, args.out_zoom).ceil().min(n as f64) as u64;+ // Latitude runs the other way: max_lat is the smaller tile y.+ let y0 = lat_to_tile_y(max_lat, args.out_zoom).floor().max(0.0) as u64;+ let y1 = lat_to_tile_y(min_lat, args.out_zoom).ceil().min(n as f64) as u64;+ if x1 <= x0 || y1 <= y0 {+ return Err(format!(+ "the bbox {min_lon},{min_lat},{max_lon},{max_lat} covers no z{} tiles",+ args.out_zoom+ ));+ }++ // Decoded DEM tiles, cached across output tiles: an output tile's neighbours share DEM tiles,+ // and re-inflating a PNG per grid point would dominate. `None` marks a tile the fetch missed.+ let mut dem_cache: HashMap<(u64, u64), Option<Vec<u16>>> = HashMap::new();+ let mut tiles: Vec<(u64, Vec<u16>)> = Vec::new();+ let mut missing = 0u64;++ for oy in y0..y1 {+ for ox in x0..x1 {+ match sample_tile(&args, ox, oy, &mut dem_cache)? {+ Some(grid) => {+ if args.skip_flat && is_flat(&grid) {+ continue;+ }+ tiles.push((tile_id(args.out_zoom, ox, oy), grid));+ }+ None => missing += 1,+ }+ }+ }++ // Ascending by tile id, so the dataset is deterministic and a merge into an archive is a+ // straight join in tile order.+ tiles.sort_by_key(|(id, _)| *id);+ write_dataset(&args, &tiles)?;+ println!(+ "dem_ingest: wrote {} tile(s) at z{} ({}x{}) to {} ({} output tile(s) had no DEM coverage)",+ tiles.len(),+ args.out_zoom,+ args.dim,+ args.dim,+ args.out.display(),+ missing,+ );+ Ok(())+}++/// Sample one output tile's grid, or `None` when no DEM tile under it was fetched.+fn sample_tile(+ args: &Args,+ ox: u64,+ oy: u64,+ cache: &mut HashMap<(u64, u64), Option<Vec<u16>>>,+) -> Result<Option<Vec<u16>>, String> {+ let dim = args.dim as usize;+ let out_n = (1u64 << args.out_zoom) as f64;+ let dem_n = (1u64 << args.dem_zoom) as f64;+ let mut grid = Vec::with_capacity(dim * dim);+ let mut any_data = false;+ for row in 0..dim {+ // Grid point fractional position within the output tile, top-left origin.+ let fy = oy as f64 + row as f64 / (dim as f64 - 1.0);+ let lat = tile_y_to_lat(fy, args.out_zoom);+ for col in 0..dim {+ let fx = ox as f64 + col as f64 / (dim as f64 - 1.0);+ let lon = tile_x_to_lon(fx, args.out_zoom);+ // The DEM tile and pixel this lon/lat lands in at the DEM zoom.+ let gx = ((lon + 180.0) / 360.0 * dem_n).clamp(0.0, dem_n - f64::EPSILON);+ let gy = lat_to_tile_y(lat, args.dem_zoom).clamp(0.0, dem_n - f64::EPSILON);+ let dtx = gx.floor() as u64;+ let dty = gy.floor() as u64;+ let px = (((gx - dtx as f64) * 256.0) as usize).min(255);+ let py = (((gy - dty as f64) * 256.0) as usize).min(255);+ let sample = match dem_tile(args, dtx, dty, cache)? {+ Some(tile) => {+ any_data = true;+ tile[py * 256 + px]+ }+ // No DEM here: sea level. A tile entirely over missing DEM is dropped below.+ None => 32768,+ };+ grid.push(sample);+ }+ let _ = out_n; // documents the projection's modulus; kept for clarity.+ }+ Ok(any_data.then_some(grid))+}++/// A decoded terrarium DEM tile as 256*256 biased `u16` samples, or `None` if the file is absent.+fn dem_tile<'a>(+ args: &Args,+ x: u64,+ y: u64,+ cache: &'a mut HashMap<(u64, u64), Option<Vec<u16>>>,+) -> Result<&'a Option<Vec<u16>>, String> {+ if !cache.contains_key(&(x, y)) {+ let path = args+ .tiles_dir+ .join(args.dem_zoom.to_string())+ .join(x.to_string())+ .join(format!("{y}.png"));+ let decoded = if path.exists() {+ let bytes = std::fs::read(&path).map_err(|e| format!("reading {}: {e}", path.display()))?;+ Some(decode_terrarium(&bytes).map_err(|e| format!("decoding {}: {e}", path.display()))?)+ } else {+ None+ };+ cache.insert((x, y), decoded);+ }+ Ok(cache.get(&(x, y)).expect("just inserted"))+}++/// A DEM grid is "flat" — an ocean or a plain at one level — when every sample is within a metre or+/// two of the same height. Such a tile carries no relief worth a section, so it is omitted.+fn is_flat(grid: &[u16]) -> bool {+ let (mut lo, mut hi) = (u16::MAX, u16::MIN);+ for &s in grid {+ lo = lo.min(s);+ hi = hi.max(s);+ }+ // Sea level is 32768; a grid that is all within ±2 m of one level (including sea) is flat.+ hi.saturating_sub(lo) <= 2+}++/// Decode a terrarium PNG into 256*256 biased `u16` height samples.+fn decode_terrarium(png: &[u8]) -> Result<Vec<u16>, String> {+ let image = decode_png(png)?;+ if image.width != 256 || image.height != 256 {+ return Err(format!("a terrarium tile is 256x256, got {}x{}", image.width, image.height));+ }+ let ch = image.channels as usize;+ let mut out = Vec::with_capacity(256 * 256);+ for i in 0..256 * 256 {+ let base = i * ch;+ let (r, g, b) = (+ image.pixels[base] as u32,+ image.pixels[base + 1] as u32,+ image.pixels[base + 2] as u32,+ );+ out.push(terrarium_stored(r, g, b));+ }+ Ok(out)+}++/// The biased `u16` for one terrarium pixel: `round(R*256 + G + B/256)`, which is+/// `elevation_m + 32768` and so lands sea level at 32768.+fn terrarium_stored(r: u32, g: u32, b: u32) -> u16 {+ // B/256 rounds to 0 or 1; the top of the range clamps rather than wraps.+ let v = r * 256 + g + if b >= 128 { 1 } else { 0 };+ v.min(u16::MAX as u32) as u16+}++struct Image {+ width: u32,+ height: u32,+ channels: u8,+ pixels: Vec<u8>,+}++/// A minimal PNG decoder: 8-bit RGB or RGBA, non-interlaced, which is what every terrarium tile is.+///+/// Not a general PNG library — palette, 16-bit, greyscale and Adam7 interlace are refused rather+/// than half-supported, because a terrarium tile is never any of them and a silent misdecode would+/// paint the wrong mountain.+fn decode_png(bytes: &[u8]) -> Result<Image, String> {+ const SIG: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];+ if bytes.len() < 8 || bytes[..8] != SIG {+ return Err("not a PNG (bad signature)".to_string());+ }+ let mut at = 8usize;+ let mut width = 0u32;+ let mut height = 0u32;+ let mut colour_type = 0u8;+ let mut idat: Vec<u8> = Vec::new();+ let mut seen_ihdr = false;+ while at + 8 <= bytes.len() {+ let len = u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize;+ let kind = &bytes[at + 4..at + 8];+ let data_start = at + 8;+ let data_end = data_start+ .checked_add(len)+ .ok_or_else(|| "a PNG chunk length overflows".to_string())?;+ if data_end + 4 > bytes.len() {+ return Err("a PNG chunk runs past the file".to_string());+ }+ let data = &bytes[data_start..data_end];+ match kind {+ b"IHDR" => {+ if len != 13 {+ return Err("a PNG IHDR is not 13 bytes".to_string());+ }+ width = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);+ height = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);+ let bit_depth = data[8];+ colour_type = data[9];+ let interlace = data[12];+ if bit_depth != 8 {+ return Err(format!("this decoder needs 8-bit PNG, got {bit_depth}-bit"));+ }+ if interlace != 0 {+ return Err("this decoder does not read interlaced PNG".to_string());+ }+ if colour_type != 2 && colour_type != 6 {+ return Err(format!(+ "this decoder reads RGB(2) or RGBA(6), got colour type {colour_type}"+ ));+ }+ seen_ihdr = true;+ }+ b"IDAT" => idat.extend_from_slice(data),+ b"IEND" => break,+ _ => {}+ }+ at = data_end + 4; // skip the trailing CRC+ }+ if !seen_ihdr {+ return Err("a PNG has no IHDR".to_string());+ }+ let channels: u8 = if colour_type == 6 { 4 } else { 3 };+ let raw = miniz_oxide::inflate::decompress_to_vec_zlib(&idat)+ .map_err(|e| format!("inflating IDAT failed: {e:?}"))?;+ unfilter(&raw, width, height, channels)+}++/// Reverse PNG's per-scanline filters into a flat pixel buffer. Each scanline is one filter byte+/// then `width * channels` bytes; filters 0..=4 are None, Sub, Up, Average and Paeth.+fn unfilter(raw: &[u8], width: u32, height: u32, channels: u8) -> Result<Image, String> {+ let ch = channels as usize;+ let stride = width as usize * ch;+ let expected = (stride + 1) * height as usize;+ if raw.len() < expected {+ return Err(format!("inflated PNG is {} bytes, expected {expected}", raw.len()));+ }+ let mut out = vec![0u8; stride * height as usize];+ for row in 0..height as usize {+ let filter = raw[row * (stride + 1)];+ let src = &raw[row * (stride + 1) + 1..row * (stride + 1) + 1 + stride];+ let (prev, cur) = out.split_at_mut(row * stride);+ let cur = &mut cur[..stride];+ let prev_row: &[u8] = if row == 0 { &[] } else { &prev[(row - 1) * stride..row * stride] };+ for i in 0..stride {+ let a = if i >= ch { cur[i - ch] as i32 } else { 0 };+ let b = if !prev_row.is_empty() { prev_row[i] as i32 } else { 0 };+ let c = if !prev_row.is_empty() && i >= ch { prev_row[i - ch] as i32 } else { 0 };+ let x = src[i] as i32;+ let value = match filter {+ 0 => x,+ 1 => x + a,+ 2 => x + b,+ 3 => x + (a + b) / 2,+ 4 => x + paeth(a, b, c),+ other => return Err(format!("unknown PNG filter {other}")),+ };+ cur[i] = (value & 0xff) as u8;+ }+ }+ Ok(Image { width, height, channels, pixels: out })+}++fn paeth(a: i32, b: i32, c: i32) -> i32 {+ let p = a + b - c;+ let (pa, pb, pc) = ((p - a).abs(), (p - b).abs(), (p - c).abs());+ if pa <= pb && pa <= pc {+ a+ } else if pb <= pc {+ b+ } else {+ c+ }+}++// --- slippy / web-mercator tile math ---++fn lon_to_tile_x(lon: f64, z: u8) -> f64 {+ (lon + 180.0) / 360.0 * (1u64 << z) as f64+}++fn lat_to_tile_y(lat: f64, z: u8) -> f64 {+ let r = lat.clamp(-85.05112878, 85.05112878).to_radians();+ (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64+}++fn tile_x_to_lon(x: f64, z: u8) -> f64 {+ x / (1u64 << z) as f64 * 360.0 - 180.0+}++fn tile_y_to_lat(y: f64, z: u8) -> f64 {+ let n = PI * (1.0 - 2.0 * y / (1u64 << z) as f64);+ n.sinh().atan().to_degrees()+}++// --- output ---++fn write_dataset(args: &Args, tiles: &[(u64, Vec<u16>)]) -> Result<(), String> {+ let mut out = Vec::with_capacity(16 + tiles.len() * (8 + args.dim as usize * args.dim as usize * 2));+ out.extend_from_slice(OUT_MAGIC);+ out.push(OUT_VERSION);+ out.push(args.out_zoom);+ out.extend_from_slice(&args.dim.to_le_bytes());+ out.extend_from_slice(&(tiles.len() as u32).to_le_bytes());+ for (id, grid) in tiles {+ out.extend_from_slice(&id.to_le_bytes());+ for &s in grid {+ out.extend_from_slice(&s.to_le_bytes());+ }+ }+ std::fs::write(&args.out, &out).map_err(|e| format!("writing {}: {e}", args.out.display()))+}++// --- CLI ---++fn parse_args() -> Result<Args, String> {+ let mut tiles_dir: Option<PathBuf> = None;+ let mut out: Option<PathBuf> = None;+ let mut out_zoom = 14u8;+ let mut dem_zoom = 12u8;+ let mut dim = 17u16;+ let mut bbox: Option<(f64, f64, f64, f64)> = None;+ let mut skip_flat = false;+ let mut it = std::env::args().skip(1);+ while let Some(a) = it.next() {+ match a.as_str() {+ "--tiles-dir" => tiles_dir = Some(PathBuf::from(next(&mut it, "--tiles-dir")?)),+ "--out" => out = Some(PathBuf::from(next(&mut it, "--out")?)),+ "--out-zoom" => out_zoom = next(&mut it, "--out-zoom")?.parse().map_err(|_| "--out-zoom must be a number")?,+ "--dem-zoom" => dem_zoom = next(&mut it, "--dem-zoom")?.parse().map_err(|_| "--dem-zoom must be a number")?,+ "--dim" => dim = next(&mut it, "--dim")?.parse().map_err(|_| "--dim must be a number")?,+ "--bbox" => bbox = Some(parse_bbox(&next(&mut it, "--bbox")?)?),+ "--skip-flat" => skip_flat = true,+ "-h" | "--help" => {+ print_help();+ std::process::exit(0);+ }+ other => return Err(format!("unknown argument {other} (try --help)")),+ }+ }+ Ok(Args {+ tiles_dir: tiles_dir.ok_or("--tiles-dir is required")?,+ out: out.ok_or("--out is required")?,+ out_zoom,+ dem_zoom,+ dim,+ bbox: bbox.ok_or("--bbox is required")?,+ skip_flat,+ })+}++fn next(it: &mut impl Iterator<Item = String>, flag: &str) -> Result<String, String> {+ it.next().ok_or_else(|| format!("{flag} needs a value"))+}++fn parse_bbox(s: &str) -> Result<(f64, f64, f64, f64), String> {+ let parts: Vec<f64> = s+ .split(',')+ .map(|p| p.trim().parse::<f64>().map_err(|_| format!("bad bbox component `{p}`")))+ .collect::<Result<_, _>>()?;+ match parts.as_slice() {+ [min_lon, min_lat, max_lon, max_lat] => Ok((*min_lon, *min_lat, *max_lon, *max_lat)),+ _ => Err("--bbox is minlon,minlat,maxlon,maxlat".to_string()),+ }+}++fn print_help() {+ println!(+ "dem_ingest --tiles-dir DIR --bbox minlon,minlat,maxlon,maxlat --out FILE\n\+ \n\+ Decode terrarium PNG tiles (laid out DIR/<z>/<x>/<y>.png) into a per-map-tile u16\n\+ heightmap grid dataset (metres + 32768 bias).\n\+ \n\+ Options:\n\+ \x20 --tiles-dir DIR directory of terrarium PNGs at the DEM zoom (required)\n\+ \x20 --bbox BOX minlon,minlat,maxlon,maxlat to cover (required)\n\+ \x20 --out FILE the .mdem dataset to write (required)\n\+ \x20 --out-zoom Z map tile zoom to sample a grid per (default 14)\n\+ \x20 --dem-zoom Z zoom the terrarium tiles were fetched at (default 12, ~30 m)\n\+ \x20 --dim N grid side length, N*N samples per tile (default 17)\n\+ \x20 --skip-flat omit tiles with no relief (ocean/flat), matching the wire format\n"+ );+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn terrarium_decode_puts_sea_level_at_the_bias() {+ // (128,0,0) is exactly 32768 raw, i.e. 0 m elevation → stored 32768.+ assert_eq!(terrarium_stored(128, 0, 0), 32768);+ // One metre up.+ assert_eq!(terrarium_stored(128, 1, 0), 32769);+ // A metre of sub-metre precision rounds up through the blue channel.+ assert_eq!(terrarium_stored(128, 0, 200), 32769);+ // The Dead Sea shore, ~-430 m, is below the bias.+ assert_eq!(terrarium_stored(126, 82, 0), 32338);+ // The clamp holds at the top rather than wrapping.+ assert_eq!(terrarium_stored(255, 255, 255), u16::MAX);+ }++ #[test]+ fn the_slippy_math_round_trips_a_tile_corner() {+ // A tile's top-left corner maps to a lon/lat that maps back to the tile origin.+ for z in [0u8, 8, 12, 14] {+ let (x, y) = (5u64.min((1 << z) - 1), 9u64.min((1 << z) - 1));+ let lon = tile_x_to_lon(x as f64, z);+ let lat = tile_y_to_lat(y as f64, z);+ assert!((lon_to_tile_x(lon, z) - x as f64).abs() < 1e-6, "z{z} lon round trip");+ assert!((lat_to_tile_y(lat, z) - y as f64).abs() < 1e-6, "z{z} lat round trip");+ }+ }++ #[test]+ fn unfilter_reverses_the_sub_filter() {+ // One 2x1 RGB scanline, filter 1 (Sub): the second pixel is a delta from the first.+ let width = 2;+ let height = 1;+ // filter byte 1, then pixel0 = (10,20,30), pixel1 delta = (1,2,3) → decodes to (11,22,33).+ let raw = vec![1u8, 10, 20, 30, 1, 2, 3];+ let img = unfilter(&raw, width, height, 3).expect("unfilter");+ assert_eq!(img.pixels, vec![10, 20, 30, 11, 22, 33]);+ }++ #[test]+ fn is_flat_omits_a_level_grid_but_keeps_relief() {+ assert!(is_flat(&vec![32768; 289]), "an all-sea-level grid is flat");+ let mut relief = vec![32768u16; 289];+ relief[100] = 32768 + 50;+ assert!(!is_flat(&relief), "50 m of relief is not flat");+ }+}
scripts/maps/harden_mamaps.sh
diff --git a/scripts/maps/harden_mamaps.sh b/scripts/maps/harden_mamaps.shindex 1d1a7a36f8..848d34d147 100644--- a/scripts/maps/harden_mamaps.sh+++ b/scripts/maps/harden_mamaps.sh@@ -5,7 +5,7 @@ # Run before publishing. # # Usage:-# ./harden_mamaps.sh --pbf california.osm.pbf --coastline land_polygons.shp [--out DIR] [--max-zoom 14]+# ./harden_mamaps.sh --pbf california.osm.pbf --coastline land_polygons.shp [--graph GRAPH_DIR] [--dem HEIGHTMAPS.mdem] [--out DIR] [--max-zoom 14] # # What it proves: #@@ -26,12 +26,16 @@ set -euo pipefail PBF="" COASTLINE=""+GRAPH=""+DEM="" OUT="${TMPDIR:-/tmp}/mamaps_harden" MAX_ZOOM=14 while [[ $# -gt 0 ]]; do case "$1" in --pbf) PBF="$2"; shift 2 ;; --coastline) COASTLINE="$2"; shift 2 ;;+ --graph) GRAPH="$2"; shift 2 ;;+ --dem) DEM="$2"; shift 2 ;; --out) OUT="$2"; shift 2 ;; --max-zoom) MAX_ZOOM="$2"; shift 2 ;; -h|--help) sed -n '2,26p' "$0"; exit 0 ;;@@ -47,6 +51,23 @@ done # the extract's bbox, so a state-sized extract keeps a few hundred polygons out of ~871k. [[ -n "$COASTLINE" ]] || { echo "harden_mamaps: --coastline is required" >&2; exit 2; } [[ -f "$COASTLINE" ]] || { echo "harden_mamaps: $COASTLINE does not exist" >&2; exit 1; }+# The v6 routing graph feeds the `traffic` layer (nodes/edges/intermediate/metadata.bin). Optional:+# without it the layer is simply empty. When given, every build below reads it so the archive and+# the traffic server derive identical component ids from the same graph.+GRAPH_ARG=()+if [[ -n "$GRAPH" ]]; then+ [[ -d "$GRAPH" ]] || { echo "harden_mamaps: graph dir $GRAPH does not exist" >&2; exit 1; }+ GRAPH_ARG=(--graph "$GRAPH")+fi+# The .mdem heightmap dataset (build_all.sh --dem writes $OUT_DIR/heightmaps.mdem) feeds the+# BODY_FLAG_HEIGHTMAP side table so the published archive carries 3D terrain. Optional: without it+# every tile stays flat (heightmap = None). Passed to every build below so all three rebuilds stay+# byte-identical with terrain in place.+DEM_ARG=()+if [[ -n "$DEM" ]]; then+ [[ -f "$DEM" ]] || { echo "harden_mamaps: dem $DEM does not exist" >&2; exit 1; }+ DEM_ARG=(--dem "$DEM")+fi HERE="$(cd "$(dirname "$0")" && pwd)" mkdir -p "$OUT"@@ -66,7 +87,8 @@ echo "== 1. byte-identical rebuilds at 1, 3 and 32 threads ==" HASHES=() for threads in 1 3 32; do RAYON_NUM_THREADS="$threads" "$BUILD" \- --input "$PBF" --out "$OUT/t$threads.mamaps" --max-zoom "$MAX_ZOOM" --coastline "$COASTLINE" >/dev/null+ --input "$PBF" --out "$OUT/t$threads.mamaps" --max-zoom "$MAX_ZOOM" --coastline "$COASTLINE" \+ "${GRAPH_ARG[@]+"${GRAPH_ARG[@]}"}" "${DEM_ARG[@]+"${DEM_ARG[@]}"}" >/dev/null h="$(sha "$OUT/t$threads.mamaps")" echo " $threads thread(s): ${h:0:16}" HASHES+=("$h")@@ -83,7 +105,8 @@ echo echo "== 2. a build id that follows its inputs ==" id_of() { "$DUMP" "$1" --mode header | awk -F'\t' '$1=="build_id"{print $2}'; } BASE_ID="$(id_of "$OUT/t1.mamaps")"-"$BUILD" --input "$PBF" --out "$OUT/shallow.mamaps" --max-zoom "$((MAX_ZOOM - 1))" --coastline "$COASTLINE" >/dev/null+"$BUILD" --input "$PBF" --out "$OUT/shallow.mamaps" --max-zoom "$((MAX_ZOOM - 1))" --coastline "$COASTLINE" \+ "${GRAPH_ARG[@]+"${GRAPH_ARG[@]}"}" "${DEM_ARG[@]+"${DEM_ARG[@]}"}" >/dev/null SHALLOW_ID="$(id_of "$OUT/shallow.mamaps")" echo " z0-$MAX_ZOOM $BASE_ID" echo " z0-$((MAX_ZOOM - 1)) $SHALLOW_ID"
scripts/maps/mamaps_build/src/coalesce.rs
diff --git a/scripts/maps/mamaps_build/src/coalesce.rs b/scripts/maps/mamaps_build/src/coalesce.rsindex 3ac8c09fad..8d7edcb561 100644--- a/scripts/maps/mamaps_build/src/coalesce.rs+++ b/scripts/maps/mamaps_build/src/coalesce.rs@@ -70,7 +70,7 @@ use std::collections::HashMap; -use tilecodec::mamaps::body::{Layer, Part, GEOM_LINE, WINDING_OUTER};+use tilecodec::mamaps::body::{BuildingAttrs, LaneTurns, Layer, Part, GEOM_LINE, WINDING_OUTER}; /// What coalescing a build saved, for the report. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]@@ -90,8 +90,10 @@ impl Stats { } } -/// What makes two line features interchangeable to a renderer.-type Class = (u16, u16, u8, u32, u8, u8, u8);+/// What makes two line features interchangeable to a renderer. The trailing `name_idx` keeps two+/// differently-named roads or rivers of the same class apart, so a curved label is never attached+/// to a line that merged with a neighbour of another name; same-named fragments still merge.+type Class = (u16, u16, u8, u32, u8, u8, u8, u8, u16); /// One line part, as `(coord_start, point_count)` into a layer's existing arena. ///@@ -107,16 +109,24 @@ type Run = Vec<Span>; /// Polygon features are left exactly as they were, in place; only the parts table and the arena are /// rebuilt around them, which [`crate::rings::normalise`] does immediately afterwards anyway. pub fn coalesce_lines(layer: &mut Layer) -> Stats {- coalesce_lines_with_ids(layer, None)+ coalesce_lines_with_ids(layer, None, None, None) } -/// As [`coalesce_lines`], but also rewrites an id side table so it stays parallel to the features.+/// As [`coalesce_lines`], but also rewrites an id side table and a turn-lane side table so they+/// stay parallel to the features. ///-/// The table is indexed by feature position, so merging lines without rewriting it leaves more ids-/// than features and the encoder rejects the tile. A merged line takes the id of the first feature-/// of its class, which is arbitrary — that is why only layers whose id-carrying features are *not*-/// lines populate the table at all (see `extract::tracks_ids`).-pub fn coalesce_lines_with_ids(layer: &mut Layer, ids: Option<&mut Vec<u64>>) -> Stats {+/// The tables are indexed by feature position, so merging lines without rewriting them leaves more+/// entries than features and the encoder rejects the tile. A merged line takes the id of the first+/// feature of its class, which is arbitrary — that is why only layers whose id-carrying features+/// are *not* lines populate the id table at all (see `extract::tracks_ids`). Turn masks are the+/// opposite: they belong to a *road* line, so a line that carries any is held out of merging+/// entirely (each becomes its own survivor) rather than folded into a neighbour and losing them.+pub fn coalesce_lines_with_ids(+ layer: &mut Layer,+ ids: Option<&mut Vec<u64>>,+ turns: Option<&mut Vec<LaneTurns>>,+ buildings: Option<&mut Vec<BuildingAttrs>>,+) -> Stats { let mut stats = Stats { features_before: layer.features.len() as u64, parts_before: layer.parts.len() as u64,@@ -131,12 +141,22 @@ pub fn coalesce_lines_with_ids(layer: &mut Layer, ids: Option<&mut Vec<u64>>) -> return stats; } + // A line that carries turn masks is never merged — its arrows belong to that exact segment —+ // so it is copied through at its position like a non-line. `false` everywhere when the layer+ // has no turn table, which is every layer but a `roads` tile that had `turn:lanes` in it.+ let unmergeable: Vec<bool> = match turns.as_deref() {+ Some(t) => layer.features.iter().enumerate().map(|(i, _)| {+ t.get(i).is_some_and(|lt| !lt.is_empty())+ }).collect(),+ None => vec![false; layer.features.len()],+ };+ // Every line part, grouped by class, in feature-then-part order. let mut order: Vec<Class> = Vec::new(); let mut group_of: HashMap<Class, usize> = HashMap::new(); let mut groups: Vec<Vec<Span>> = Vec::new();- for feature in &layer.features {- if feature.geom_type != GEOM_LINE {+ for (index, feature) in layer.features.iter().enumerate() {+ if feature.geom_type != GEOM_LINE || unmergeable[index] { continue; } let class = class_of(feature);@@ -156,15 +176,16 @@ pub fn coalesce_lines_with_ids(layer: &mut Layer, ids: Option<&mut Vec<u64>>) -> groups.iter().map(|parts| chain(parts, &layer.coords)).collect(); let mut features = Vec::with_capacity(layer.features.len() - lines + order.len());- // The original position of each surviving feature, for remapping the id table below.+ // The original position of each surviving feature, for remapping the side tables below. let mut kept: Vec<usize> = Vec::with_capacity(features.capacity()); let mut parts: Vec<Part> = Vec::with_capacity(layer.parts.len()); let mut coords: Vec<(i16, i16)> = Vec::with_capacity(layer.coords.len()); let mut emitted: Vec<bool> = vec![false; order.len()]; for (index, feature) in layer.features.iter().enumerate() {- if feature.geom_type != GEOM_LINE {- // Copied through at its original position, so a mixed layer keeps its feature order.+ if feature.geom_type != GEOM_LINE || unmergeable[index] {+ // Copied through at its original position, so a mixed layer keeps its feature order and+ // a turn-masked road keeps its own geometry and its arrows. let from = feature.parts_offset as usize; let start = parts.len() as u32; for part in &layer.parts[from..from + feature.part_count as usize] {@@ -219,6 +240,16 @@ pub fn coalesce_lines_with_ids(layer: &mut Layer, ids: Option<&mut Vec<u64>>) -> *ids = kept.iter().map(|&at| ids[at]).collect(); } }+ if let Some(turns) = turns {+ if !turns.is_empty() {+ *turns = kept.iter().map(|&at| turns[at].clone()).collect();+ }+ }+ if let Some(buildings) = buildings {+ if !buildings.is_empty() {+ *buildings = kept.iter().map(|&at| buildings[at]).collect();+ }+ } layer.features = features; layer.parts = parts;@@ -237,6 +268,8 @@ fn class_of(feature: &tilecodec::mamaps::body::Feature) -> Class { feature.transit_ordinal, feature.transit_lanes, feature.transit_taper,+ feature.lane_count,+ feature.name_idx, ) } @@ -343,6 +376,7 @@ mod tests { transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,+ lane_count: 0, }); } layer
scripts/maps/mamaps_build/src/dem.rs
diff --git a/scripts/maps/mamaps_build/src/dem.rs b/scripts/maps/mamaps_build/src/dem.rsnew file mode 100644index 0000000000..8ab3a19031--- /dev/null+++ b/scripts/maps/mamaps_build/src/dem.rs@@ -0,0 +1,281 @@+//! Load the `.mdem` heightmap dataset `dem_ingest` produced and hand the tiler one grid per output+//! tile — the second half of WS-G's build side, closing the gap the wire format left open.+//!+//! `dem_ingest` fetches AWS terrarium PNG tiles and downsamples them into one small square `u16`+//! grid per map tile at a single zoom (`--out-zoom`, default 14; `--dim`, default 17), each sample+//! `metres + 32768` row-major from the tile's top-left. That is exactly the layout+//! [`tilecodec::mamaps::body::Heightmap`] carries on the wire, so a tile at the dataset's own zoom+//! is a **verbatim copy** of its grid — no resample, byte for byte what the ingest computed.+//!+//! A tile at any other zoom is **resampled**: `dim * dim` points are sampled across the tile's own+//! extent (the same slippy walk `dem_ingest` does over the terrarium grid), each bilinearly+//! interpolated from the covering dataset grid. A tile with no data under it at all — off the fetch+//! coverage, or open ocean the ingest dropped with `--skip-flat` — yields `None`, so that tile omits+//! the section and stays 16-byte, matching the format's rule.++use std::collections::HashMap;+use std::f64::consts::PI;+use std::path::Path;++use tilecodec::mamaps::body::Heightmap;+use tilecodec::pmtiles::tile_id;+use tilecodec::proto::{err, Error, Result};++/// The `.mdem` dataset's magic and version, as `dem_ingest` writes them.+const MAGIC: &[u8; 4] = b"MDEM";+const VERSION: u8 = 1;++/// The biased `u16` for zero metres: sea level, and what a sample with no DEM under it reads as.+/// The same bias [`Heightmap`] and the terrarium source use.+const SEA_LEVEL: u16 = 32768;++/// A loaded `.mdem` dataset: one `u16` grid per output tile, keyed by pmtiles tile id at the+/// dataset's own zoom.+pub struct Dem {+ /// The zoom the grids were sampled at — the one a tile can copy verbatim rather than resample.+ out_zoom: u8,+ /// The grid side length, so every grid is `dim * dim` samples. Shared by every tile.+ dim: u16,+ /// `tile_id(out_zoom, x, y)` -> the tile's `dim * dim` samples, row-major from its top-left.+ grids: HashMap<u64, Vec<u16>>,+}++impl Dem {+ /// Read and parse a `.mdem` dataset from disk.+ pub fn load(path: &Path) -> Result<Dem> {+ let bytes = std::fs::read(path)+ .map_err(|e| Error(format!("reading the DEM dataset {}: {e}", path.display())))?;+ Dem::parse(&bytes)+ }++ /// Parse a `.mdem` dataset: a 12-byte header (`MDEM`, version, out_zoom, `dim` u16, tile count+ /// u32), then per tile a `u64` tile id and its `dim * dim` `u16` samples, little-endian.+ fn parse(bytes: &[u8]) -> Result<Dem> {+ if bytes.len() < 12 {+ return err("a .mdem dataset is shorter than its 12-byte header");+ }+ if &bytes[0..4] != MAGIC {+ return err("not a .mdem dataset (bad magic)");+ }+ if bytes[4] != VERSION {+ return err(format!("unsupported .mdem version {} (this build reads {VERSION})", bytes[4]));+ }+ let out_zoom = bytes[5];+ let dim = u16::from_le_bytes([bytes[6], bytes[7]]);+ if dim < 2 {+ return err("a .mdem grid dimension is less than 2");+ }+ let count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;+ let cells = dim as usize * dim as usize;+ // One tile: an 8-byte id then `cells` little-endian u16 samples.+ let stride = 8 + cells * 2;+ let mut at = 12usize;+ let mut grids = HashMap::with_capacity(count);+ for _ in 0..count {+ if at + stride > bytes.len() {+ return err("a .mdem tile runs past the end of the dataset");+ }+ let id = u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"));+ at += 8;+ let mut samples = Vec::with_capacity(cells);+ for i in 0..cells {+ let o = at + i * 2;+ samples.push(u16::from_le_bytes([bytes[o], bytes[o + 1]]));+ }+ at += cells * 2;+ grids.insert(id, samples);+ }+ Ok(Dem { out_zoom, dim, grids })+ }++ /// The heightmap for one output tile, or `None` when no DEM covers it (so the tile omits the+ /// section and stays 16-byte).+ ///+ /// A tile at the dataset's own zoom is a verbatim copy of its grid — byte for byte what the+ /// ingest sampled, independent of neighbour coverage. Any other zoom is resampled onto this+ /// tile's grid.+ pub fn heightmap_for(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {+ if z == self.out_zoom {+ let samples = self.grids.get(&tile_id(z, x, y))?;+ return Some(Heightmap { dim: self.dim, samples: samples.clone() });+ }+ self.resample(z, x, y)+ }++ /// Resample the dataset's grids onto one tile's `dim * dim` grid, sampling `dim * dim` points+ /// across the tile's own extent from its top-left — the same slippy walk `dem_ingest` runs over+ /// the terrarium grid, sourced from the loaded grids instead of PNGs.+ fn resample(&self, z: u8, x: u64, y: u64) -> Option<Heightmap> {+ let dim = self.dim as usize;+ let mut samples = Vec::with_capacity(dim * dim);+ let mut any = false;+ for row in 0..dim {+ let fy = y as f64 + row as f64 / (self.dim as f64 - 1.0);+ let lat = tile_y_to_lat(fy, z);+ for col in 0..dim {+ let fx = x as f64 + col as f64 / (self.dim as f64 - 1.0);+ let lon = tile_x_to_lon(fx, z);+ match self.sample_at(lon, lat) {+ Some(v) => {+ any = true;+ samples.push(v);+ }+ // No DEM here: sea level, as `dem_ingest` fills a missing terrarium pixel. A+ // tile entirely over missing DEM is dropped below.+ None => samples.push(SEA_LEVEL),+ }+ }+ }+ any.then_some(Heightmap { dim: self.dim, samples })+ }++ /// Build a dataset directly from grids, for tests that inject a synthetic DEM into the tiler+ /// rather than round-tripping bytes through disk.+ #[cfg(test)]+ pub(crate) fn from_grids(out_zoom: u8, dim: u16, grids: Vec<(u64, Vec<u16>)>) -> Dem {+ Dem { out_zoom, dim, grids: grids.into_iter().collect() }+ }++ /// The elevation at one lon/lat, bilinearly interpolated within the dataset grid that covers it,+ /// or `None` when that grid was not fetched.+ fn sample_at(&self, lon: f64, lat: f64) -> Option<u16> {+ let n = (1u64 << self.out_zoom) as f64;+ // The fractional tile position at the dataset zoom. Clamped so a point exactly on the+ // world's right/bottom edge lands in the last tile rather than one past it.+ let tx = lon_to_tile_x(lon, self.out_zoom).clamp(0.0, n - f64::EPSILON);+ let ty = lat_to_tile_y(lat, self.out_zoom).clamp(0.0, n - f64::EPSILON);+ let ix = tx.floor() as u64;+ let iy = ty.floor() as u64;+ let grid = self.grids.get(&tile_id(self.out_zoom, ix, iy))?;+ let last = self.dim as usize - 1;+ // The point's position within the tile's grid: the fraction across the tile scaled onto the+ // `dim - 1` cells between the grid's edge samples.+ let gx = (tx - ix as f64) * last as f64;+ let gy = (ty - iy as f64) * last as f64;+ let x0 = gx.floor() as usize;+ let y0 = gy.floor() as usize;+ let x1 = (x0 + 1).min(last);+ let y1 = (y0 + 1).min(last);+ let fx = gx - x0 as f64;+ let fy = gy - y0 as f64;+ let d = self.dim as usize;+ let at = |cx: usize, cy: usize| grid[cy * d + cx] as f64;+ let top = at(x0, y0) * (1.0 - fx) + at(x1, y0) * fx;+ let bot = at(x0, y1) * (1.0 - fx) + at(x1, y1) * fx;+ let v = top * (1.0 - fy) + bot * fy;+ Some(v.round().clamp(0.0, u16::MAX as f64) as u16)+ }+}++// --- slippy / web-mercator tile math, matching `dem_ingest` so a resample lands where the ingest+// would have sampled ---++fn lon_to_tile_x(lon: f64, z: u8) -> f64 {+ (lon + 180.0) / 360.0 * (1u64 << z) as f64+}++fn lat_to_tile_y(lat: f64, z: u8) -> f64 {+ let r = lat.clamp(-85.05112878, 85.05112878).to_radians();+ (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64+}++fn tile_x_to_lon(x: f64, z: u8) -> f64 {+ x / (1u64 << z) as f64 * 360.0 - 180.0+}++fn tile_y_to_lat(y: f64, z: u8) -> f64 {+ let n = PI * (1.0 - 2.0 * y / (1u64 << z) as f64);+ n.sinh().atan().to_degrees()+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Serialise a synthetic `.mdem` dataset the way `dem_ingest` does, for the parser to read back.+ fn dataset(out_zoom: u8, dim: u16, tiles: &[(u64, Vec<u16>)]) -> Vec<u8> {+ let mut out = Vec::new();+ out.extend_from_slice(MAGIC);+ out.push(VERSION);+ out.push(out_zoom);+ out.extend_from_slice(&dim.to_le_bytes());+ out.extend_from_slice(&(tiles.len() as u32).to_le_bytes());+ for (id, grid) in tiles {+ out.extend_from_slice(&id.to_le_bytes());+ for &s in grid {+ out.extend_from_slice(&s.to_le_bytes());+ }+ }+ out+ }++ /// A ramp grid whose sample at `(col, row)` is `32768 + row * 10 + col`, so a read-back can name+ /// which cell it got.+ fn ramp(dim: u16) -> Vec<u16> {+ let d = dim as usize;+ let mut g = Vec::with_capacity(d * d);+ for row in 0..d {+ for col in 0..d {+ g.push(SEA_LEVEL + (row * 10 + col) as u16);+ }+ }+ g+ }++ #[test]+ fn a_tile_at_the_datasets_zoom_is_a_verbatim_copy() {+ let (z, dim) = (14u8, 17u16);+ let (x, y) = (2730u64, 6335u64);+ let grid = ramp(dim);+ let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), grid.clone())])).expect("parse");+ let hm = dem.heightmap_for(z, x, y).expect("a heightmap for the covered tile");+ assert_eq!(hm.dim, dim);+ assert_eq!(hm.samples, grid, "the grid is copied byte for byte at the dataset's own zoom");+ // And it reads back through the wire type's own accessor.+ assert_eq!(hm.sample(0, 0), Some(SEA_LEVEL));+ assert_eq!(hm.sample(3, 2), Some(SEA_LEVEL + 23));+ assert_eq!(Heightmap::metres(hm.sample(3, 2).unwrap()), 23);+ assert_eq!(hm.sample(dim, 0), None, "out of range");+ }++ #[test]+ fn a_tile_off_coverage_has_no_heightmap() {+ let (z, dim) = (14u8, 17u16);+ let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, 10, 10), ramp(dim))])).expect("parse");+ assert!(dem.heightmap_for(z, 999, 999).is_none(), "an uncovered tile omits the section");+ }++ /// A coarser tile resamples from the covering grids. Sampled over a tile whose whole extent is+ /// covered, a flat field must come back flat and non-empty.+ #[test]+ fn a_coarser_tile_resamples_within_range() {+ let (oz, dim) = (14u8, 17u16);+ // A z13 tile's dim*dim points span its three edge columns/rows of z14 tiles: x in+ // 2730..=2732 and y in 6334..=6336 for z13 (1365, 3167). Cover that whole 3x3 block so no+ // sample point falls off coverage (which would read as sea level).+ let flat: Vec<u16> = vec![SEA_LEVEL + 100; dim as usize * dim as usize];+ let mut tiles = Vec::new();+ for cx in 2730..=2732u64 {+ for cy in 6334..=6336u64 {+ tiles.push((tile_id(oz, cx, cy), flat.clone()));+ }+ }+ let dem = Dem::parse(&dataset(oz, dim, &tiles)).expect("parse");+ let hm = dem.heightmap_for(13, 1365, 3167).expect("a resampled heightmap");+ assert_eq!(hm.dim, dim);+ assert!(+ hm.samples.iter().all(|&s| s == SEA_LEVEL + 100),+ "resampling a flat 100 m field is still 100 m everywhere",+ );+ }++ #[test]+ fn a_short_dataset_is_refused() {+ assert!(Dem::parse(b"MDE").is_err(), "shorter than the header");+ assert!(Dem::parse(b"XXXX\x01\x0e\x11\x00\x00\x00\x00\x00").is_err(), "bad magic");+ // A header claiming one tile with no tile bytes behind it.+ let mut short = dataset(14, 17, &[]);+ short[8] = 1; // claim one tile+ assert!(Dem::parse(&short).is_err(), "a claimed tile past the end is refused");+ }+}
scripts/maps/mamaps_build/src/extract.rs
diff --git a/scripts/maps/mamaps_build/src/extract.rs b/scripts/maps/mamaps_build/src/extract.rsindex 2723516f28..f6057b2960 100644--- a/scripts/maps/mamaps_build/src/extract.rs+++ b/scripts/maps/mamaps_build/src/extract.rs@@ -56,6 +56,8 @@ use rayon::prelude::*; use crate::schema::{self, Class, Layers}; use crate::store::{Sink, Store, WayCounts, WayReader, WaySink};+use tilecodec::mamaps::body::BuildingAttrs;+use tilecodec::mamaps::dict::LAYER_BUILDINGS; /// One classified feature, in lon/lat, ready to tile. ///@@ -78,6 +80,20 @@ pub struct Feature { pub transit_ordinal: u8, pub transit_lanes: u8, pub transit_taper: u8,+ /// A `roads` feature's carriageway lane count, zero for every other layer and for a road with+ /// no `lanes` tag. Baked into the body feature so the renderer can draw the carriageway as its+ /// individual lanes at high zoom. See [`crate::schema::roads::lane_count`].+ pub lane_count: u8,+ /// A road's per-lane turn-indication masks, `(forward, backward)`, left to right — the+ /// `LANE_*` bits of OSM `turn:lanes[:forward|:backward]`. Empty for every other layer and for+ /// a road with no `turn:lanes`. Baked into the body's turn-lane side table so the renderer can+ /// draw per-lane arrows at junctions. See [`crate::schema::roads::turn_masks`].+ pub turn_fwd: Vec<u16>,+ pub turn_bwd: Vec<u16>,+ /// A building's OSM Simple 3D Buildings attributes (height, roof, colours), `None` for every+ /// non-building feature. Baked into the body's building side table so the renderer can extrude+ /// the footprint in 3D. See [`crate::schema::buildings::attrs`].+ pub building: Option<BuildingAttrs>, } /// The id space an [`Feature::id`] came from, in the low two bits.@@ -115,6 +131,8 @@ pub struct Stats { pub nodes_classified: u64, /// Coloured rail lines read from a prepared GTFS transit-routes export, if one was given. pub transit_routes: u64,+ /// Drivable component segments emitted into the `traffic` layer from the v6 routing graph.+ pub traffic_segments: u64, /// Road ways whose `min_zoom` was pulled shallower to match their corridor. pub corridor_promotions: u64, pub rings: RingStats,@@ -126,6 +144,16 @@ struct Way { refs: Vec<i64>, /// The display label for `places`/`poi` ways, `None` for every other layer. name: Option<String>,+ /// A road's carriageway lane count, zero for every other layer and for a road with no `lanes`+ /// tag. See [`crate::schema::roads::lane_count`].+ lane_count: u8,+ /// A road's per-lane turn masks `(forward, backward)`; empty otherwise. See+ /// [`crate::schema::roads::turn_masks`].+ turn_fwd: Vec<u16>,+ turn_bwd: Vec<u16>,+ /// A building's S3DB attributes, `None` for every non-building. See+ /// [`crate::schema::buildings::attrs`].+ building: Option<BuildingAttrs>, } /// A classified relation, held between passes.@@ -142,6 +170,8 @@ struct Relation { name: Option<String>, /// The relation's own OSM id, tagged — see [`tagged_id`]. Only read for label relations. id: i64,+ /// A building relation's S3DB attributes (a multipolygon `building=*`), `None` otherwise.+ building: Option<BuildingAttrs>, } /// Read `input` and spill every feature the schema classifies to `spill_path`.@@ -154,6 +184,7 @@ pub fn extract( layers: Layers, coastline: Option<&Path>, transit_routes: Option<&Path>,+ graph: Option<&Path>, spill_path: &Path, ) -> Result<(Store, Stats)> { // Stage A's boundaries are printed with their elapsed time so an external RSS sampler can say@@ -227,7 +258,41 @@ pub fn extract( } } let name = schema::display_name(&way.tags, class.layer);- state.0.push((way.id, Way { class, refs: way.refs.to_vec(), name }));+ // A road's carriageway lane count and per-lane turn masks, baked so the+ // renderer can draw the lanes individually and place turn arrows. Zero+ // and empty for every other layer.+ let is_road =+ class.layer == tilecodec::mamaps::dict::LAYER_ROADS;+ let lane_count = if is_road {+ schema::roads::lane_count(&way.tags)+ } else {+ 0+ };+ let (turn_fwd, turn_bwd) = if is_road {+ schema::roads::turn_masks(&way.tags)+ } else {+ (Vec::new(), Vec::new())+ };+ // A building's S3DB attributes, parsed once here beside its class.+ // Zero-cost for the overwhelming majority of ways, which are not+ // buildings.+ let building = if class.layer == LAYER_BUILDINGS {+ Some(schema::buildings::attrs(&way.tags))+ } else {+ None+ };+ state.0.push((+ way.id,+ Way {+ class,+ refs: way.refs.to_vec(),+ name,+ lane_count,+ turn_fwd,+ turn_bwd,+ building,+ },+ )); } } Element::Relation(relation) => {@@ -255,6 +320,13 @@ pub fn extract( // distinction `Class::area` exists to make. let area = class.area; let name = schema::display_name(&relation.tags, class.layer);+ // A multipolygon building (a footprint with a courtyard) carries S3DB+ // attributes just as a building way does.+ let building = if class.layer == LAYER_BUILDINGS {+ Some(schema::buildings::attrs(&relation.tags))+ } else {+ None+ }; // An administrative relation yields *two* features: the border, which // is a line and is what the basemap draws, and the region's shape, // which nothing draws and the region mask reads. They cannot be one@@ -270,10 +342,18 @@ pub fn extract( area: true, name: name.clone(), id: relation.id,+ building: None, }); } }- state.1.push(Relation { class, members, area, name, id: relation.id });+ state.1.push(Relation {+ class,+ members,+ area,+ name,+ id: relation.id,+ building,+ }); } } Element::Node(_) => {}@@ -287,7 +367,16 @@ pub fn extract( // leaves the file in ascending id order. `WaySink::push` refuses an id that does not // advance rather than letting an unsorted file reorder the archive silently. for (id, way) in chunk_ways {- ways.push(id, &way.class, &way.refs, way.name.as_deref())?;+ ways.push(+ id,+ &way.class,+ &way.refs,+ way.name.as_deref(),+ way.lane_count,+ &way.turn_fwd,+ &way.turn_bwd,+ way.building,+ )?; } relations.extend(chunk_relations); corridors.extend(chunk_corridors);@@ -467,12 +556,12 @@ pub fn extract( // 64 Ki ways at ~10 nodes each is a few tens of MB of geometry in flight, against a build that // peaks near 7 GB. const MATERIALISE_BATCH: usize = 64 * 1024;- let mut batch: Vec<(Class, Option<String>, Vec<i64>, u64)> =+ let mut batch: Vec<(Class, Option<String>, Vec<i64>, u64, u8, Vec<u16>, Vec<u16>, Option<BuildingAttrs>)> = Vec::with_capacity(MATERIALISE_BATCH); let mut built: Vec<Option<Geometry<(f64, f64)>>> = Vec::with_capacity(MATERIALISE_BATCH); loop { let more = reader.next(&mut refs)?;- if let Some((id, class, name)) = more.as_ref() {+ if let Some((id, class, name, lane_count, turn_fwd, turn_bwd, building)) = more.as_ref() { let mut class = *class; // The corridor's zoom, where it is shallower than this way's own. if let Ok(at) = promoted.binary_search_by_key(id, |(id, _)| *id) {@@ -486,7 +575,16 @@ pub fn extract( } else { tilecodec::mamaps::body::ID_NONE };- batch.push((class, name.clone(), std::mem::take(&mut refs), id));+ batch.push((+ class,+ name.clone(),+ std::mem::take(&mut refs),+ id,+ *lane_count,+ turn_fwd.clone(),+ turn_bwd.clone(),+ *building,+ )); } // Flushed when full, and once more at the end with whatever is left. if batch.len() >= MATERIALISE_BATCH || (more.is_none() && !batch.is_empty()) {@@ -494,7 +592,7 @@ pub fn extract( par::install(|| { batch .par_iter()- .map(|(class, _, refs, _)| {+ .map(|(class, _, refs, _, _, _, _, _)| { let line = table.line(refs); // A label layer's ways are centroided to points: a town mapped as an area // is still one label, not a loop. Everything else keeps its geometry.@@ -506,10 +604,27 @@ pub fn extract( }) .collect_into_vec(&mut built); });- for ((class, name, _, id), geometry) in batch.iter().zip(built.drain(..)) {+ for ((class, name, _, id, lane_count, turn_fwd, turn_bwd, building), geometry) in+ batch.iter().zip(built.drain(..))+ { match geometry { Some(geometry) => {- sink.push_named(class, &geometry, name.as_deref(), *id)?;+ // A building carries its S3DB attributes; a road with lane data carries+ // those; everything else — and a plain road — goes the plain, named way.+ if let Some(b) = building {+ sink.push_building(class, &geometry, name.as_deref(), *b)?;+ } else if *lane_count > 0 || !turn_fwd.is_empty() || !turn_bwd.is_empty() {+ sink.push_road(+ class,+ &geometry,+ name.as_deref(),+ *lane_count,+ turn_fwd,+ turn_bwd,+ )?;+ } else {+ sink.push_named(class, &geometry, name.as_deref(), *id)?;+ } stats.features += 1; } None => stats.geometry_failed += 1,@@ -596,7 +711,13 @@ pub fn extract( } else { tilecodec::mamaps::body::ID_NONE };- sink.push_named(&relation.class, &Geometry::Polygons(polygons), None, id)?;+ // A multipolygon building carries its S3DB attributes into the building side table, just+ // as a building way does.+ if let Some(building) = relation.building {+ sink.push_building(&relation.class, &Geometry::Polygons(polygons), None, building)?;+ } else {+ sink.push_named(&relation.class, &Geometry::Polygons(polygons), None, id)?;+ } stats.features += 1; } bar.finish("relation(s)");@@ -639,6 +760,16 @@ pub fn extract( } } }+ // The `traffic` layer, last of the non-OSM sources: its geometry is the v6 routing graph+ // (see [`schema::traffic`]), read straight off disk rather than classified from the `.pbf`.+ // Not clipped to the bbox here — the graph is already the built region, and the tiler clips+ // each component segment per tile like any other line.+ if let Some(dir) = graph {+ println!("reading the v6 routing graph at {} for the traffic layer", dir.display());+ stats.traffic_segments = schema::traffic::stream_graph(dir, &mut sink)?;+ stats.features += stats.traffic_segments;+ println!(" {} drivable component segment(s)", stats.traffic_segments);+ } let store = sink.finish(spill_path)?; // The one phase that had no mark after it, and it turned out to be the largest single item in the // build outside tiling: ~25 s of a 136 s California run. It is 170 M coordinate lookups through@@ -822,7 +953,9 @@ pub(crate) fn is_label(layer: u8) -> bool { /// position: every feature in such a layer needs an entry, `ID_NONE` included, or the table stops /// lining up with the features it describes. pub(crate) fn layer_tracks_ids(layer: u8) -> bool {- is_label(layer) || layer == tilecodec::mamaps::dict::LAYER_BOUNDARIES+ is_label(layer)+ || layer == tilecodec::mamaps::dict::LAYER_BOUNDARIES+ || layer == tilecodec::mamaps::dict::LAYER_TRAFFIC } /// May this feature carry a non-zero id?@@ -838,8 +971,10 @@ pub(crate) fn layer_tracks_ids(layer: u8) -> bool { /// line and must not. `coalesce` merges adjacent border lines, and the survivor's id would be /// whichever member happened to come first. pub(crate) fn tracks_ids(class: &crate::schema::Class) -> bool {- use tilecodec::mamaps::dict::LAYER_BOUNDARIES;- is_label(class.layer) || (class.layer == LAYER_BOUNDARIES && class.area)+ use tilecodec::mamaps::dict::{LAYER_BOUNDARIES, LAYER_TRAFFIC};+ is_label(class.layer)+ || (class.layer == LAYER_BOUNDARIES && class.area)+ || class.layer == LAYER_TRAFFIC } /// The centroid of a coordinate list: the arithmetic mean, or `None` when there is nothing.@@ -954,7 +1089,7 @@ mod tests { // Ascending way ids, as pass 1 produces; overlapping refs, as real ways have. for way in 0..64i64 { let refs: Vec<i64> = (0..8).map(|i| way * 5 + i).collect();- sink.push(way + 1, &class, &refs, None).expect("push");+ sink.push(way + 1, &class, &refs, None, 0, &[], &[], None).expect("push"); } let counts = sink.finish().expect("finish");
scripts/maps/mamaps_build/src/main.rs
diff --git a/scripts/maps/mamaps_build/src/main.rs b/scripts/maps/mamaps_build/src/main.rsindex fb53b2da20..a8a10c0e69 100644--- a/scripts/maps/mamaps_build/src/main.rs+++ b/scripts/maps/mamaps_build/src/main.rs@@ -32,6 +32,7 @@ use std::process::ExitCode; mod coalesce; mod corridor;+mod dem; mod extract; mod rings; mod shapefile;@@ -98,6 +99,8 @@ fn main() -> ExitCode { let mut build_id: Option<u64> = None; let mut coastline: Option<PathBuf> = None; let mut transit_routes: Option<PathBuf> = None;+ let mut graph: Option<PathBuf> = None;+ let mut dem: Option<PathBuf> = None; let mut i = 1; while i < args.len() {@@ -133,6 +136,14 @@ fn main() -> ExitCode { transit_routes = Some(PathBuf::from(v)); 2 }),+ "--graph" => value("--graph").map(|v| {+ graph = Some(PathBuf::from(v));+ 2+ }),+ "--dem" => value("--dem").map(|v| {+ dem = Some(PathBuf::from(v));+ 2+ }), "--layers" => value("--layers").and_then(|v| { layers = schema::Layers::parse(&v)?; Ok(2)@@ -185,6 +196,8 @@ fn main() -> ExitCode { reuse_store, coastline, transit_routes,+ graph,+ dem, layers, min_zoom, max_zoom,@@ -209,6 +222,14 @@ struct RunSettings { /// A prepared GTFS export for `transit`'s coloured rail lines. Without it the layer is empty: /// nothing in the `.osm.pbf` produces one. transit_routes: Option<PathBuf>,+ /// The v6 routing graph directory (`nodes.bin`/`edges.bin`/`intermediate.bin`/`metadata.bin`)+ /// for `traffic`'s per-component lines. Without it the layer is empty: its geometry is the+ /// graph, not the `.osm.pbf`.+ graph: Option<PathBuf>,+ /// The `.mdem` heightmap dataset `dem_ingest` produced (via `build_all.sh --dem`). Without it+ /// every tile's `heightmap` stays `None` and the archive is a valid v6 with no terrain grids;+ /// with it, each output tile carries the DEM grid sampled to its own z/x/y.+ dem: Option<PathBuf>, layers: schema::Layers, min_zoom: u8, max_zoom: u8,@@ -244,11 +265,23 @@ fn run( "no --transit-routes given, so `transit` is empty; its lines come from GTFS, not the .pbf" ); }+ // The same asymmetry once more, for the traffic layer's graph source: the flag without the+ // layer is a mistake worth stopping for, the layer without the flag is a legitimate build of+ // an archive with no traffic overlay.+ if run.graph.is_some() && !layers.traffic {+ return Err("--graph was given but the traffic layer is not selected".to_string());+ }+ if run.graph.is_none() && layers.traffic {+ println!(+ "no --graph given, so `traffic` is empty; its lines come from the v6 routing graph, not the .pbf"+ );+ } let provenance = store::Provenance::of( input, layers, run.coastline.is_some(), run.transit_routes.is_some(),+ run.graph.is_some(), ) .map_err(|e| e.to_string())?; // Stage A is most of a large build -- 17.6 minutes of a north-america run, and identical every@@ -270,6 +303,7 @@ fn run( layers, run.coastline.as_deref(), run.transit_routes.as_deref(),+ run.graph.as_deref(), &spill, ) .map_err(|e| format!("{}: {e}", input.display()))?;@@ -292,6 +326,12 @@ fn run( if stats.transit_routes > 0 { println!(" including {} coloured transit route(s) from GTFS", stats.transit_routes); }+ if stats.traffic_segments > 0 {+ println!(+ " including {} drivable component segment(s) for the traffic layer",+ stats.traffic_segments,+ );+ } if stats.corridor_promotions > 0 { println!( " {} road way(s) pulled to their corridor's zoom",@@ -317,9 +357,21 @@ fn run( simplification, stats.features, run.transit_routes.is_some(),+ run.graph.is_some(), ) }); + // The DEM heightmap dataset, if one was fetched. Loaded here (this is where I/O belongs) and+ // handed to the tiler, which samples one grid per output tile into the body's heightmap section.+ let dem = match run.dem.as_deref() {+ Some(path) => {+ let dem = dem::Dem::load(path).map_err(|e| e.to_string())?;+ println!("loaded the DEM dataset at {}", path.display());+ Some(dem)+ }+ None => None,+ };+ let settings = tiler::Settings { min_zoom, max_zoom,@@ -331,6 +383,7 @@ fn run( // `tiler::add_ocean`. The green-over-water problem it existed to solve is handled in the // style instead, by not painting marine protected areas green in the first place. ocean: false,+ dem, }; let (bytes, per_zoom) = tiler::build(&store, &settings).map_err(|e| e.to_string())?; tiler::check_not_empty(&per_zoom).map_err(|e| e.to_string())?;@@ -473,6 +526,7 @@ fn derive_build_id( simplification: f64, features: u64, transit_routes: bool,+ graph: bool, ) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; let mut eat = |bytes: &[u8]| {@@ -481,6 +535,11 @@ fn derive_build_id( h = h.wrapping_mul(0x100_0000_01b3); } };+ // Revision 12: `.mamaps` v4. A `traffic` layer (id 10) is baked from the v6 routing graph —+ // one line per drivable component segment, each carrying its packed `component_id` in the+ // body id table — and `FORMAT_VERSION` bumps 3->4. The layer set and the format both move, so+ // a warm cache must miss.+ // // Revision 11: the `boundaries` layer populates the id side table, so a region's shape carries // its OSM relation id. Without it a region is an anonymous polygon per tile and nothing says // which pieces belong to the same region, so a mask could only ever punch out the one tile@@ -523,7 +582,7 @@ fn derive_build_id( // Revision 3: road `min_zoom` is decided per corridor (`corridor`), and place // `kind_detail` carries the reference basemap's 0-15 population rank rather than a // three-step one (`schema::places::rank_of`).- eat(b"mamaps_build/11");+ eat(b"mamaps_build/12"); eat(input.to_string_lossy().as_bytes()); if let Ok(meta) = std::fs::metadata(input) { eat(&meta.len().to_le_bytes());@@ -544,11 +603,14 @@ fn derive_build_id( u8::from(layers.places), u8::from(layers.poi), u8::from(layers.transit),+ u8::from(layers.traffic), min_zoom, max_zoom, // A build with a transit-routes file and one without carry different layers from the // same `.pbf`, and readers cache byte ranges under `(url, build_id)`. u8::from(transit_routes),+ // Likewise a build with a graph carries the whole traffic layer that one without does not.+ u8::from(graph), ]); eat(&simplification.to_le_bytes()); eat(&features.to_le_bytes());@@ -615,6 +677,8 @@ fn usage() { \x20 [--min-zoom N] [--max-zoom N]\n\ \x20 [--coastline LAND.shp|LAND.geojsonseq]\n\ \x20 [--transit-routes ROUTES.geojsonseq]\n\+ \x20 [--graph GRAPH_DIR]\n\+ \x20 [--dem HEIGHTMAPS.mdem]\n\ \x20 [--simplification F] [--build-id N] [--report FILE]\n\ \x20 [--keep-store] [--reuse-store]\n\ \n\@@ -698,15 +762,17 @@ mod tests { fn a_build_id_follows_the_inputs_that_decide_the_output() { let path = std::path::Path::new("nonexistent.osm.pbf"); let all = schema::Layers::all();- let base = derive_build_id(path, all, 0, 14, 1.0, 100, false);- assert_eq!(base, derive_build_id(path, all, 0, 14, 1.0, 100, false), "stable");+ let base = derive_build_id(path, all, 0, 14, 1.0, 100, false, false);+ assert_eq!(base, derive_build_id(path, all, 0, 14, 1.0, 100, false, false), "stable"); for other in [- derive_build_id(path, all, 1, 14, 1.0, 100, false),- derive_build_id(path, all, 0, 15, 1.0, 100, false),- derive_build_id(path, all, 0, 14, 2.0, 100, false),- derive_build_id(path, all, 0, 14, 1.0, 101, false),+ derive_build_id(path, all, 1, 14, 1.0, 100, false, false),+ derive_build_id(path, all, 0, 15, 1.0, 100, false, false),+ derive_build_id(path, all, 0, 14, 2.0, 100, false, false),+ derive_build_id(path, all, 0, 14, 1.0, 101, false, false), // A transit-routes file adds a whole layer the same `.pbf` would not produce.- derive_build_id(path, all, 0, 14, 1.0, 100, true),+ derive_build_id(path, all, 0, 14, 1.0, 100, true, false),+ // A routing graph adds the traffic layer the same `.pbf` would not produce.+ derive_build_id(path, all, 0, 14, 1.0, 100, false, true), derive_build_id( path, schema::Layers { water: true, ..schema::Layers::none() },@@ -715,6 +781,7 @@ mod tests { 1.0, 100, false,+ false, ), derive_build_id( std::path::Path::new("other.osm.pbf"),@@ -724,6 +791,7 @@ mod tests { 1.0, 100, false,+ false, ), ] { assert_ne!(base, other, "a changed input should change the id");
scripts/maps/mamaps_build/src/rings.rs
diff --git a/scripts/maps/mamaps_build/src/rings.rs b/scripts/maps/mamaps_build/src/rings.rsindex e6334989e7..4443ff8d5b 100644--- a/scripts/maps/mamaps_build/src/rings.rs+++ b/scripts/maps/mamaps_build/src/rings.rs@@ -30,7 +30,7 @@ //! wedge across a continent, which is visible and inexplicable. So a hole that cannot be placed //! cleanly is **dropped and counted**, and the count is in the build report. -use tilecodec::mamaps::body::{Layer, Part, WINDING_HOLE, WINDING_OUTER};+use tilecodec::mamaps::body::{BuildingAttrs, LaneTurns, Layer, Part, WINDING_HOLE, WINDING_OUTER}; /// What normalising a build cost, for the report. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]@@ -64,16 +64,23 @@ impl Stats { /// Rebuilds the parts table and the coordinate arena, because dropping a ring changes both and the /// encoder requires the parts to tile the arena exactly. pub fn normalise(layer: &mut Layer) -> Stats {- normalise_with_ids(layer, None)+ normalise_with_ids(layer, None, None, None) } -/// As [`normalise`], but also drops the id of any feature it drops.+/// As [`normalise`], but also drops the id and turn-lane records of any feature it drops. ///-/// The id table is indexed by feature position, so the retain at the end has to happen to both or-/// every id after the first casualty describes the wrong feature. This only started mattering when-/// `boundaries` gained a table: `places` and `poi` are points, and a point never loses its single-/// part, so the retain was a no-op for every layer that carried ids.-pub fn normalise_with_ids(layer: &mut Layer, ids: Option<&mut Vec<u64>>) -> Stats {+/// The side tables are indexed by feature position, so the retain at the end has to happen to all+/// of them or every entry after the first casualty describes the wrong feature. This only started+/// mattering when `boundaries` gained a table: `places` and `poi` are points, and a point never+/// loses its single part, so the retain was a no-op for every layer that carried ids. A road's+/// turn table rides along for the same discipline, though a road is a line and a line is never+/// dropped here.+pub fn normalise_with_ids(+ layer: &mut Layer,+ ids: Option<&mut Vec<u64>>,+ turns: Option<&mut Vec<LaneTurns>>,+ buildings: Option<&mut Vec<BuildingAttrs>>,+) -> Stats { let mut stats = Stats::default(); let mut parts: Vec<Part> = Vec::with_capacity(layer.parts.len()); let mut coords: Vec<(i16, i16)> = Vec::with_capacity(layer.coords.len());@@ -187,6 +194,28 @@ pub fn normalise_with_ids(layer: &mut Layer, ids: Option<&mut Vec<u64>>) -> Stat }); } }+ if let Some(turns) = turns {+ if turns.len() == layer.features.len() {+ let mut at = 0;+ turns.retain(|_| {+ let keep = layer.features[at].part_count > 0;+ at += 1;+ keep+ });+ }+ }+ // The building side table is indexed by feature position too, so a dropped degenerate building+ // must drop its attrs with it, in the same order and by the same predicate.+ if let Some(buildings) = buildings {+ if buildings.len() == layer.features.len() {+ let mut at = 0;+ buildings.retain(|_| {+ let keep = layer.features[at].part_count > 0;+ at += 1;+ keep+ });+ }+ } layer.features.retain(|feature| feature.part_count > 0); layer.parts = parts; layer.coords = coords;@@ -404,6 +433,7 @@ mod tests { transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,+ lane_count: 0, }); for (index, ring) in rings.iter().enumerate() { layer.parts.push(Part {@@ -453,6 +483,7 @@ mod tests { transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,+ lane_count: 0, }); layer.parts.push(Part { coord_start: layer.coords.len() as u32,@@ -466,7 +497,7 @@ mod tests { push(square(200, 200, 100)); let mut ids = vec![11u64, 22, 33];- normalise_with_ids(&mut layer, Some(&mut ids));+ normalise_with_ids(&mut layer, Some(&mut ids), None, None); assert_eq!(layer.features.len(), 2, "the collapsed exterior is dropped"); assert_eq!(ids, vec![11, 33], "and its id goes with it, not the one after it");@@ -570,6 +601,7 @@ mod tests { transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,+ lane_count: 0, }); layer.parts.push(Part { coord_start: 0, point_count: 3, winding: WINDING_OUTER }); layer.coords = vec![(0, 0), (50, 0), (50, 50)];@@ -618,6 +650,9 @@ mod tests { layers: vec![layer], names: Vec::new(), ids: Vec::new(),+ turn_lanes: Vec::new(),+ buildings: Vec::new(),+ heightmap: None, carriageways: Vec::new(), convention: None, }; // The encoder's own contiguity check, which is the real proof. assert!(tilecodec::mamaps::body::serialize(&body).is_ok());@@ -646,7 +681,10 @@ mod tests { // A hole, wound the same way as its exterior, which stage C has to reverse. ring(-120.2, 35.2, 0.3), ]]),- name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,+ name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,+ turn_fwd: Vec::new(),+ turn_bwd: Vec::new(),+ building: None, }, crate::extract::Feature { class: Class::area(dict::LAYER_WATER, crate::schema::kind("water"), 0),@@ -655,7 +693,10 @@ mod tests { // A hole nowhere near its exterior, which stage C has to drop. ring(-100.0, 20.0, 0.1), ]]),- name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0,+ name: None, id: tilecodec::mamaps::body::ID_NONE, transit_color: 0, transit_ordinal: 0, transit_lanes: 0, transit_taper: 0, lane_count: 0,+ turn_fwd: Vec::new(),+ turn_bwd: Vec::new(),+ building: None, }, ]; let settings = crate::tiler::Settings {@@ -666,6 +707,7 @@ mod tests { scratch: std::env::temp_dir() .join(format!("mamaps_rings_{}.tilechunks", std::process::id())), ocean: false,+ dem: None, }; let store = crate::store::Store::of(&features).expect("spill"); let (bytes, stats) = crate::tiler::build(&store, &settings).expect("build");
scripts/maps/mamaps_build/src/schema/buildings.rs
diff --git a/scripts/maps/mamaps_build/src/schema/buildings.rs b/scripts/maps/mamaps_build/src/schema/buildings.rsindex 59153d8076..5576830202 100644--- a/scripts/maps/mamaps_build/src/schema/buildings.rs+++ b/scripts/maps/mamaps_build/src/schema/buildings.rs@@ -9,12 +9,38 @@ //! `building:part` is a separate kind because a 3D model tags the parts of a building separately //! from its footprint, and drawing both means drawing the courtyard of a building twice. +use tilecodec::mamaps::body::{+ BuildingAttrs, ROOF_DOME, ROOF_FLAT, ROOF_GABLED, ROOF_HIPPED, ROOF_ORIENT_ACROSS,+ ROOF_ORIENT_ALONG, ROOF_PYRAMIDAL, ROOF_SKILLION,+}; use tilecodec::mamaps::dict::LAYER_BUILDINGS; use super::{kind, Class, TagSource}; /// The pre-screen.-pub const FILTERS: &[&str] = &["building", "building:part"];+///+/// A superset of the keys the rules and [`attrs`] read: `building`/`building:part` decide the+/// classification, and the rest carry the S3DB attributes [`attrs`] parses. Listing the attribute+/// keys keeps a building's height and roof tags through the `osmium tags-filter` extract step, so+/// they are still present when [`attrs`] runs — a building that passed the screen on `building`+/// alone would otherwise arrive stripped of everything the 3D extrusion needs.+pub const FILTERS: &[&str] = &[+ "building",+ "building:part",+ "height",+ "building:levels",+ "building:min_level",+ "min_height",+ "roof:shape",+ "roof:height",+ "roof:levels",+ "roof:direction",+ "roof:orientation",+ "building:colour",+ "roof:colour",+ "building:material",+ "roof:material",+]; /// Every `kind` this module can emit. #[cfg_attr(not(test), allow(dead_code))]@@ -39,6 +65,222 @@ pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> { None } +/// Roughly the height of one storey, in metres. OSM's own default for `building:levels` when a+/// building carries no explicit `height`, and what the S3DB wiki suggests. Rooms are ~2.5 m but a+/// storey includes floor and ceiling, so 3 m is the conventional figure the renderer expects back.+const METRES_PER_LEVEL: f64 = 3.0;++/// The S3DB attributes of a building, parsed from its tags — the build half of the 3D extrusion.+///+/// Called by [`crate::extract`] on any feature the classifier put in [`LAYER_BUILDINGS`], for both+/// `building` footprints and `building:part` parts. Every field falls back gracefully: a building+/// with no S3DB tags at all yields [`BuildingAttrs::default`], which the renderer extrudes as a+/// flat box at its own default height. Heights are stored in decimetres (0.1 m); directions are+/// quantised to a byte; colours resolve a CSS/named colour or, failing that, a `*:material`.+pub fn attrs(tags: &(impl TagSource + ?Sized)) -> BuildingAttrs {+ // `height` wins over `building:levels`; a building with neither leaves 0 for the renderer's+ // own default rather than guessing a storey count.+ let height = metres_dm(tags, "height")+ .or_else(|| levels_dm(tags, "building:levels"))+ .unwrap_or(0);+ let min_height = metres_dm(tags, "min_height")+ .or_else(|| levels_dm(tags, "building:min_level"))+ .unwrap_or(0);+ let roof_height =+ metres_dm(tags, "roof:height").or_else(|| levels_dm(tags, "roof:levels")).unwrap_or(0);+ let building_colour = tags+ .get("building:colour")+ .and_then(parse_colour)+ .or_else(|| tags.get("building:material").and_then(material_colour))+ .unwrap_or(0);+ let roof_colour = tags+ .get("roof:colour")+ .and_then(parse_colour)+ .or_else(|| tags.get("roof:material").and_then(material_colour))+ .unwrap_or(0);+ BuildingAttrs {+ height,+ min_height,+ roof_height,+ roof_shape: roof_shape(tags.get("roof:shape")),+ roof_direction: roof_direction(tags.get("roof:direction")),+ roof_orientation: match tags.get("roof:orientation") {+ Some("across") => ROOF_ORIENT_ACROSS,+ _ => ROOF_ORIENT_ALONG,+ },+ building_colour,+ roof_colour,+ }+}++/// A metre value (`12`, `12.5`, `12 m`) as decimetres, clamped to what a `u16` holds (6553.5 m,+/// past the tallest building on earth). `None` when the tag is absent or not a number.+fn metres_dm(tags: &(impl TagSource + ?Sized), key: &str) -> Option<u16> {+ let raw = tags.get(key)?;+ let metres = parse_leading_f64(raw)?;+ dm_of(metres)+}++/// A level count (`building:levels=3`) as a height in decimetres, at [`METRES_PER_LEVEL`] each.+fn levels_dm(tags: &(impl TagSource + ?Sized), key: &str) -> Option<u16> {+ let levels = parse_leading_f64(tags.get(key)?)?;+ dm_of(levels * METRES_PER_LEVEL)+}++/// Metres to decimetres, rounded and clamped to `u16`; negative or non-finite yields `None`.+fn dm_of(metres: f64) -> Option<u16> {+ if !metres.is_finite() || metres < 0.0 {+ return None;+ }+ Some((metres * 10.0).round().min(u16::MAX as f64) as u16)+}++/// The leading number of a value, ignoring a trailing unit like ` m`. OSM height tags are metres+/// by convention; a stray `ft` is rare enough to accept the bare number rather than convert.+fn parse_leading_f64(raw: &str) -> Option<f64> {+ let trimmed = raw.trim();+ let end = trimmed+ .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+'))+ .unwrap_or(trimmed.len());+ trimmed[..end].parse::<f64>().ok()+}++/// An OSM `roof:shape` mapped to one of the six the renderer models. Anything else — round,+/// gambrel, mansard, sawtooth — falls back to flat, which is the plan's stated behaviour: a shape+/// the extruder cannot build is drawn as a flat cap rather than guessed at.+fn roof_shape(value: Option<&str>) -> u8 {+ match value {+ Some("gabled") => ROOF_GABLED,+ Some("hipped") => ROOF_HIPPED,+ Some("pyramidal") => ROOF_PYRAMIDAL,+ Some("skillion") => ROOF_SKILLION,+ Some("dome") => ROOF_DOME,+ _ => ROOF_FLAT,+ }+}++/// A `roof:direction` (degrees, or a compass point like `NE`) quantised to a byte: `deg * 256 /+/// 360`, which the renderer decodes as `v * 360 / 256`. Zero (north) for an absent or unparseable+/// value, which is the same default a flat roof carries anyway.+fn roof_direction(value: Option<&str>) -> u8 {+ let Some(raw) = value else { return 0 };+ let degrees = compass_degrees(raw.trim()).or_else(|| parse_leading_f64(raw)).unwrap_or(0.0);+ // Wrap into 0..360 before quantising, so 720 and -90 land where a compass would put them.+ let wrapped = degrees.rem_euclid(360.0);+ ((wrapped / 360.0 * 256.0).round() as i64).rem_euclid(256) as u8+}++/// The eight- and sixteen-point compass abbreviations OSM allows in a direction tag, in degrees.+fn compass_degrees(raw: &str) -> Option<f64> {+ let d = match raw.to_ascii_uppercase().as_str() {+ "N" => 0.0,+ "NNE" => 22.5,+ "NE" => 45.0,+ "ENE" => 67.5,+ "E" => 90.0,+ "ESE" => 112.5,+ "SE" => 135.0,+ "SSE" => 157.5,+ "S" => 180.0,+ "SSW" => 202.5,+ "SW" => 225.0,+ "WSW" => 247.5,+ "W" => 270.0,+ "WNW" => 292.5,+ "NW" => 315.0,+ "NNW" => 337.5,+ _ => return None,+ };+ Some(d)+}++/// A CSS/OSM colour — `#rgb`, `#rrggbb`, or a common colour name — as opaque `0xAARRGGBB`.+/// `None` for anything unrecognised, so the caller can fall back to a material.+fn parse_colour(raw: &str) -> Option<u32> {+ let s = raw.trim();+ if let Some(hex) = s.strip_prefix('#') {+ let rgb = match hex.len() {+ 3 => {+ let mut v = 0u32;+ for c in hex.chars() {+ let n = c.to_digit(16)?;+ // Each nibble is doubled: #abc is #aabbcc.+ v = (v << 8) | (n * 17);+ }+ v+ }+ 6 => u32::from_str_radix(hex, 16).ok()?,+ _ => return None,+ };+ return Some(0xFF00_0000 | rgb);+ }+ named_colour(&s.to_ascii_lowercase()).map(|rgb| 0xFF00_0000 | rgb)+}++/// The common CSS/OSM colour names that actually appear on buildings, as `0xRRGGBB`.+///+/// Not the full 147-name CSS set: the long tail never appears on a `building:colour`, and a name+/// this misses falls through to the material palette or to "no colour", both of which are fine.+fn named_colour(name: &str) -> Option<u32> {+ let rgb = match name {+ "white" => 0xFFFFFF,+ "black" => 0x000000,+ "gray" | "grey" => 0x808080,+ "silver" => 0xC0C0C0,+ "lightgray" | "lightgrey" => 0xD3D3D3,+ "darkgray" | "darkgrey" => 0xA9A9A9,+ "red" => 0xFF0000,+ "darkred" => 0x8B0000,+ "maroon" => 0x800000,+ "brown" => 0xA52A2A,+ "sienna" => 0xA0522D,+ "orange" => 0xFFA500,+ "yellow" => 0xFFFF00,+ "gold" => 0xFFD700,+ "beige" => 0xF5F5DC,+ "cream" => 0xFFFDD0,+ "tan" => 0xD2B48C,+ "green" => 0x008000,+ "darkgreen" => 0x006400,+ "olive" => 0x808000,+ "lightgreen" => 0x90EE90,+ "blue" => 0x0000FF,+ "lightblue" => 0xADD8E6,+ "navy" => 0x000080,+ "cyan" => 0x00FFFF,+ "teal" => 0x008080,+ "purple" => 0x800080,+ "pink" => 0xFFC0CB,+ "terracotta" => 0xE2725B,+ _ => return None,+ };+ Some(rgb)+}++/// A `building:material` or `roof:material` mapped to a representative colour, as opaque+/// `0xAARRGGBB`. The palette a renderer falls back to when a building states its material but not+/// its colour, which is the common case on 3D-mapped cities.+fn material_colour(material: &str) -> Option<u32> {+ let rgb = match material.trim().to_ascii_lowercase().as_str() {+ "brick" | "brick_wall" => 0xB0_4A_39,+ "concrete" | "cement_block" => 0xB0_B0_B0,+ "glass" | "mirror" => 0xB8_D0_E0,+ "wood" | "timber_framing" => 0x9B_6B_43,+ "stone" | "sandstone" | "limestone" => 0xC8_BE_A8,+ "marble" => 0xF0_EE_E6,+ "metal" | "metal_sheet" | "steel" => 0xB4_B8_BC,+ "copper" => 0x7A_9E_8E,+ "plaster" | "stucco" | "render" => 0xE8_E0_D0,+ "roof_tiles" | "tile" | "tiles" | "clay" => 0xB5_6A_4A,+ "slate" => 0x50_54_5A,+ "tar_paper" | "asphalt" | "bitumen" => 0x3A_3A_3E,+ "grass" | "green_roof" => 0x6E_8B_3D,+ "gravel" => 0x9A_94_88,+ _ => return None,+ };+ Some(0xFF00_0000 | rgb)+}+ #[cfg(test)] mod tests { use super::*;@@ -103,4 +345,129 @@ mod tests { let class = classify_tags(&[("building", "yes")]).expect("building"); assert_eq!(class.min_zoom, 14); }++ fn attrs_of(pairs: &[(&str, &str)]) -> BuildingAttrs {+ super::attrs(pairs)+ }++ #[test]+ fn a_plain_building_has_default_attrs() {+ // No S3DB tags at all: a flat box at the renderer's own default height, no colours.+ let a = attrs_of(&[("building", "yes")]);+ assert_eq!(a, BuildingAttrs::default());+ assert_eq!(a.height, 0, "0 means the renderer picks a default");+ assert_eq!(a.roof_shape, ROOF_FLAT);+ }++ #[test]+ fn height_is_metres_in_decimetres_and_levels_are_the_fallback() {+ // An explicit height wins and carries its fraction, stored as decimetres.+ assert_eq!(attrs_of(&[("building", "yes"), ("height", "12.5")]).height, 125);+ // A trailing unit is ignored — the number is metres by convention.+ assert_eq!(attrs_of(&[("building", "yes"), ("height", "20 m")]).height, 200);+ // Levels are the fallback at 3 m each, only when there is no explicit height.+ assert_eq!(attrs_of(&[("building", "yes"), ("building:levels", "4")]).height, 120);+ let both = attrs_of(&[("building", "yes"), ("height", "9"), ("building:levels", "4")]);+ assert_eq!(both.height, 90, "an explicit height wins over the level count");+ }++ #[test]+ fn min_height_and_roof_height_parse_with_their_level_fallbacks() {+ let a = attrs_of(&[+ ("building:part", "yes"),+ ("min_height", "8"),+ ("roof:height", "3.5"),+ ]);+ assert_eq!(a.min_height, 80);+ assert_eq!(a.roof_height, 35);+ let levels = attrs_of(&[+ ("building:part", "yes"),+ ("building:min_level", "2"),+ ("roof:levels", "1"),+ ]);+ assert_eq!(levels.min_height, 60, "two levels up at 3 m each");+ assert_eq!(levels.roof_height, 30);+ }++ #[test]+ fn roof_shapes_map_and_unknown_falls_back_to_flat() {+ for (tag, want) in [+ ("flat", ROOF_FLAT),+ ("gabled", ROOF_GABLED),+ ("hipped", ROOF_HIPPED),+ ("pyramidal", ROOF_PYRAMIDAL),+ ("skillion", ROOF_SKILLION),+ ("dome", ROOF_DOME),+ // Shapes the extruder does not model fall back to flat rather than guessing.+ ("gambrel", ROOF_FLAT),+ ("mansard", ROOF_FLAT),+ ("round", ROOF_FLAT),+ ] {+ assert_eq!(+ attrs_of(&[("building", "yes"), ("roof:shape", tag)]).roof_shape,+ want,+ "roof:shape={tag}",+ );+ }+ }++ #[test]+ fn roof_direction_takes_degrees_and_compass_points() {+ // 90° east quantises to a quarter of 256.+ assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "90")]).roof_direction, 64);+ assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "E")]).roof_direction, 64);+ assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "N")]).roof_direction, 0);+ // A value past 360 wraps like a compass rather than clamping.+ assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "450")]).roof_direction, 64);+ assert_eq!(+ attrs_of(&[("building", "yes"), ("roof:orientation", "across")]).roof_orientation,+ ROOF_ORIENT_ACROSS,+ );+ assert_eq!(+ attrs_of(&[("building", "yes")]).roof_orientation,+ ROOF_ORIENT_ALONG,+ "the default orientation is along",+ );+ }++ #[test]+ fn colours_parse_hex_and_names_with_a_material_fallback() {+ // Hex, short and long, opaque.+ assert_eq!(+ attrs_of(&[("building", "yes"), ("building:colour", "#ffcc00")]).building_colour,+ 0xFF_FF_CC_00,+ );+ assert_eq!(+ attrs_of(&[("building", "yes"), ("building:colour", "#fc0")]).building_colour,+ 0xFF_FF_CC_00,+ "a three-digit hex doubles each nibble",+ );+ // A named colour.+ assert_eq!(+ attrs_of(&[("building", "yes"), ("roof:colour", "red")]).roof_colour,+ 0xFF_FF_00_00,+ );+ // No colour, but a material: the palette fills in.+ let brick = attrs_of(&[("building", "yes"), ("building:material", "brick")]);+ assert_ne!(brick.building_colour, 0, "a material resolves to a palette colour");+ assert_eq!(brick.building_colour >> 24, 0xFF, "and it is opaque");+ // An explicit colour beats the material.+ let both = attrs_of(&[+ ("building", "yes"),+ ("building:colour", "white"),+ ("building:material", "brick"),+ ]);+ assert_eq!(both.building_colour, 0xFF_FF_FF_FF, "the colour wins over the material");+ // No colour and no material: absent, so the style default is used.+ assert_eq!(attrs_of(&[("building", "yes")]).building_colour, 0);+ }++ #[test]+ fn a_giant_height_is_clamped_rather_than_wrapping() {+ // A vandalised height must not wrap a u16 into a short building.+ let a = attrs_of(&[("building", "yes"), ("height", "999999")]);+ assert_eq!(a.height, u16::MAX);+ // A negative height is nonsense and drops to the default rather than a huge unsigned value.+ assert_eq!(attrs_of(&[("building", "yes"), ("height", "-5")]).height, 0);+ } }
scripts/maps/mamaps_build/src/schema/mod.rs
diff --git a/scripts/maps/mamaps_build/src/schema/mod.rs b/scripts/maps/mamaps_build/src/schema/mod.rsindex d2d80f58a3..7434762290 100644--- a/scripts/maps/mamaps_build/src/schema/mod.rs+++ b/scripts/maps/mamaps_build/src/schema/mod.rs@@ -30,6 +30,7 @@ pub mod land; pub mod places; pub mod poi; pub mod roads;+pub mod traffic; pub mod transit; pub mod water; @@ -162,6 +163,7 @@ pub struct Layers { pub places: bool, pub poi: bool, pub transit: bool,+ pub traffic: bool, } impl Layers {@@ -179,6 +181,10 @@ impl Layers { // Reserved by v2; populated when transit lands (task 52). Selected by default so // the layer set — and therefore the build id — does not shift when it does. transit: true,+ // v4's live traffic overlay. Selected by default like `transit`, and empty without+ // its data source (`--graph`) rather than an error: an archive with no traffic layer+ // is an obvious "no overlay", not the silent disaster an archive with no mainland is.+ traffic: true, } } @@ -194,6 +200,7 @@ impl Layers { places: false, poi: false, transit: false,+ traffic: false, } } @@ -212,10 +219,11 @@ impl Layers { "places" => layers.places = true, "poi" => layers.poi = true, "transit" => layers.transit = true,+ "traffic" => layers.traffic = true, other => { return Err(format!( "unknown layer `{other}`; this generator produces earth, water, buildings, \- roads, boundaries, landcover, landuse, places, poi and transit"+ roads, boundaries, landcover, landuse, places, poi, transit and traffic" )) } }@@ -239,6 +247,7 @@ impl Layers { dict::LAYER_PLACES => self.places, dict::LAYER_POI => self.poi, dict::LAYER_TRANSIT => self.transit,+ dict::LAYER_TRAFFIC => self.traffic, _ => false, } }@@ -309,16 +318,32 @@ pub fn classify( /// A label's display name for a classified feature, or `None` when the layer carries none. ///-/// Only `places` and `poi` name features (`name:en` → `name`, as the style coalesces). Called-/// by extract at each classify site; the name travels beside the class into the spill.+/// `places` and `poi` name points; `roads` and `water` name their lines (a street or a river) so+/// the renderer can curve a label along the centreline. All four coalesce `name:en` then `name`,+/// the same order the reference style does. Called by extract at each classify site; the name+/// travels beside the class into the spill and is interned per tile with no format cost — the name+/// table already exists. pub fn display_name(tags: &(impl TagSource + ?Sized), layer: u8) -> Option<String> { match layer { dict::LAYER_PLACES => places::display_name(tags), dict::LAYER_POI => poi::display_name(tags),+ dict::LAYER_ROADS | dict::LAYER_WATER => line_name(tags), _ => None, } } +/// The coalesced `name:en`/`name` of a line feature, trimmed, or `None` when it has neither.+///+/// The same rule [`places::display_name`] applies, spelled out here because a road or a river is+/// not a `places` label and reusing that function would read as one.+fn line_name(tags: &(impl TagSource + ?Sized)) -> Option<String> {+ tags.get("name:en")+ .or_else(|| tags.get("name"))+ .map(str::trim)+ .filter(|name| !name.is_empty())+ .map(str::to_string)+}+ /// The `osmium tags-filter` expressions that pre-screen each layer, as one list. /// /// Reading three tags to reject a feature instead of the thirty the rules would read between them.@@ -396,7 +421,7 @@ mod tests { Layers { water: true, ..Layers::none() }, ); assert_eq!(- Layers::parse("earth,water,buildings,roads,boundaries,landcover,landuse,places,poi,transit")+ Layers::parse("earth,water,buildings,roads,boundaries,landcover,landuse,places,poi,transit,traffic") .expect("all"), Layers::all(), );
scripts/maps/mamaps_build/src/schema/roads.rs
diff --git a/scripts/maps/mamaps_build/src/schema/roads.rs b/scripts/maps/mamaps_build/src/schema/roads.rsindex ce6a11a07a..8ec4ecb839 100644--- a/scripts/maps/mamaps_build/src/schema/roads.rs+++ b/scripts/maps/mamaps_build/src/schema/roads.rs@@ -202,6 +202,47 @@ fn flags(tags: &(impl TagSource + ?Sized), value: &str) -> u8 { flags } +/// The carriageway lane count baked into a `roads` feature, or zero when the way carries no+/// `lanes` tag.+///+/// The OSM `lanes` total (both directions), parsed by the same [`osm_ingest::tags::parse_int_tag`]+/// the routing graph and the `roads.pmtiles` layer use, so a road cannot describe its lane count+/// one way to the router and another to the basemap. Capped at [`osm_ingest::tags::MAX_LANES`]+/// (64), which fits a byte — the renderer stores it in the feature record's last byte and expands+/// it into that many parallel lanes with dividers at high zoom. A mistagged `lanes=999999999`+/// therefore becomes the cap rather than an absurd fan.+///+/// Only the total is baked, not the per-lane `turn:lanes` masks: those are variable length and+/// belong in a side table (the turn-arrow pass), while the count is one byte the parallel-lane+/// geometry needs first.+pub fn lane_count(tags: &(impl TagSource + ?Sized)) -> u8 {+ osm_ingest::tags::parse_int_tag(tags.get("lanes")).min(osm_ingest::tags::MAX_LANES) as u8+}++/// The per-lane turn-indication masks for a road, `(forward, backward)`, each a left-to-right+/// list of `LANE_*` bit sets from OSM `turn:lanes[:forward|:backward]`.+///+/// A verbatim reuse of the routing graph's own derivation+/// ([`osm_ingest::roads::lane_masks`]) via a [`RoadTags`](osm_ingest::roads::RoadTags) built from+/// this tag source, so a road cannot describe its lanes one way to the router and another to the+/// arrows drawn over it. Empty vectors when the way has no `turn:lanes`, which is almost every+/// road. Forward lanes are traversed toward the way's end (its junction), backward toward its+/// start — which is where the renderer places each direction's arrows.+pub fn turn_masks(tags: &(impl TagSource + ?Sized)) -> (Vec<u16>, Vec<u16>) {+ let rt = osm_ingest::roads::RoadTags {+ highway: tags.get("highway"),+ lanes: tags.get("lanes"),+ lanes_forward: tags.get("lanes:forward"),+ lanes_backward: tags.get("lanes:backward"),+ turn_lanes: tags.get("turn:lanes"),+ turn_lanes_forward: tags.get("turn:lanes:forward"),+ turn_lanes_backward: tags.get("turn:lanes:backward"),+ oneway: tags.get("oneway"),+ ..Default::default()+ };+ osm_ingest::roads::lane_masks(&rt)+}+ #[cfg(test)] mod tests { use super::*;@@ -314,6 +355,46 @@ mod tests { assert_eq!(names(&crossing).0, "minor_road"); } + /// The carriageway lane count baked for the renderer's parallel-lane draw: the OSM `lanes`+ /// total, zero when absent, and capped so a mistagged count cannot become an absurd fan.+ #[test]+ fn the_lane_count_is_the_capped_osm_lanes_total() {+ assert_eq!(lane_count(&[("highway", "primary"), ("lanes", "4")][..]), 4);+ assert_eq!(lane_count(&[("highway", "residential")][..]), 0, "no tag, no lanes");+ assert_eq!(lane_count(&[("highway", "primary"), ("lanes", "0")][..]), 0);+ // A byte, and never past the shared MAX_LANES the router and pmtiles layer use.+ assert_eq!(+ lane_count(&[("highway", "motorway"), ("lanes", "999999999")][..]),+ osm_ingest::tags::MAX_LANES as u8,+ );+ }++ /// The per-lane turn masks reuse the routing graph's derivation, so the arrows drawn over a+ /// road agree with how it is routed: a oneway's plain `turn:lanes` is forward, a two-way's is+ /// neither, and the masks are the graph's `LANE_*` bits left to right.+ #[test]+ fn the_turn_masks_match_the_routing_graphs_derivation() {+ use osm_ingest::tags::{LANE_LEFT, LANE_RIGHT, LANE_THROUGH};+ // A oneway carries its plain `turn:lanes` as forward, none backward.+ let oneway: &[(&str, &str)] =+ &[("highway", "primary"), ("oneway", "yes"), ("turn:lanes", "left|through|through;right")];+ let (fwd, bwd) = turn_masks(oneway);+ assert_eq!(fwd, vec![LANE_LEFT, LANE_THROUGH, LANE_THROUGH | LANE_RIGHT]);+ assert!(bwd.is_empty());+ // Explicit forward/backward split on a two-way street.+ let split: &[(&str, &str)] = &[+ ("highway", "secondary"),+ ("turn:lanes:forward", "through|right"),+ ("turn:lanes:backward", "left"),+ ];+ let (fwd, bwd) = turn_masks(split);+ assert_eq!(fwd, vec![LANE_THROUGH, LANE_RIGHT]);+ assert_eq!(bwd, vec![LANE_LEFT]);+ // A road with no turn tags carries nothing either way.+ let (fwd, bwd) = turn_masks(&[("highway", "residential")][..]);+ assert!(fwd.is_empty() && bwd.is_empty());+ }+ #[test] fn an_unrecognised_value_is_not_a_road() { for tags in [
scripts/maps/mamaps_build/src/schema/traffic.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic.rs b/scripts/maps/mamaps_build/src/schema/traffic.rsnew file mode 100644index 0000000000..3ee89a0849--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -0,0 +1,626 @@+//! `traffic`: one line per drivable **component** segment of the v6 routing graph.+//!+//! The one layer whose geometry is not in the `.osm.pbf` and not in a prepared product either: it+//! is read straight from the app's v6 routing graph — `metadata.bin`, `nodes.bin`, `edges.bin` and+//! `intermediate.bin`, produced by `scripts/maps/osm_ingest`'s `road_graph`. Building from the+//! graph is what makes every feature's `component_id` match, byte for byte and with no coordination+//! file, the ids the traffic server computes from the same graph. The authoritative spec is+//! `analysis/traffic_id_contract.md`; the reader below mirrors `maps/src/main/rust/src/graph.rs`.+//!+//! # What one feature is+//!+//! A big edge's polyline is `source_node -> interior points -> target_node`. A **component**+//! segment is one consecutive vertex pair of that polyline, and each becomes one `GEOM_LINE`+//! feature carrying `component_id = (big_edge_id << 16) | seg_index` in the body's id side table.+//! The tiler does not coalesce this layer, so its features stay one-to-one with those ids.+//!+//! # Emit-each-segment-once (dedup), verbatim from the contract §3+//!+//! A two-way road is two directed edges over the same ground. To draw it once — and, more+//! importantly, so the archive and the server pick the **same** directed `big_edge_id` for a+//! physical segment — this canonicalises identically to WS1:+//!+//! 1. Skip any edge with `REVERSE_GEOMETRY_FLAG` (`0x40`): it is the reverse twin of a *curved*+//! two-way road and stores no geometry of its own; its non-flag twin owns the shape.+//! 2. A straight two-way chord stores no blob and the flag is set on neither direction, so step 1+//! alone would emit both. For an edge with no stored geometry that has a drivable twin, emit+//! only the canonical direction (`source_idx < target_idx`). A genuine one-way has no twin, so+//! it is emitted regardless.+//!+//! # Drivable+//!+//! An edge is drivable iff `(type_ & 0x3F)` is in `1..=9` (motorway..living_street). The road-class+//! bits are masked before the range test so the reverse-geometry flag never trips it.++use std::path::Path;++use osm_ingest::proto::{err, Result};+use tile_build::geom::Geometry;+use tilecodec::mamaps::dict::{self, LAYER_TRAFFIC};++use super::Class;+use crate::store::Sink;++/// The zoom the traffic overlay first surfaces at.+///+/// Component lines are dense — roughly the whole drivable network as one line per segment — so a+/// traffic overlay only earns its bytes where a street network reads at all. z12 is the shallowest+/// zoom a city's arterials are legible; below it the overlay would be a red smear. Raise it to trim+/// the archive further, lower it to show motorway congestion sooner. The store packs `min_zoom` in+/// five bits, so anything up to 31 is representable.+pub const MIN_ZOOM: u8 = 12;++/// Bits reserved for the component-segment index inside a packed component id. Shared on-disk/wire+/// contract with the server and the device — keep in sync with `graph.rs::COMPONENT_SEG_BITS` and+/// `analysis/traffic_id_contract.md` §1.+pub const COMPONENT_SEG_BITS: u32 = 16;+pub const COMPONENT_SEG_MASK: u64 = (1 << COMPONENT_SEG_BITS) - 1;++/// `component_id = (big_edge_id << 16) | seg_index`.+#[inline]+pub fn pack_component_id(big_edge_id: u64, seg_index: u32) -> u64 {+ debug_assert!(u64::from(seg_index) <= COMPONENT_SEG_MASK);+ (big_edge_id << COMPONENT_SEG_BITS) | u64::from(seg_index)+}++/// The inverse of [`pack_component_id`].+#[inline]+pub fn unpack_component_id(component_id: u64) -> (u64, u32) {+ (component_id >> COMPONENT_SEG_BITS, (component_id & COMPONENT_SEG_MASK) as u32)+}++/// The class every traffic segment carries: layer `traffic`, no kind and no detail.+///+/// No `kind`/`kind_detail`, because the layer is not drawn by the basemap style — it is filtered on+/// and recoloured by the renderer from a pushed id→speed table, keyed on the `component_id` in the+/// body's id side table rather than on any interned attribute. Keeping it out of [`dict::KINDS`]+/// avoids disturbing the frozen kind table for a value nothing matches by name.+pub fn traffic_class() -> Class {+ Class {+ layer: LAYER_TRAFFIC,+ kind: dict::NONE,+ kind_detail: dict::NONE,+ flags: 0,+ area: false,+ min_zoom: MIN_ZOOM,+ min_area_px: 0.0,+ }+}++// --- v6 graph on-disk constants (see traffic_id_contract.md §2 / graph.rs) -----------------++const MARG_MAGIC: u32 = 0x4752_414D; // "MARG"+const GRAPH_VERSION: u32 = 6;+/// One escape block index per 1024 edges (`graph.rs` ESCAPE_BLOCK).+const ESCAPE_BLOCK: u64 = 1024;+/// One coarse geometry offset per 32 geometry edges (`graph.rs` INTERMEDIATE_BLOCK).+const INTERMEDIATE_BLOCK: u64 = 32;+/// One rank word per 512 edges = 64 present bytes (`graph.rs` RANK_BLOCK_BYTES).+const RANK_BLOCK_BYTES: usize = 64;+/// `type_` bit 6: this edge stores no geometry of its own; its twin runs `target -> source`.+const REVERSE_GEOMETRY_FLAG: u8 = 0x40;+/// The low six bits of `type_` are the road class.+const ROAD_TYPE_MASK: u8 = 0x3F;+/// A `target_delta` of `i16::MIN` means the true target is in the escape table.+const TARGET_DELTA_ESCAPE: i16 = i16::MIN;+/// A `dist` u24 of all-ones means the true target and distance are in the escape table.+const DIST_MM_ESCAPE: u32 = 0x00FF_FFFF;+/// The most vertices a big edge's polyline holds (`geom.rs` MAX_POINTS); the reader stops here.+const MAX_POINTS: usize = 256;++fn u16_at(buf: &[u8], at: usize) -> u16 {+ u16::from_le_bytes([buf[at], buf[at + 1]])+}+fn i16_at(buf: &[u8], at: usize) -> i16 {+ i16::from_le_bytes([buf[at], buf[at + 1]])+}+fn u32_at(buf: &[u8], at: usize) -> u32 {+ u32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]])+}+fn i32_at(buf: &[u8], at: usize) -> i32 {+ i32::from_le_bytes([buf[at], buf[at + 1], buf[at + 2], buf[at + 3]])+}+fn u64_at(buf: &[u8], at: usize) -> u64 {+ u64::from_le_bytes([+ buf[at],+ buf[at + 1],+ buf[at + 2],+ buf[at + 3],+ buf[at + 4],+ buf[at + 5],+ buf[at + 6],+ buf[at + 7],+ ])+}++fn align_up8(n: usize) -> usize {+ (n + 7) & !7+}++/// Bytes an [`EdgeBitmap`] over `edges` edges occupies: a `u64` rank word per 512 edges plus one+/// present byte per 8 edges (`graph.rs` `EdgeBitmap`).+fn present_offset(edges: u64) -> usize {+ ((edges.div_ceil(512) + 1) * 8) as usize+}+fn edge_bitmap_bytes(edges: u64) -> usize {+ present_offset(edges) + edges.div_ceil(8) as usize+}++/// The subset of the v6 graph reader the traffic layer needs: node coordinates, edge targets and+/// types, and big-edge geometry. Names, distances and speed limits are skipped — the server reads+/// those; the archive carries only geometry and the id.+struct Graph {+ nodes: Vec<u8>,+ edges: Vec<u8>,+ inter: Vec<u8>,+ node_count: u64,+ escape_first_off: usize,+ escapes_off: usize,+ // intermediate.bin sub-table offsets+ geom_rank_off: usize,+ geom_present_off: usize,+ coarse_off: usize,+ within_off: usize,+}++impl Graph {+ fn load(dir: &Path) -> Result<Graph> {+ let read = |name: &str| -> Result<Vec<u8>> {+ let path = dir.join(name);+ std::fs::read(&path)+ .map_err(|e| osm_ingest::proto::Error(format!("cannot read {}: {e}", path.display())))+ };+ let meta = read("metadata.bin")?;+ if meta.len() < 40 {+ return err(format!("metadata.bin is {} bytes, a v6 MARG header is 40", meta.len()));+ }+ if u32_at(&meta, 0) != MARG_MAGIC {+ return err("metadata.bin is not a MARG graph header".to_string());+ }+ let version = u32_at(&meta, 4);+ if version != GRAPH_VERSION {+ return err(format!(+ "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION}"+ ));+ }+ let node_count = u64_at(&meta, 8);+ let edge_count = u64_at(&meta, 16);+ let escape_count = u64_at(&meta, 24);+ if edge_count > u32::MAX as u64 {+ return err(format!("edge_count {edge_count} does not fit u32"));+ }+ if escape_count > edge_count {+ return err(format!(+ "escape_count {escape_count} exceeds edge_count {edge_count}"+ ));+ }++ let nodes = read("nodes.bin")?;+ let want_nodes = (node_count + 1)+ .checked_mul(12)+ .ok_or_else(|| osm_ingest::proto::Error("node table size overflows".to_string()))?;+ if nodes.len() as u64 != want_nodes {+ return err(format!(+ "nodes.bin is {} bytes, expected {} for {node_count}+1 records",+ nodes.len(),+ want_nodes,+ ));+ }++ let edges = read("edges.bin")?;+ let escape_first_off = align_up8((edge_count as usize) * 7);+ let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;+ let escapes_off = escape_first_off + (escape_blocks as usize) * 4;+ let want_edges_min = escapes_off + (escape_count as usize) * 12;+ if edges.len() < want_edges_min {+ return err(format!(+ "edges.bin is {} bytes, too short for {edge_count} edges and {escape_count} escapes",+ edges.len(),+ ));+ }++ let inter = read("intermediate.bin")?;+ if inter.len() < 8 {+ return err("intermediate.bin is too short to hold its geometry-edge count".to_string());+ }+ let g_edges = u64_at(&inter, inter.len() - 8);+ if g_edges > edge_count {+ return err(format!(+ "intermediate.bin claims {g_edges} geometry edges, past the {edge_count} in the graph"+ ));+ }+ let bitmap_bytes = edge_bitmap_bytes(edge_count);+ let coarse_bytes = ((g_edges.div_ceil(INTERMEDIATE_BLOCK) + 1) * 8) as usize;+ let within_bytes = ((g_edges + 1) * 2) as usize;+ let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;+ if inter.len() < trailer {+ return err(format!(+ "intermediate.bin is {} bytes, too short for its {trailer}-byte trailer",+ inter.len(),+ ));+ }+ let blob_bytes = inter.len() - trailer;+ let geom_rank_off = blob_bytes;+ let geom_present_off = blob_bytes + present_offset(edge_count);+ let coarse_off = blob_bytes + bitmap_bytes;+ let within_off = coarse_off + coarse_bytes;++ Ok(Graph {+ nodes,+ edges,+ inter,+ node_count,+ escape_first_off,+ escapes_off,+ geom_rank_off,+ geom_present_off,+ coarse_off,+ within_off,+ })+ }++ /// A node's `(lat_e7, lon_e7)`.+ fn node(&self, n: u64) -> (i32, i32) {+ let base = (n as usize) * 12;+ (i32_at(&self.nodes, base), i32_at(&self.nodes, base + 4))+ }++ /// A node's first outgoing edge index. The sentinel record (index `node_count`) holds+ /// `edge_count`, so `edge_ptr(n+1)` is always defined for a real node `n`.+ fn edge_ptr(&self, n: u64) -> u32 {+ u32_at(&self.nodes, (n as usize) * 12 + 8)+ }++ fn edge_type(&self, idx: u32) -> u8 {+ self.edges[(idx as usize) * 7 + 5]+ }++ /// The target node of edge `idx` whose source is `s`, decoding the escape table when the+ /// delta or distance is sentinelled.+ fn edge_target(&self, idx: u32, s: u32) -> Result<u32> {+ let base = (idx as usize) * 7;+ let delta = i16_at(&self.edges, base);+ let dist = (self.edges[base + 2] as u32)+ | ((self.edges[base + 3] as u32) << 8)+ | ((self.edges[base + 4] as u32) << 16);+ if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE {+ self.escape_target(idx)+ } else {+ Ok(s.wrapping_add_signed(delta as i32))+ }+ }++ fn escape_target(&self, idx: u32) -> Result<u32> {+ let block = (idx as u64 / ESCAPE_BLOCK) as usize;+ let lo = u32_at(&self.edges, self.escape_first_off + block * 4);+ let hi = u32_at(&self.edges, self.escape_first_off + (block + 1) * 4);+ for r in lo..hi {+ let rb = self.escapes_off + (r as usize) * 12;+ if u32_at(&self.edges, rb) == idx {+ return Ok(u32_at(&self.edges, rb + 4));+ }+ }+ err(format!("edge {idx} is escaped but has no escape row"))+ }++ /// Does edge `idx` store an interior-point blob?+ fn geom_contains(&self, idx: u32) -> bool {+ let byte = self.geom_present_off + (idx as usize) / 8;+ self.inter[byte] & (1u8 << (idx % 8)) != 0+ }++ /// The rank of edge `idx` among the geometry-carrying edges: the number of set bits strictly+ /// below it in the presence bitmap.+ fn geom_rank(&self, idx: u32) -> u64 {+ let byte = (idx as usize) / 8;+ let block = byte / RANK_BLOCK_BYTES;+ let mut n = u64_at(&self.inter, self.geom_rank_off + block * 8);+ for b in (block * RANK_BLOCK_BYTES)..byte {+ n += self.inter[self.geom_present_off + b].count_ones() as u64;+ }+ let mask = ((1u16 << (idx % 8)) - 1) as u8;+ n += (self.inter[self.geom_present_off + byte] & mask).count_ones() as u64;+ n+ }++ /// The blob byte offset of the `g`th geometry edge: `coarse[g/32] + within[g]`.+ fn geom_offset(&self, g: u64) -> u64 {+ let coarse = u64_at(&self.inter, self.coarse_off + (g / INTERMEDIATE_BLOCK) as usize * 8);+ let within = u16_at(&self.inter, self.within_off + (g as usize) * 2) as u64;+ coarse + within+ }++ /// The `(start, end)` byte range of edge `idx`'s interior-point blob, or `None` when it stores+ /// no geometry (a straight chord).+ fn intermediate_range(&self, idx: u32) -> Option<(usize, usize)> {+ if !self.geom_contains(idx) {+ return None;+ }+ let g = self.geom_rank(idx);+ Some((self.geom_offset(g) as usize, self.geom_offset(g + 1) as usize))+ }++ /// The full polyline of edge `idx` in canonical `source -> target` order, as `(lat_e7, lon_e7)`+ /// vertices: the source node, any stored interior points, then the target node.+ fn polyline(&self, idx: u32, s: u32, t: u32) -> Vec<(i32, i32)> {+ let (slat, slon) = self.node(s as u64);+ let (tlat, tlon) = self.node(t as u64);+ let mut out = Vec::with_capacity(4);+ out.push((slat, slon));+ if let Some((start, end)) = self.intermediate_range(idx) {+ let (mut lat, mut lon) = (slat, slon);+ let mut off = start;+ // count starts at 1 for the source; the reader stops at MAX_POINTS total, matching+ // `graph.rs::decode_edge_coords`.+ let mut count
Diff truncated.