//! 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 9), 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, //! unless the tile is flat enough to coarsen (see `FLAT_RELIEF_M`). //! //! 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. A tile whose grid is entirely sea //! level yields `None` the same way, whatever the zoom: it carries no relief, and a flat sea-level //! grid would make the renderer draw earth-coloured terrain over open water (see [`Dem::heightmap_for`]). use std::f64::consts::PI; use std::path::Path; use rayon::prelude::*; use tile_build::par; 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; /// Whether every sample in a grid is sea level, i.e. the tile is all ocean / flat coast at 0 m and /// carries no relief worth a terrain grid. See [`Dem::heightmap_for`] for why such tiles drop it. fn all_sea_level(samples: &[u16]) -> bool { samples.iter().all(|&s| s == SEA_LEVEL) } /// A tile flatter than this (max sample minus min sample, in metres) carries /// a coarse grid: at 5x5 the elevation error is bounded by the relief the /// grid cannot see, and below a 10-storey building over a tile (~1 km at /// z14) the mesh is indistinguishable from full resolution. pub const FLAT_RELIEF_M: u16 = 32; /// The coarse grid side length for flat tiles. 5x5x2+2 = 52 bytes against /// 9x9x2+2 = 164 — a 68% saving where it applies, with zero reader changes /// (the wire carries a per-tile `dim`, and sampling/tessellation derive /// from it). pub const FLAT_DIM: u16 = 5; /// The relief (max minus min sample) of a grid, in sample units (metres). fn relief(samples: &[u16]) -> u16 { let (mut lo, mut hi) = (u16::MAX, u16::MIN); for &s in samples { lo = lo.min(s); hi = hi.max(s); } hi - lo } /// Downsample a `dim x dim` grid to `FLAT_DIM x FLAT_DIM` by picking the /// evenly-spaced rows/columns (corners included, so the tile edges agree /// with a full-resolution neighbour's skirt). Only called when /// `dim >= FLAT_DIM` and the grid is flat — the values barely vary, so /// nearest-pick and averaging differ by less than the relief itself. fn coarsen(samples: &[u16], dim: usize) -> Vec { let flat = FLAT_DIM as usize; let mut out = Vec::with_capacity(flat * flat); for row in 0..flat { let src_row = row * (dim - 1) / (flat - 1); for col in 0..flat { let src_col = col * (dim - 1) / (flat - 1); out.push(samples[src_row * dim + src_col]); } } out } /// The grid a tile carries, from its full-resolution `dim x dim` samples. /// /// Default: today's relief gate (flat tiles coarsen to `FLAT_DIM`). Under /// `--dem-max-error M` (planet-size prototype): the coarsest aligned sub-grid whose bilinear /// reconstruction stays within `M/2` of the full grid, then elevations quantised to a /// `floor(M)`-metre step (rounding error <= M/2), so the total error is <= M metres by /// construction — flat ground collapses to 2x2, mountains keep 9x9. Either way the emitted /// grid's error against the full grid is recorded in [`DEM_STATS`]. fn finish_grid(z: u8, y: u64, samples: &[u16], dim: u16) -> Heightmap { let o = crate::tiler::size_opts(); let tol = if o.dem_px > 0.0 { let lat = tile_y_to_lat(y as f64 + 0.5, z); let m_per_px = 156_543.033_92 * lat.to_radians().cos() / (1u64 << z) as f64; (o.dem_px * m_per_px).max(o.dem_max_error_m.max(1.0)) } else { o.dem_max_error_m }; let full = Heightmap { dim, samples: samples.to_vec() }; let out = if tol > 0.0 { adapt_grid(&full, tol) } else if relief(samples) <= FLAT_RELIEF_M && dim >= FLAT_DIM { Heightmap { dim: FLAT_DIM, samples: coarsen(samples, dim as usize) } } else { full.clone() }; DEM_STATS.record(z, &full, &out); out } fn bilinear_at(g: &[u16], dg: usize, fr: f64, fc: f64) -> f64 { let gr = fr * (dg - 1) as f64; let gc = fc * (dg - 1) as f64; let r0 = (gr.floor() as usize).min(dg - 1); let c0 = (gc.floor() as usize).min(dg - 1); let r1 = (r0 + 1).min(dg - 1); let c1 = (c0 + 1).min(dg - 1); let (fy, fx) = (gr - r0 as f64, gc - c0 as f64); let at = |r: usize, c: usize| g[r * dg + c] as f64; let top = at(r0, c0) * (1.0 - fx) + at(r0, c1) * fx; let bot = at(r1, c0) * (1.0 - fx) + at(r1, c1) * fx; top * (1.0 - fy) + bot * fy } /// Max abs and sum of squared error of `new` against `full`, at every full-grid node. Both are /// bilinear surfaces and the coarse nodes are a subset of the fine ones, so the difference is /// bilinear inside every fine cell: the max over the nodes is the max over the whole surface. fn grid_error(full: &Heightmap, new: &Heightmap) -> (f64, f64) { let d = full.dim as usize; let dn = new.dim as usize; let (mut mx, mut ss) = (0.0f64, 0.0f64); for r in 0..d { for c in 0..d { let e = (bilinear_at( &new.samples, dn, r as f64 / (d - 1) as f64, c as f64 / (d - 1) as f64, ) - full.samples[r * d + c] as f64) .abs(); mx = mx.max(e); ss += e * e; } } (mx, ss) } fn adapt_grid(full: &Heightmap, tol: f64) -> Heightmap { let d = full.dim as usize; let mut pick = full.clone(); for dn in (2..=d).filter(|dn| (d - 1) % (dn - 1) == 0) { let mut sub = Vec::with_capacity(dn * dn); for r in 0..dn { for c in 0..dn { sub.push(full.samples[(r * (d - 1) / (dn - 1)) * d + c * (d - 1) / (dn - 1)]); } } let cand = Heightmap { dim: dn as u16, samples: sub }; if grid_error(full, &cand).0 <= tol / 2.0 + 1e-9 { pick = cand; break; } } let q = tol.floor().max(1.0) as i32; if q > 1 { for v in &mut pick.samples { let m = *v as i32 - SEA_LEVEL as i32; let r = ((m as f64 / q as f64).round() as i32) * q; *v = (r + SEA_LEVEL as i32).clamp(0, u16::MAX as i32) as u16; } // Quantising can make a coastal grid all-sea-level; keep it (the caller already decided // the tile has relief) — the renderer's land mask handles the shore. } pick } /// Per-zoom DEM error/size accounting, printed at the end of the build. pub struct DemStats { max_bits: [std::sync::atomic::AtomicU64; 15], ss_micro: [std::sync::atomic::AtomicU64; 15], nodes: [std::sync::atomic::AtomicU64; 15], grids: [std::sync::atomic::AtomicU64; 15], cells: [std::sync::atomic::AtomicU64; 15], } #[allow(clippy::declare_interior_mutable_const)] const ZERO: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); pub static DEM_STATS: DemStats = DemStats { max_bits: [ZERO; 15], ss_micro: [ZERO; 15], nodes: [ZERO; 15], grids: [ZERO; 15], cells: [ZERO; 15], }; impl DemStats { fn record(&self, z: u8, full: &Heightmap, out: &Heightmap) { use std::sync::atomic::Ordering::Relaxed; let z = (z as usize).min(14); let (mx, ss) = grid_error(full, out); // Non-negative f64s order like their bit patterns. self.max_bits[z].fetch_max(mx.to_bits(), Relaxed); self.ss_micro[z].fetch_add((ss * 1e6).round() as u64, Relaxed); self.nodes[z].fetch_add((full.dim as u64).pow(2), Relaxed); self.grids[z].fetch_add(1, Relaxed); self.cells[z].fetch_add((out.dim as u64).pow(2), Relaxed); } pub fn report(&self) { use std::sync::atomic::Ordering::Relaxed; println!("DEM grids (error vs the full dim^2-sample dataset grid, metres):"); let (mut gmx, mut gss, mut gn) = (0.0f64, 0.0f64, 0u64); for z in 0..15 { let g = self.grids[z].load(Relaxed); if g == 0 { continue; } let mx = f64::from_bits(self.max_bits[z].load(Relaxed)); let ss = self.ss_micro[z].load(Relaxed) as f64 / 1e6; let n = self.nodes[z].load(Relaxed); gmx = gmx.max(mx); gss += ss; gn += n; println!( " DEMSTAT z{z:<2} grids {g:>10} avg_cells {:>6.1} max_err {mx:>7.2} rms_err {:>7.3}", self.cells[z].load(Relaxed) as f64 / g as f64, (ss / n.max(1) as f64).sqrt() ); } println!(" DEMSTAT all max_err {gmx:.2} rms_err {:.3}", (gss / gn.max(1) as f64).sqrt()); } } /// 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: Grids, } /// The dataset's grids as one sorted id column and one contiguous sample column. /// /// Was a `HashMap>`: on the 13 GB world dataset that is ~76 M allocations and a /// single-threaded fold of ~76 M inserts on every build regardless of region (the bulk of a /// 12-24 s `dem-load` at ~5 cores), plus the map's own slack. Here both columns are built on the /// pool and a lookup is a binary search. Same answers as the map for every id, including a file /// that repeats one: the map kept the **last** insert, and so does [`Grids::build`]. struct Grids { /// Tile ids, strictly ascending. ids: Vec, /// `ids.len() * cells` samples; tile `i`'s grid is `samples[i * cells..][..cells]`. samples: Vec, cells: usize, } impl Grids { /// From `(id, file index)` for every record and a way to fill a grid from a record index. /// Ids are sorted (already ascending in a `dem_ingest` file, which is checked rather than /// assumed) and a repeated id keeps its last record, as `HashMap::insert` in file order did. fn build(mut keys: Vec<(u64, usize)>, cells: usize, fill: F) -> Grids where F: Fn(usize, &mut [u16]) + Sync, { let ascending = keys.par_windows(2).all(|w| w[0].0 < w[1].0); if !ascending { // (id, index) is a total order with unique keys, so the sort is deterministic; the // last of each id's run is its last record in the file. keys.par_sort_unstable(); let mut kept: Vec<(u64, usize)> = Vec::with_capacity(keys.len()); for k in keys { match kept.last_mut() { Some(last) if last.0 == k.0 => *last = k, _ => kept.push(k), } } keys = kept; } let mut samples = vec![0u16; keys.len() * cells]; if cells > 0 { samples .par_chunks_mut(cells) .zip(keys.par_iter()) .for_each(|(grid, &(_, index))| fill(index, grid)); } Grids { ids: keys.into_iter().map(|(id, _)| id).collect(), samples, cells } } fn get(&self, id: &u64) -> Option<&[u16]> { let i = self.ids.binary_search(id).ok()?; Some(&self.samples[i * self.cells..(i + 1) * self.cells]) } } include!("dem_s1.rs");