1use std::borrow::Cow;
11use std::path::{Path, PathBuf};
12use std::sync::{Mutex, PoisonError};
13
14use geolith::error::{GeolithError, Result};
15
16use crate::terrain::cog::Cog;
17use crate::terrain::crs::Crs;
18use crate::terrain::dem::{Dem, GeoTransform};
19use crate::terrain::source::{Bounds, ElevationSource};
20
21const METRES_PER_DEGREE: f64 = 111_320.0;
23
24const EDGE_SAMPLES: usize = 8;
27
28const MAX_IDLE_READERS: usize = 1;
31
32const WINDOW_PAD: i64 = 2;
35
36#[derive(Debug)]
38struct MosaicSource {
39 path: PathBuf,
40 crs: Crs,
41 bounds: Bounds,
42 levels: Vec<(u32, u32, GeoTransform)>,
44 readers: Mutex<Vec<Cog>>,
46 range: Option<(f32, f32)>,
47}
48
49#[derive(Debug)]
51pub struct CogMosaic {
52 sources: Vec<MosaicSource>,
53 epsg: u32,
54}
55
56impl CogMosaic {
57 pub fn open(paths: &[PathBuf], crs_override: Option<Crs>) -> Result<Self> {
66 if paths.is_empty() {
67 return Err(GeolithError::GeoTiff("no DEM files to read".into()));
68 }
69 let mut sources = Vec::with_capacity(paths.len());
70 for path in paths {
71 sources.push(open_source(path, crs_override)?);
72 }
73 let epsg = sources[0].crs.epsg();
74 Ok(Self { sources, epsg })
75 }
76
77 #[must_use]
79 pub const fn len(&self) -> usize {
80 self.sources.len()
81 }
82
83 #[must_use]
86 pub const fn is_empty(&self) -> bool {
87 self.sources.is_empty()
88 }
89}
90
91impl ElevationSource for CogMosaic {
92 fn wgs84_bounds(&self) -> Bounds {
93 self.sources.iter().map(|s| s.bounds).fold(
94 (
95 f64::INFINITY,
96 f64::INFINITY,
97 f64::NEG_INFINITY,
98 f64::NEG_INFINITY,
99 ),
100 |a, b| (a.0.min(b.0), a.1.min(b.1), a.2.max(b.2), a.3.max(b.3)),
101 )
102 }
103
104 fn elevation_range(&self) -> Option<(f32, f32)> {
105 self.sources
106 .iter()
107 .filter_map(|s| s.range)
108 .reduce(|a, b| (a.0.min(b.0), a.1.max(b.1)))
109 }
110
111 fn source_epsg(&self) -> u32 {
112 self.epsg
113 }
114
115 fn patches(&self, bounds: Bounds, metres_per_pixel: f64) -> Result<Vec<Cow<'_, Dem>>> {
116 let mut patches = Vec::with_capacity(2);
117 for source in self.sources.iter().filter(|s| overlaps(s.bounds, bounds)) {
118 if let Some(dem) = source.window(bounds, metres_per_pixel)? {
119 patches.push(Cow::Owned(dem));
120 }
121 }
122 Ok(patches)
123 }
124}
125
126impl MosaicSource {
127 fn window(&self, bounds: Bounds, metres_per_pixel: f64) -> Result<Option<Dem>> {
130 let centre_lat = f64::midpoint(bounds.1, bounds.3);
131 let level = pick_level(&self.levels, self.crs, centre_lat, metres_per_pixel);
132 let (width, height, transform) = self.levels[level];
133
134 let (mut min_c, mut min_r) = (f64::INFINITY, f64::INFINITY);
135 let (mut max_c, mut max_r) = (f64::NEG_INFINITY, f64::NEG_INFINITY);
136 for (lon, lat) in edge_points(bounds) {
137 let (x, y) = self.crs.from_wgs84(lon, lat);
138 let (c, r) = transform.to_pixel(x, y);
139 min_c = min_c.min(c);
140 min_r = min_r.min(r);
141 max_c = max_c.max(c);
142 max_r = max_r.max(r);
143 }
144 let x0 = (min_c.floor() as i64 - WINDOW_PAD).max(0);
145 let y0 = (min_r.floor() as i64 - WINDOW_PAD).max(0);
146 let x1 = (max_c.ceil() as i64 + WINDOW_PAD).min(i64::from(width));
147 let y1 = (max_r.ceil() as i64 + WINDOW_PAD).min(i64::from(height));
148 if x0 >= x1 || y0 >= y1 {
149 return Ok(None);
150 }
151 let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
152
153 let mut reader = self.take_reader()?;
154 let read = reader.read_window(level, x0, y0, w, h);
155 let mut idle = self.readers.lock().unwrap_or_else(PoisonError::into_inner);
156 if idle.len() < MAX_IDLE_READERS {
157 idle.push(reader);
158 }
159 drop(idle);
160 let values = read?;
161
162 Ok(Some(Dem {
163 width: w,
164 height: h,
165 values,
166 transform: GeoTransform {
167 origin_x: transform.origin_x + x0 as f64 * transform.pixel_width,
168 origin_y: transform.origin_y - y0 as f64 * transform.pixel_height,
169 pixel_width: transform.pixel_width,
170 pixel_height: transform.pixel_height,
171 },
172 crs: self.crs,
173 }))
174 }
175
176 fn take_reader(&self) -> Result<Cog> {
178 let free = self
179 .readers
180 .lock()
181 .unwrap_or_else(PoisonError::into_inner)
182 .pop();
183 match free {
184 Some(reader) => Ok(reader),
185 None => Cog::open(&self.path, Some(self.crs)),
186 }
187 }
188}
189
190pub fn dem_files(path: &Path) -> Result<Vec<PathBuf>> {
198 if !path.is_dir() {
199 return Ok(vec![path.to_path_buf()]);
200 }
201 let mut files = Vec::with_capacity(64);
202 for entry in std::fs::read_dir(path)? {
203 let file = entry?.path();
204 let is_tiff = file
205 .extension()
206 .and_then(|e| e.to_str())
207 .is_some_and(|e| e.eq_ignore_ascii_case("tif") || e.eq_ignore_ascii_case("tiff"));
208 if is_tiff && file.is_file() {
209 files.push(file);
210 }
211 }
212 if files.is_empty() {
213 return Err(GeolithError::GeoTiff(format!(
214 "{}: no .tif or .tiff files in the directory",
215 path.display()
216 )));
217 }
218 files.sort();
219 Ok(files)
220}
221
222fn open_source(path: &Path, crs_override: Option<Crs>) -> Result<MosaicSource> {
224 let mut cog = Cog::open(path, crs_override)?;
225 let crs = cog.crs();
226 let mut levels = Vec::with_capacity(cog.levels());
227 for level in 0..cog.levels() {
228 if let (Some((w, h)), Some(t)) = (cog.size(level), cog.geo_transform(level)) {
229 levels.push((w, h, t));
230 }
231 }
232 let (w0, h0, t0) = levels[0];
233 let smallest = levels.len() - 1;
234 let (ws, hs, _) = levels[smallest];
235 let range = value_range(&cog.read_window(smallest, 0, 0, ws, hs)?);
236
237 let dem = Dem {
238 width: w0,
239 height: h0,
240 values: Vec::new(),
241 transform: t0,
242 crs,
243 };
244 Ok(MosaicSource {
245 path: path.to_path_buf(),
246 crs,
247 bounds: dem.wgs84_bounds(),
248 levels,
249 readers: Mutex::new(vec![cog]),
250 range,
251 })
252}
253
254fn value_range(values: &[f32]) -> Option<(f32, f32)> {
256 values
257 .iter()
258 .filter(|v| !v.is_nan())
259 .fold(None, |acc, &v| match acc {
260 None => Some((v, v)),
261 Some((lo, hi)) => Some((lo.min(v), hi.max(v))),
262 })
263}
264
265fn pick_level(
268 levels: &[(u32, u32, GeoTransform)],
269 crs: Crs,
270 lat: f64,
271 metres_per_pixel: f64,
272) -> usize {
273 let scale = metres_per_unit(crs, lat);
274 levels
275 .iter()
276 .rposition(|(_, _, t)| t.pixel_width * scale <= metres_per_pixel)
277 .unwrap_or(0)
278}
279
280fn metres_per_unit(crs: Crs, lat: f64) -> f64 {
282 match crs {
283 Crs::Wgs84 => METRES_PER_DEGREE * lat.to_radians().cos(),
284 Crs::WebMercator => lat.to_radians().cos(),
285 _ => 1.0,
286 }
287}
288
289fn edge_points(bounds: Bounds) -> Vec<(f64, f64)> {
291 let (min_lon, min_lat, max_lon, max_lat) = bounds;
292 let mut points = Vec::with_capacity(4 * (EDGE_SAMPLES + 1));
293 for i in 0..=EDGE_SAMPLES {
294 let t = i as f64 / EDGE_SAMPLES as f64;
295 let lon = min_lon + t * (max_lon - min_lon);
296 let lat = min_lat + t * (max_lat - min_lat);
297 points.extend([
298 (lon, min_lat),
299 (lon, max_lat),
300 (min_lon, lat),
301 (max_lon, lat),
302 ]);
303 }
304 points
305}
306
307fn overlaps(a: Bounds, b: Bounds) -> bool {
309 a.0 <= b.2 && b.0 <= a.2 && a.1 <= b.3 && b.1 <= a.3
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 fn transform(pixel: f64) -> GeoTransform {
317 GeoTransform {
318 origin_x: 500_000.0,
319 origin_y: 2_100_000.0,
320 pixel_width: pixel,
321 pixel_height: pixel,
322 }
323 }
324
325 #[test]
326 fn pick_level_takes_the_coarsest_level_fine_enough() {
327 let levels = [
328 (8, 8, transform(15.0)),
329 (4, 4, transform(30.0)),
330 (2, 2, transform(60.0)),
331 ];
332 let utm = Crs::from_epsg(32_643).expect("UTM 43N");
333 assert_eq!(
334 pick_level(&levels, utm, 19.0, 10.0),
335 0,
336 "finer than level 0"
337 );
338 assert_eq!(pick_level(&levels, utm, 19.0, 15.0), 0);
339 assert_eq!(pick_level(&levels, utm, 19.0, 45.0), 1);
340 assert_eq!(pick_level(&levels, utm, 19.0, 1000.0), 2);
341 }
342
343 #[test]
345 fn geographic_pixels_are_sized_in_ground_metres() {
346 let levels = [
347 (8, 8, transform(1.0 / 3600.0)),
348 (4, 4, transform(2.0 / 3600.0)),
349 ];
350 assert_eq!(pick_level(&levels, Crs::Wgs84, 0.0, 31.0), 0);
351 assert_eq!(pick_level(&levels, Crs::Wgs84, 0.0, 62.0), 1);
352 assert_eq!(pick_level(&levels, Crs::Wgs84, 60.0, 31.0), 1);
354 }
355
356 #[test]
359 fn web_mercator_metres_shrink_with_latitude() {
360 assert!((metres_per_unit(Crs::WebMercator, 0.0) - 1.0).abs() < 1e-12);
361 assert!((metres_per_unit(Crs::WebMercator, 60.0) - 0.5).abs() < 1e-12);
362 }
363
364 #[test]
365 fn value_range_skips_nan() {
366 assert_eq!(
367 value_range(&[f32::NAN, 3.0, -2.0, f32::NAN]),
368 Some((-2.0, 3.0))
369 );
370 assert_eq!(value_range(&[f32::NAN]), None);
371 assert_eq!(value_range(&[]), None);
372 }
373
374 #[test]
375 fn overlaps_counts_a_shared_edge_and_rejects_a_gap() {
376 assert!(overlaps((0.0, 0.0, 1.0, 1.0), (1.0, 0.0, 2.0, 1.0)));
377 assert!(!overlaps((0.0, 0.0, 1.0, 1.0), (1.5, 0.0, 2.0, 1.0)));
378 }
379
380 #[test]
381 fn edge_points_include_all_four_corners() {
382 let points = edge_points((1.0, 2.0, 3.0, 4.0));
383 for corner in [(1.0, 2.0), (3.0, 2.0), (1.0, 4.0), (3.0, 4.0)] {
384 assert!(points.contains(&corner), "missing corner {corner:?}");
385 }
386 }
387
388 #[test]
389 fn dem_files_lists_tiffs_in_path_order_and_skips_other_files() {
390 let dir = tempfile::tempdir().expect("tempdir");
391 for name in ["b.tif", "a.TIFF", "c.tif.aux.xml", "notes.txt"] {
392 std::fs::write(dir.path().join(name), b"").expect("write");
393 }
394 std::fs::create_dir(dir.path().join("d.tif")).expect("dir named like a tiff");
395 let names: Vec<String> = dem_files(dir.path())
396 .expect("listed")
397 .iter()
398 .filter_map(|p| p.file_name()?.to_str().map(str::to_owned))
399 .collect();
400 assert_eq!(names, ["a.TIFF", "b.tif"]);
401 }
402
403 #[test]
404 fn dem_files_passes_a_file_through_and_rejects_an_empty_directory() {
405 let dir = tempfile::tempdir().expect("tempdir");
406 let file = dir.path().join("x.tif");
407 assert_eq!(dem_files(&file).expect("file"), std::slice::from_ref(&file));
408 assert!(dem_files(dir.path()).is_err(), "no tiffs yet");
409 }
410
411 #[test]
412 fn opening_no_files_is_an_error() {
413 assert!(CogMosaic::open(&[], None).is_err());
414 }
415}