Skip to main content

geolith_tiles_builder/terrain/
mosaic.rs

1//! A set of `GeoTIFFs` rendered as one elevation surface, read window by
2//! window so memory follows the output tile instead of the input size.
3//!
4//! Each tile reads, from every source it overlaps, only the pixels under
5//! it, at the coarsest overview that still has at least the tile's
6//! resolution. Sources may use different CRSs (one UTM zone each, for
7//! example); where they overlap, the first source in the given order wins,
8//! so a later source only fills pixels an earlier one leaves as nodata.
9//!
10//! A planet DEM is ~26,000 files, more than a process may keep open, so a
11//! source's reader is opened when a tile needs it and parked in a bounded
12//! pool: the descriptors a build holds follow the pool, not the source count.
13
14use std::borrow::Cow;
15use std::path::{Path, PathBuf};
16use std::sync::{Mutex, PoisonError};
17
18use geolith::error::{GeolithError, Result};
19
20use crate::terrain::cog::Cog;
21use crate::terrain::crs::Crs;
22use crate::terrain::dem::{Dem, GeoTransform};
23use crate::terrain::source::{Bounds, ElevationSource};
24
25/// Metres per degree of latitude on the WGS84 sphere approximation.
26const METRES_PER_DEGREE: f64 = 111_320.0;
27
28/// Points sampled along each tile edge when projecting it into a source
29/// CRS; edges curve in a transverse Mercator grid.
30const EDGE_SAMPLES: usize = 8;
31
32/// Idle readers kept across tiles. A planet DEM is ~26,000 files and holding
33/// one reader per source exceeds the 10,240-file hard limit of macOS, so the
34/// pool bounds what a build keeps open: sources are opened on demand and the
35/// oldest reader is closed once the pool is full.
36const MAX_OPEN_READERS: usize = 32;
37
38/// Extra source pixels read around a window so bilinear sampling at the
39/// tile edge has all four neighbours.
40const WINDOW_PAD: i64 = 2;
41
42/// One input raster of a mosaic: where it is and what it covers, with no
43/// reader held (see [`ReaderPool`]).
44#[derive(Debug)]
45struct MosaicSource {
46    path: PathBuf,
47    crs: Crs,
48    bounds: Bounds,
49    /// `(width, height, transform)` per level, full resolution first.
50    levels: Vec<(u32, u32, GeoTransform)>,
51    range: Option<(f32, f32)>,
52}
53
54/// Open readers, keyed by source path, shared by every tile in flight.
55///
56/// A window takes its source's reader (opening the file when the pool holds
57/// none) and puts it back, so the descriptors a build holds follow this pool
58/// and not the number of sources.
59#[derive(Debug, Default)]
60struct ReaderPool {
61    open: Vec<(PathBuf, Cog)>,
62}
63
64impl ReaderPool {
65    /// The reader for `path`: a parked one, or a new open of the file.
66    fn take(&mut self, path: &Path, crs: Crs) -> Result<Cog> {
67        let parked = self.open.iter().position(|(open, _)| open == path);
68        match parked {
69            Some(index) => Ok(self.open.swap_remove(index).1),
70            None => Cog::open(path, Some(crs)),
71        }
72    }
73
74    /// Park `reader` for `path`, closing the oldest first when full.
75    fn put(&mut self, path: PathBuf, reader: Cog) {
76        if self.open.len() >= MAX_OPEN_READERS {
77            self.open.remove(0);
78        }
79        self.open.push((path, reader));
80    }
81}
82
83/// `GeoTIFFs` rendered as one elevation surface.
84#[derive(Debug)]
85pub struct CogMosaic {
86    sources: Vec<MosaicSource>,
87    epsg: u32,
88    readers: Mutex<ReaderPool>,
89}
90
91impl CogMosaic {
92    /// Open every path as one mosaic, in the given order.
93    ///
94    /// `crs_override` applies to every source. Each source is read once, for
95    /// its bounds, levels and elevation range, and closed; tiles open readers
96    /// from a bounded pool, so a planet of 26,000 files fits in a process.
97    ///
98    /// # Errors
99    ///
100    /// Returns an error when `paths` is empty or a source cannot be read.
101    pub fn open(paths: &[PathBuf], crs_override: Option<Crs>) -> Result<Self> {
102        if paths.is_empty() {
103            return Err(GeolithError::GeoTiff("no DEM files to read".into()));
104        }
105        let mut sources = Vec::with_capacity(paths.len());
106        for path in paths {
107            sources.push(open_source(path, crs_override)?);
108        }
109        let epsg = sources[0].crs.epsg();
110        Ok(Self {
111            sources,
112            epsg,
113            readers: Mutex::new(ReaderPool::default()),
114        })
115    }
116
117    /// Number of source rasters.
118    #[must_use]
119    pub const fn len(&self) -> usize {
120        self.sources.len()
121    }
122
123    /// `true` when the mosaic has no sources; [`CogMosaic::open`] never
124    /// returns such a mosaic.
125    #[must_use]
126    pub const fn is_empty(&self) -> bool {
127        self.sources.is_empty()
128    }
129}
130
131impl ElevationSource for CogMosaic {
132    fn wgs84_bounds(&self) -> Bounds {
133        self.sources.iter().map(|s| s.bounds).fold(
134            (
135                f64::INFINITY,
136                f64::INFINITY,
137                f64::NEG_INFINITY,
138                f64::NEG_INFINITY,
139            ),
140            |a, b| (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)),
141        )
142    }
143
144    fn elevation_range(&self) -> Option<(f32, f32)> {
145        self.sources
146            .iter()
147            .filter_map(|s| s.range)
148            .reduce(|a, b| (a.0.min(b.0), a.1.max(b.1)))
149    }
150
151    fn source_epsg(&self) -> u32 {
152        self.epsg
153    }
154
155    fn patches(&self, bounds: Bounds, metres_per_pixel: f64) -> Result<Vec<Cow<'_, Dem>>> {
156        let mut patches = Vec::with_capacity(2);
157        for source in self.sources.iter().filter(|s| overlaps(s.bounds, bounds)) {
158            let mut reader = {
159                let mut pool = self.readers.lock().unwrap_or_else(PoisonError::into_inner);
160                pool.take(&source.path, source.crs)?
161            };
162            let window = source.window(&mut reader, bounds, metres_per_pixel);
163            let mut pool = self.readers.lock().unwrap_or_else(PoisonError::into_inner);
164            pool.put(source.path.clone(), reader);
165            drop(pool);
166            if let Some(dem) = window? {
167                patches.push(Cow::Owned(dem));
168            }
169        }
170        Ok(patches)
171    }
172}
173
174impl MosaicSource {
175    /// Source pixels under `bounds` as a small [`Dem`], or `None` when the
176    /// footprint misses the raster.
177    fn window(
178        &self,
179        reader: &mut Cog,
180        bounds: Bounds,
181        metres_per_pixel: f64,
182    ) -> Result<Option<Dem>> {
183        let centre_lat = f64::midpoint(bounds.1, bounds.3);
184        let level = pick_level(&self.levels, self.crs, centre_lat, metres_per_pixel);
185        let (width, height, transform) = self.levels[level];
186
187        let (mut min_c, mut min_r) = (f64::INFINITY, f64::INFINITY);
188        let (mut max_c, mut max_r) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
189        for (lon, lat) in edge_points(bounds) {
190            let (x, y) = self.crs.from_wgs84(lon, lat);
191            let (c, r) = transform.to_pixel(x, y);
192            min_c = min_c.min(c);
193            min_r = min_r.min(r);
194            max_c = max_c.max(c);
195            max_r = max_r.max(r);
196        }
197        let x0 = (min_c.floor() as i64 - WINDOW_PAD).max(0);
198        let y0 = (min_r.floor() as i64 - WINDOW_PAD).max(0);
199        let x1 = (max_c.ceil() as i64 + WINDOW_PAD).min(i64::from(width));
200        let y1 = (max_r.ceil() as i64 + WINDOW_PAD).min(i64::from(height));
201        if x0 >= x1 || y0 >= y1 {
202            return Ok(None);
203        }
204        let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
205
206        let values = reader.read_window(level, x0, y0, w, h)?;
207
208        Ok(Some(Dem {
209            width: w,
210            height: h,
211            values,
212            transform: GeoTransform {
213                origin_x: transform.origin_x + x0 as f64 * transform.pixel_width,
214                origin_y: transform.origin_y - y0 as f64 * transform.pixel_height,
215                pixel_width: transform.pixel_width,
216                pixel_height: transform.pixel_height,
217            },
218            crs: self.crs,
219        }))
220    }
221}
222
223/// The `GeoTIFFs` a `--dem` path names: the file itself, or every `.tif` and
224/// `.tiff` file directly inside a directory, sorted by path so the mosaic
225/// order never depends on the filesystem.
226///
227/// # Errors
228///
229/// Returns an error when the directory cannot be read or holds no `GeoTIFF`.
230pub fn dem_files(path: &Path) -> Result<Vec<PathBuf>> {
231    if !path.is_dir() {
232        return Ok(vec![path.to_path_buf()]);
233    }
234    let mut files = Vec::with_capacity(64);
235    for entry in std::fs::read_dir(path)? {
236        let file = entry?.path();
237        let is_tiff = file
238            .extension()
239            .and_then(|e| e.to_str())
240            .is_some_and(|e| e.eq_ignore_ascii_case("tif") || e.eq_ignore_ascii_case("tiff"));
241        if is_tiff && file.is_file() {
242            files.push(file);
243        }
244    }
245    if files.is_empty() {
246        return Err(GeolithError::GeoTiff(format!(
247            "{}: no .tif or .tiff files in the directory",
248            path.display()
249        )));
250    }
251    files.sort();
252    Ok(files)
253}
254
255/// Open one source and read its smallest overview for the elevation range.
256fn open_source(path: &Path, crs_override: Option<Crs>) -> Result<MosaicSource> {
257    let mut cog = Cog::open(path, crs_override)?;
258    let crs = cog.crs();
259    let mut levels = Vec::with_capacity(cog.levels());
260    for level in 0..cog.levels() {
261        if let (Some((w, h)), Some(t)) = (cog.size(level), cog.geo_transform(level)) {
262            levels.push((w, h, t));
263        }
264    }
265    let (w0, h0, t0) = levels[0];
266    let smallest = levels.len() - 1;
267    let (ws, hs, _) = levels[smallest];
268    let range = value_range(&cog.read_window(smallest, 0, 0, ws, hs)?);
269    // The metadata is all the mosaic keeps: a reader held here would be one
270    // descriptor per source (see ReaderPool).
271    drop(cog);
272
273    let dem = Dem {
274        width: w0,
275        height: h0,
276        values: Vec::new(),
277        transform: t0,
278        crs,
279    };
280    Ok(MosaicSource {
281        path: path.to_path_buf(),
282        crs,
283        bounds: dem.wgs84_bounds(),
284        levels,
285        range,
286    })
287}
288
289/// Minimum and maximum of the non-NaN values.
290fn value_range(values: &[f32]) -> Option<(f32, f32)> {
291    values
292        .iter()
293        .filter(|v| !v.is_nan())
294        .fold(None, |acc, &v| match acc {
295            None => Some((v, v)),
296            Some((lo, hi)) => Some((lo.min(v), hi.max(v))),
297        })
298}
299
300/// The coarsest level whose pixels are no larger than `metres_per_pixel`,
301/// or full resolution when even that is coarser.
302fn pick_level(
303    levels: &[(u32, u32, GeoTransform)],
304    crs: Crs,
305    lat: f64,
306    metres_per_pixel: f64,
307) -> usize {
308    let scale = metres_per_unit(crs, lat);
309    levels
310        .iter()
311        .rposition(|(_, _, t)| t.pixel_width * scale <= metres_per_pixel)
312        .unwrap_or(0)
313}
314
315/// Ground metres per CRS unit at latitude `lat`.
316fn metres_per_unit(crs: Crs, lat: f64) -> f64 {
317    match crs {
318        Crs::Wgs84 => METRES_PER_DEGREE * lat.to_radians().cos(),
319        Crs::WebMercator => lat.to_radians().cos(),
320        _ => 1.0,
321    }
322}
323
324/// Points along the four edges of `bounds`, corners included.
325fn edge_points(bounds: Bounds) -> Vec<(f64, f64)> {
326    let (min_lon, min_lat, max_lon, max_lat) = bounds;
327    let mut points = Vec::with_capacity(4 * (EDGE_SAMPLES + 1));
328    for i in 0..=EDGE_SAMPLES {
329        let t = i as f64 / EDGE_SAMPLES as f64;
330        let lon = min_lon + t * (max_lon - min_lon);
331        let lat = min_lat + t * (max_lat - min_lat);
332        points.extend([
333            (lon, min_lat),
334            (lon, max_lat),
335            (min_lon, lat),
336            (max_lon, lat),
337        ]);
338    }
339    points
340}
341
342/// `true` when two geographic boxes intersect.
343fn overlaps(a: Bounds, b: Bounds) -> bool {
344    a.0 <= b.2 && b.0 <= a.2 && a.1 <= b.3 && b.1 <= a.3
345}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    fn transform(pixel: f64) -> GeoTransform {
352        GeoTransform {
353            origin_x: 500_000.0,
354            origin_y: 2_100_000.0,
355            pixel_width: pixel,
356            pixel_height: pixel,
357        }
358    }
359
360    #[test]
361    fn pick_level_takes_the_coarsest_level_fine_enough() {
362        let levels = [
363            (8, 8, transform(15.0)),
364            (4, 4, transform(30.0)),
365            (2, 2, transform(60.0)),
366        ];
367        let utm = Crs::from_epsg(32_643).expect("UTM 43N");
368        assert_eq!(
369            pick_level(&levels, utm, 19.0, 10.0),
370            0,
371            "finer than level 0"
372        );
373        assert_eq!(pick_level(&levels, utm, 19.0, 15.0), 0);
374        assert_eq!(pick_level(&levels, utm, 19.0, 45.0), 1);
375        assert_eq!(pick_level(&levels, utm, 19.0, 1000.0), 2);
376    }
377
378    /// One arc-second (1/3600°) at the equator is 111320 / 3600 = 30.9 m.
379    #[test]
380    fn geographic_pixels_are_sized_in_ground_metres() {
381        let levels = [
382            (8, 8, transform(1.0 / 3600.0)),
383            (4, 4, transform(2.0 / 3600.0)),
384        ];
385        assert_eq!(pick_level(&levels, Crs::Wgs84, 0.0, 31.0), 0);
386        assert_eq!(pick_level(&levels, Crs::Wgs84, 0.0, 62.0), 1);
387        // At 60° north a degree of longitude is half as long.
388        assert_eq!(pick_level(&levels, Crs::Wgs84, 60.0, 31.0), 1);
389    }
390
391    /// Web Mercator stretches ground by 1 / cos(lat): at 60° north one
392    /// projected metre covers half a metre of ground.
393    #[test]
394    fn web_mercator_metres_shrink_with_latitude() {
395        assert!((metres_per_unit(Crs::WebMercator, 0.0) - 1.0).abs() < 1e-12);
396        assert!((metres_per_unit(Crs::WebMercator, 60.0) - 0.5).abs() < 1e-12);
397    }
398
399    #[test]
400    fn value_range_skips_nan() {
401        assert_eq!(
402            value_range(&[f32::NAN, 3.0, -2.0, f32::NAN]),
403            Some((-2.0, 3.0))
404        );
405        assert_eq!(value_range(&[f32::NAN]), None);
406        assert_eq!(value_range(&[]), None);
407    }
408
409    #[test]
410    fn overlaps_counts_a_shared_edge_and_rejects_a_gap() {
411        assert!(overlaps((0.0, 0.0, 1.0, 1.0), (1.0, 0.0, 2.0, 1.0)));
412        assert!(!overlaps((0.0, 0.0, 1.0, 1.0), (1.5, 0.0, 2.0, 1.0)));
413    }
414
415    #[test]
416    fn edge_points_include_all_four_corners() {
417        let points = edge_points((1.0, 2.0, 3.0, 4.0));
418        for corner in [(1.0, 2.0), (3.0, 2.0), (1.0, 4.0), (3.0, 4.0)] {
419            assert!(points.contains(&corner), "missing corner {corner:?}");
420        }
421    }
422
423    #[test]
424    fn dem_files_lists_tiffs_in_path_order_and_skips_other_files() {
425        let dir = tempfile::tempdir().expect("tempdir");
426        for name in ["b.tif", "a.TIFF", "c.tif.aux.xml", "notes.txt"] {
427            std::fs::write(dir.path().join(name), b"").expect("write");
428        }
429        std::fs::create_dir(dir.path().join("d.tif")).expect("dir named like a tiff");
430        let names: Vec<String> = dem_files(dir.path())
431            .expect("listed")
432            .iter()
433            .filter_map(|p| p.file_name()?.to_str().map(str::to_owned))
434            .collect();
435        assert_eq!(names, ["a.TIFF", "b.tif"]);
436    }
437
438    #[test]
439    fn dem_files_passes_a_file_through_and_rejects_an_empty_directory() {
440        let dir = tempfile::tempdir().expect("tempdir");
441        let file = dir.path().join("x.tif");
442        assert_eq!(dem_files(&file).expect("file"), std::slice::from_ref(&file));
443        assert!(dem_files(dir.path()).is_err(), "no tiffs yet");
444    }
445
446    #[test]
447    fn opening_no_files_is_an_error() {
448        assert!(CogMosaic::open(&[], None).is_err());
449    }
450}