Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / dem.rs

dem.rs259 lines · 10.6 KiBRaw
1//! Sample the `.mdem` heightmap dataset (`dem_ingest`) at graph-node coordinates so
2//! `write_graph` can bake a per-node elevation into `elevation.bin` — the build side of
3//! WS-G's route elevation profile.
4//!
5//! `dem_ingest` fetches AWS terrarium PNG tiles and downsamples them into one small square `u16`
6//! grid per map tile at a single zoom (`--out-zoom`, default 14; `--dim`, default 17), each sample
7//! `metres + 32768` row-major from the tile's top-left. That is exactly the layout
8//! `mamaps_build`'s `dem.rs` and the wire `Heightmap` carry; this is a *self-contained* reader —
9//! `osm_ingest` is deliberately detached from the Android workspace (see `Cargo.toml`), so it
10//! parses the format and reproduces the PMTiles Hilbert tile id itself rather than depending on
11//! `tilecodec`.
12//!
13//! [`Dem::sample_metres`] bilinearly interpolates a single lon/lat within the dataset grid that
14//! covers it, returning **metres** (already un-biased), or `None` when no fetched grid covers the
15//! point — a node off the DEM coverage (open ocean, or outside the build bbox) bakes as 0.
16
17use std::collections::HashMap;
18use std::f64::consts::PI;
19use std::path::Path;
20
21use crate::proto::{err, Result};
22
23/// The `.mdem` dataset's magic and version, as `dem_ingest` writes them.
24const MAGIC: &[u8; 4] = b"MDEM";
25const VERSION: u8 = 1;
26
27/// The biased `u16` for zero metres: sea level, and the bias every terrarium sample carries.
28const SEA_LEVEL: i32 = 32768;
29
30/// A loaded `.mdem` dataset: one `u16` grid per output tile, keyed by PMTiles tile id at the
31/// dataset's own zoom.
32pub struct Dem {
33 /// The zoom the grids were sampled at.
34 out_zoom: u8,
35 /// The grid side length, so every grid is `dim * dim` samples. Shared by every tile.
36 dim: u16,
37 /// `tile_id(out_zoom, x, y)` -> the tile's `dim * dim` samples, row-major from its top-left.
38 grids: HashMap<u64, Vec<u16>>,
39}
40
41impl Dem {
42 /// Read and parse a `.mdem` dataset from disk.
43 pub fn load(path: &Path) -> Result<Dem> {
44 let bytes = std::fs::read(path).map_err(|e| {
45 crate::proto::Error(format!("reading the DEM dataset {}: {e}", path.display()))
46 })?;
47 Dem::parse(&bytes)
48 }
49
50 /// Parse a `.mdem` dataset: a 12-byte header (`MDEM`, version, out_zoom, `dim` u16, tile count
51 /// u32), then per tile a `u64` tile id and its `dim * dim` `u16` samples, little-endian.
52 fn parse(bytes: &[u8]) -> Result<Dem> {
53 if bytes.len() < 12 {
54 return err("a .mdem dataset is shorter than its 12-byte header");
55 }
56 if &bytes[0..4] != MAGIC {
57 return err("not a .mdem dataset (bad magic)");
58 }
59 if bytes[4] != VERSION {
60 return err(format!(
61 "unsupported .mdem version {} (this build reads {VERSION})",
62 bytes[4]
63 ));
64 }
65 let out_zoom = bytes[5];
66 let dim = u16::from_le_bytes([bytes[6], bytes[7]]);
67 if dim < 2 {
68 return err("a .mdem grid dimension is less than 2");
69 }
70 let count = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
71 let cells = dim as usize * dim as usize;
72 // One tile: an 8-byte id then `cells` little-endian u16 samples.
73 let stride = 8 + cells * 2;
74 let mut at = 12usize;
75 let mut grids = HashMap::with_capacity(count);
76 for _ in 0..count {
77 if at + stride > bytes.len() {
78 return err("a .mdem tile runs past the end of the dataset");
79 }
80 let id = u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes"));
81 at += 8;
82 let mut samples = Vec::with_capacity(cells);
83 for i in 0..cells {
84 let o = at + i * 2;
85 samples.push(u16::from_le_bytes([bytes[o], bytes[o + 1]]));
86 }
87 at += cells * 2;
88 grids.insert(id, samples);
89 }
90 Ok(Dem { out_zoom, dim, grids })
91 }
92
93 /// Elevation in **metres** at one lon/lat, bilinearly interpolated within the dataset grid that
94 /// covers it, or `None` when that grid was not fetched (the node bakes as 0 metres).
95 pub fn sample_metres(&self, lon: f64, lat: f64) -> Option<i16> {
96 let biased = self.sample_biased(lon, lat)?;
97 Some((i32::from(biased) - SEA_LEVEL).clamp(i16::MIN as i32, i16::MAX as i32) as i16)
98 }
99
100 /// The raw biased `u16` sample (metres + 32768), or `None` off coverage. Mirrors the sampler in
101 /// `mamaps_build`'s `dem.rs` so a bake lands where the ingest would have sampled.
102 fn sample_biased(&self, lon: f64, lat: f64) -> Option<u16> {
103 let n = (1u64 << self.out_zoom) as f64;
104 // The fractional tile position at the dataset zoom. Clamped so a point exactly on the
105 // world's right/bottom edge lands in the last tile rather than one past it.
106 let tx = lon_to_tile_x(lon, self.out_zoom).clamp(0.0, n - f64::EPSILON);
107 let ty = lat_to_tile_y(lat, self.out_zoom).clamp(0.0, n - f64::EPSILON);
108 let ix = tx.floor() as u64;
109 let iy = ty.floor() as u64;
110 let grid = self.grids.get(&tile_id(self.out_zoom, ix, iy))?;
111 let last = self.dim as usize - 1;
112 // The point's position within the tile's grid: the fraction across the tile scaled onto the
113 // `dim - 1` cells between the grid's edge samples.
114 let gx = (tx - ix as f64) * last as f64;
115 let gy = (ty - iy as f64) * last as f64;
116 let x0 = gx.floor() as usize;
117 let y0 = gy.floor() as usize;
118 let x1 = (x0 + 1).min(last);
119 let y1 = (y0 + 1).min(last);
120 let fx = gx - x0 as f64;
121 let fy = gy - y0 as f64;
122 let d = self.dim as usize;
123 let at = |cx: usize, cy: usize| grid[cy * d + cx] as f64;
124 let top = at(x0, y0) * (1.0 - fx) + at(x1, y0) * fx;
125 let bot = at(x0, y1) * (1.0 - fx) + at(x1, y1) * fx;
126 let v = top * (1.0 - fy) + bot * fy;
127 Some(v.round().clamp(0.0, u16::MAX as f64) as u16)
128 }
129}
130
131// --- PMTiles Hilbert tile ids (a self-contained copy of `tilecodec::pmtiles::tile_id`, so a
132// dataset written with that function reads back here without a `tilecodec` dependency) ---
133
134/// Number of tiles in every zoom below `z`, i.e. the first tile id at `z`. `(4^z - 1) / 3`.
135fn zoom_base(z: u8) -> u64 {
136 ((1u64 << (2 * z as u32)) - 1) / 3
137}
138
139/// Rotate/flip a quadrant. The canonical Hilbert helper.
140fn rot(n: u64, x: &mut u64, y: &mut u64, rx: u64, ry: u64) {
141 if ry == 0 {
142 if rx == 1 {
143 *x = n.wrapping_sub(1).wrapping_sub(*x);
144 *y = n.wrapping_sub(1).wrapping_sub(*y);
145 }
146 std::mem::swap(x, y);
147 }
148}
149
150/// `(z, x, y)` -> PMTiles tile id.
151fn tile_id(z: u8, x: u64, y: u64) -> u64 {
152 let n = 1u64 << z;
153 let (mut x, mut y) = (x, y);
154 let mut d = 0u64;
155 let mut s = n / 2;
156 while s > 0 {
157 let rx = u64::from(x & s > 0);
158 let ry = u64::from(y & s > 0);
159 d += s * s * ((3 * rx) ^ ry);
160 rot(n, &mut x, &mut y, rx, ry);
161 s /= 2;
162 }
163 zoom_base(z) + d
164}
165
166// --- slippy / web-mercator tile math, matching `dem_ingest` / `mamaps_build`'s `dem.rs` ---
167
168fn lon_to_tile_x(lon: f64, z: u8) -> f64 {
169 (lon + 180.0) / 360.0 * (1u64 << z) as f64
170}
171
172fn lat_to_tile_y(lat: f64, z: u8) -> f64 {
173 let r = lat.clamp(-85.05112878, 85.05112878).to_radians();
174 (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 /// Serialise a synthetic `.mdem` dataset the way `dem_ingest` does, for the parser to read back.
182 fn dataset(out_zoom: u8, dim: u16, tiles: &[(u64, Vec<u16>)]) -> Vec<u8> {
183 let mut out = Vec::new();
184 out.extend_from_slice(MAGIC);
185 out.push(VERSION);
186 out.push(out_zoom);
187 out.extend_from_slice(&dim.to_le_bytes());
188 out.extend_from_slice(&(tiles.len() as u32).to_le_bytes());
189 for (id, grid) in tiles {
190 out.extend_from_slice(&id.to_le_bytes());
191 for &s in grid {
192 out.extend_from_slice(&s.to_le_bytes());
193 }
194 }
195 out
196 }
197
198 /// A ramp grid whose sample at `(col, row)` is `32768 + row * 10 + col`.
199 fn ramp(dim: u16) -> Vec<u16> {
200 let d = dim as usize;
201 let mut g = Vec::with_capacity(d * d);
202 for row in 0..d {
203 for col in 0..d {
204 g.push(SEA_LEVEL as u16 + (row * 10 + col) as u16);
205 }
206 }
207 g
208 }
209
210 /// The lon/lat at the top-left corner of a dataset tile, so a sample there hits grid cell (0,0).
211 fn tile_top_left(z: u8, x: u64, y: u64) -> (f64, f64) {
212 let n = (1u64 << z) as f64;
213 let lon = x as f64 / n * 360.0 - 180.0;
214 let ang = PI * (1.0 - 2.0 * y as f64 / n);
215 let lat = ang.sinh().atan().to_degrees();
216 (lon, lat)
217 }
218
219 #[test]
220 fn samples_read_back_as_unbiased_metres_over_synthetic_terrain() {
221 let (z, dim) = (14u8, 17u16);
222 let (x, y) = (2730u64, 6335u64);
223 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), ramp(dim))])).expect("parse");
224 // The tile's top-left corner is grid cell (0, 0) == SEA_LEVEL, i.e. 0 metres.
225 let (lon, lat) = tile_top_left(z, x, y);
226 assert_eq!(dem.sample_metres(lon, lat), Some(0), "corner is sea level = 0 m");
227 }
228
229 #[test]
230 fn a_point_off_coverage_has_no_sample() {
231 let (z, dim) = (14u8, 17u16);
232 let dem =
233 Dem::parse(&dataset(z, dim, &[(tile_id(z, 2730, 6335), ramp(dim))])).expect("parse");
234 // Antarctica, nowhere near the one fetched California tile.
235 assert!(dem.sample_metres(0.0, -80.0).is_none(), "a point off coverage bakes as 0");
236 }
237
238 #[test]
239 fn interior_terrain_interpolates_to_a_positive_elevation() {
240 let (z, dim) = (14u8, 17u16);
241 let (x, y) = (2730u64, 6335u64);
242 let dem = Dem::parse(&dataset(z, dim, &[(tile_id(z, x, y), ramp(dim))])).expect("parse");
243 // A point a third of the way into the tile is inside the ramp, so strictly above sea level.
244 let n = (1u64 << z) as f64;
245 let lon = (x as f64 + 0.5) / n * 360.0 - 180.0;
246 let ang = PI * (1.0 - 2.0 * (y as f64 + 0.5) / n);
247 let lat = ang.sinh().atan().to_degrees();
248 assert!(dem.sample_metres(lon, lat).unwrap() > 0, "interior of the ramp is above 0 m");
249 }
250
251 #[test]
252 fn a_short_dataset_is_refused() {
253 assert!(Dem::parse(b"MDE").is_err(), "shorter than the header");
254 assert!(Dem::parse(b"XXXX\x01\x0e\x11\x00\x00\x00\x00\x00").is_err(), "bad magic");
255 let mut short = dataset(14, 17, &[]);
256 short[8] = 1; // claim one tile with no bytes behind it
257 assert!(Dem::parse(&short).is_err(), "a claimed tile past the end is refused");
258 }
259}