Skip to main content

geolith_tiles_builder/terrain/
tiler.rs

1//! Render a DEM into Terrain-RGB raster tiles and pack them into `PMTiles`.
2
3use std::path::Path;
4
5use geolith::error::{GeolithError, Result};
6use geolith::geometry::mercator::TileCoord;
7use geolith::output::hilbert::tile_to_pmtiles_id;
8use geolith::output::writer::{Compression, PmtilesWriter, TileType};
9use rayon::prelude::*;
10
11use std::sync::Arc;
12
13use geolith::terrain::range::{WORLD_EXTENT, tile_range_for_bounds};
14
15use crate::terrain::clip::{ClipMask, inside};
16use crate::terrain::encoding::TerrainEncoding;
17use crate::terrain::source::{Bounds, ElevationSource};
18
19/// Tiles rendered between two archive writes; bounds the encoded PNGs held
20/// in memory to a few hundred megabytes.
21const RENDER_BATCH: usize = 1024;
22
23/// Options controlling terrain tile generation.
24#[derive(Debug, Clone)]
25pub struct TerrainTilerOptions {
26    /// Minimum zoom level to render.
27    pub min_zoom: u8,
28    /// Maximum zoom level to render.
29    pub max_zoom: u8,
30    /// Tile edge length in pixels.
31    pub tile_size: u32,
32    /// Elevation encoding for the emitted PNGs.
33    pub encoding: TerrainEncoding,
34    /// Polygon outside which pixels are nodata and tiles are not written.
35    pub clip: Option<Arc<ClipMask>>,
36}
37
38impl Default for TerrainTilerOptions {
39    fn default() -> Self {
40        Self {
41            min_zoom: 0,
42            max_zoom: 14,
43            tile_size: 512,
44            encoding: TerrainEncoding::Mapbox,
45            clip: None,
46        }
47    }
48}
49
50/// Summary of a completed terrain tiling run.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct TerrainTileStats {
53    /// Number of tiles written to the archive.
54    pub tiles_written: u64,
55    /// Number of unique tile blobs stored after deduplication.
56    pub unique_tiles: usize,
57}
58
59/// Convert a fractional tile index back to a Web Mercator metre coordinate.
60#[must_use]
61fn tile_fraction_to_mercator(tx: f64, ty: f64, zoom: u8) -> (f64, f64) {
62    let scale = f64::from(1_u32 << zoom);
63    let x = tx / scale * 2.0 * WORLD_EXTENT - WORLD_EXTENT;
64    let y = WORLD_EXTENT - ty / scale * 2.0 * WORLD_EXTENT;
65    (x, y)
66}
67
68/// Geographic bounds of a tile as `(min_lon, min_lat, max_lon, max_lat)`.
69#[must_use]
70fn tile_wgs84_bounds(coord: TileCoord) -> (f64, f64, f64, f64) {
71    let (x0, y0) = tile_fraction_to_mercator(f64::from(coord.x), f64::from(coord.y), coord.z);
72    let (x1, y1) =
73        tile_fraction_to_mercator(f64::from(coord.x + 1), f64::from(coord.y + 1), coord.z);
74    let (min_lon, max_lat) = mercator_to_wgs84(x0, y0);
75    let (max_lon, min_lat) = mercator_to_wgs84(x1, y1);
76    (min_lon, min_lat, max_lon, max_lat)
77}
78
79/// Ground metres covered by one output pixel at the tile's centre latitude.
80#[must_use]
81fn tile_metres_per_pixel(coord: TileCoord, tile_size: u32) -> f64 {
82    let (_, min_lat, _, max_lat) = tile_wgs84_bounds(coord);
83    let centre = f64::midpoint(min_lat, max_lat).to_radians();
84    2.0 * WORLD_EXTENT * centre.cos() / f64::from(1_u32 << coord.z) / f64::from(tile_size)
85}
86
87/// Render one tile, returning `None` when no pixel has elevation data.
88///
89/// Skipping fully empty tiles keeps the archive to the DEM footprint instead
90/// of padding the whole zoom level with sea-level tiles.
91///
92/// # Errors
93///
94/// Returns an error when the source raster cannot be read.
95pub fn render_tile<S: ElevationSource + ?Sized>(
96    source: &S,
97    coord: TileCoord,
98    options: &TerrainTilerOptions,
99) -> Result<Option<Vec<u8>>> {
100    let bounds = tile_wgs84_bounds(coord);
101    if options
102        .clip
103        .as_ref()
104        .is_some_and(|c| !c.may_intersect(bounds))
105    {
106        return Ok(None);
107    }
108    let patches = source.patches(bounds, tile_metres_per_pixel(coord, options.tile_size))?;
109    if patches.is_empty() {
110        return Ok(None);
111    }
112    let size = options.tile_size as usize;
113    let mut rgb = vec![0_u8; size * size * 3];
114    let nodata = options.encoding.nodata_rgb();
115    let mut has_data = false;
116
117    for row in 0..size {
118        let ty = f64::from(coord.y) + (row as f64 + 0.5) / options.tile_size as f64;
119        let (_, row_lat) = mercator_to_wgs84(0.0, tile_fraction_to_mercator(0.0, ty, coord.z).1);
120        let crossings = options.clip.as_ref().map(|c| c.crossings(row_lat));
121        for col in 0..size {
122            let tx = f64::from(coord.x) + (col as f64 + 0.5) / options.tile_size as f64;
123            let (mx, my) = tile_fraction_to_mercator(tx, ty, coord.z);
124            let (lon, lat) = mercator_to_wgs84(mx, my);
125            let clipped = crossings.as_ref().is_some_and(|xs| !inside(xs, lon));
126            let elevation = (!clipped)
127                .then(|| {
128                    patches.iter().find_map(|dem| {
129                        let (px, py) = dem.crs.from_wgs84(lon, lat);
130                        dem.sample(px, py)
131                    })
132                })
133                .flatten();
134
135            let pixel = match elevation {
136                Some(elevation) => {
137                    has_data = true;
138                    options.encoding.encode(elevation)
139                }
140                None => nodata,
141            };
142
143            let offset = (row * size + col) * 3;
144            rgb[offset] = pixel[0];
145            rgb[offset + 1] = pixel[1];
146            rgb[offset + 2] = pixel[2];
147        }
148    }
149
150    Ok(has_data.then(|| encode_png(&rgb, options.tile_size)))
151}
152
153/// Convert Web Mercator metres to WGS84 degrees.
154#[must_use]
155fn mercator_to_wgs84(x: f64, y: f64) -> (f64, f64) {
156    const R: f64 = 6_378_137.0;
157    let lon = (x / R).to_degrees();
158    let lat = ((y / R).exp().atan() * 2.0 - std::f64::consts::FRAC_PI_2).to_degrees();
159    (lon, lat)
160}
161
162/// Encode an RGB8 buffer as a PNG.
163#[must_use]
164fn encode_png(rgb: &[u8], size: u32) -> Vec<u8> {
165    let mut out = Vec::with_capacity(rgb.len() / 3);
166    {
167        let mut encoder = png::Encoder::new(&mut out, size, size);
168        encoder.set_color(png::ColorType::Rgb);
169        encoder.set_depth(png::BitDepth::Eight);
170        encoder.set_compression(png::Compression::Balanced);
171        let mut writer = encoder
172            .write_header()
173            .expect("png header write to Vec is infallible");
174        writer
175            .write_image_data(rgb)
176            .expect("png image write to Vec is infallible");
177    }
178    out
179}
180
181/// Footprint written to the archive: the source bounds, cut to the clip
182/// polygon's bounds when one is set.
183#[must_use]
184fn archive_bounds<S: ElevationSource + ?Sized>(
185    source: &S,
186    options: &TerrainTilerOptions,
187) -> Bounds {
188    let b = source.wgs84_bounds();
189    match &options.clip {
190        Some(clip) => {
191            let c = clip.bounds();
192            (b.0.max(c.0), b.1.max(c.1), b.2.min(c.2), b.3.min(c.3))
193        }
194        None => b,
195    }
196}
197
198/// Build the `PMTiles` metadata document for a terrain archive.
199#[must_use]
200pub fn terrain_metadata<S: ElevationSource + ?Sized>(
201    source: &S,
202    options: &TerrainTilerOptions,
203    name: &str,
204) -> serde_json::Value {
205    let (min_lon, min_lat, max_lon, max_lat) = archive_bounds(source, options);
206    let (min_elev, max_elev) = source.elevation_range().unwrap_or((0.0, 0.0));
207
208    serde_json::json!({
209        "name": name,
210        "format": "png",
211        "type": "baselayer",
212        "encoding": options.encoding.maplibre_name(),
213        "tileSize": options.tile_size,
214        "minzoom": options.min_zoom,
215        "maxzoom": options.max_zoom,
216        "bounds": format!("{min_lon},{min_lat},{max_lon},{max_lat}"),
217        "center": format!(
218            "{},{},{}",
219            (min_lon + max_lon) / 2.0,
220            (min_lat + max_lat) / 2.0,
221            options.max_zoom
222        ),
223        "attribution": geolith::attribution::CREDIT,
224        "elevation": {
225            "min": min_elev,
226            "max": max_elev,
227            "source_epsg": source.source_epsg(),
228        },
229        "generator": concat!("geolith ", env!("CARGO_PKG_VERSION")),
230    })
231}
232
233/// Render `source` across the configured zoom range into a `PMTiles` archive.
234///
235/// # Errors
236///
237/// Returns an error when the zoom range is invalid, a source raster cannot
238/// be read, or the archive cannot be written.
239pub fn write_terrain_pmtiles<S: ElevationSource + ?Sized>(
240    source: &S,
241    output: &Path,
242    options: &TerrainTilerOptions,
243    name: &str,
244) -> Result<TerrainTileStats> {
245    if options.min_zoom > options.max_zoom {
246        return Err(GeolithError::PmtilesWrite(format!(
247            "min zoom {} exceeds max zoom {}",
248            options.min_zoom, options.max_zoom
249        )));
250    }
251    if options.max_zoom > 22 {
252        return Err(GeolithError::PmtilesWrite(format!(
253            "max zoom {} exceeds the PMTiles limit of 22",
254            options.max_zoom
255        )));
256    }
257
258    let bounds = archive_bounds(source, options);
259    let mut writer = PmtilesWriter::create(
260        output,
261        Compression::None,
262        TileType::Png,
263        options.min_zoom,
264        options.max_zoom,
265    )?;
266    writer.set_bounds(bounds.0, bounds.1, bounds.2, bounds.3);
267
268    for zoom in options.min_zoom..=options.max_zoom {
269        let (min_x, min_y, max_x, max_y) = tile_range_for_bounds(bounds, zoom);
270        let coords: Vec<TileCoord> = (min_y..=max_y)
271            .flat_map(|y| (min_x..=max_x).map(move |x| TileCoord { z: zoom, x, y }))
272            .collect();
273
274        let mut written = 0_usize;
275        for batch in coords.chunks(RENDER_BATCH) {
276            let rendered = batch
277                .par_iter()
278                .map(|coord| {
279                    render_tile(source, *coord, options)
280                        .map(|png| png.map(|png| (tile_to_pmtiles_id(*coord), png)))
281                })
282                .collect::<Result<Vec<_>>>()?;
283            for (tile_id, png) in rendered.into_iter().flatten() {
284                writer.write_tile(tile_id, &png)?;
285                written += 1;
286            }
287        }
288
289        tracing::info!(
290            zoom,
291            candidates = coords.len(),
292            written,
293            "terrain zoom level rendered"
294        );
295    }
296
297    let stats = TerrainTileStats {
298        tiles_written: writer.tiles_written(),
299        unique_tiles: writer.unique_tiles(),
300    };
301
302    let metadata = terrain_metadata(source, options, name);
303    writer.finalize(serde_json::to_string(&metadata)?.as_bytes())?;
304
305    Ok(stats)
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::terrain::crs::Crs;
312    use crate::terrain::dem::{Dem, GeoTransform};
313    use geolith::terrain::range::{mercator_to_tile_fraction, wgs84_to_mercator};
314
315    /// A 4x4 DEM spanning a small patch near Belvedere Glacier.
316    fn alpine_dem() -> Dem {
317        let values: Vec<f32> = (0..16).map(|i| 2000.0 + i as f32 * 10.0).collect();
318        Dem {
319            width: 4,
320            height: 4,
321            values,
322            transform: GeoTransform {
323                origin_x: 7.90,
324                origin_y: 45.94,
325                pixel_width: 0.005,
326                pixel_height: 0.005,
327            },
328            crs: Crs::Wgs84,
329        }
330    }
331
332    #[test]
333    fn mercator_tile_fraction_roundtrip() {
334        for zoom in [0_u8, 5, 12] {
335            let (x, y) = wgs84_to_mercator(7.9797, 45.9756);
336            let (tx, ty) = mercator_to_tile_fraction(x, y, zoom);
337            let (bx, by) = tile_fraction_to_mercator(tx, ty, zoom);
338            assert!((bx - x).abs() < 1e-6, "zoom {zoom} x: {bx} vs {x}");
339            assert!((by - y).abs() < 1e-6, "zoom {zoom} y: {by} vs {y}");
340        }
341    }
342
343    #[test]
344    fn zoom_zero_has_exactly_one_tile() {
345        let (min_x, min_y, max_x, max_y) = tile_range_for_bounds((-180.0, -85.0, 180.0, 85.0), 0);
346        assert_eq!((min_x, min_y, max_x, max_y), (0, 0, 0, 0));
347    }
348
349    #[test]
350    fn tile_range_is_clamped_to_zoom_extent() {
351        let (min_x, min_y, max_x, max_y) = tile_range_for_bounds((-180.0, -85.0, 180.0, 85.0), 3);
352        assert_eq!(min_x, 0);
353        assert_eq!(min_y, 0);
354        assert_eq!(max_x, 7, "must not exceed 2^3 - 1");
355        assert_eq!(max_y, 7);
356    }
357
358    #[test]
359    fn tile_range_covers_the_dem_footprint() {
360        let dem = alpine_dem();
361        let bounds = dem.wgs84_bounds();
362        let (min_x, min_y, max_x, max_y) = tile_range_for_bounds(bounds, 12);
363        assert!(min_x <= max_x, "{min_x} <= {max_x}");
364        assert!(min_y <= max_y, "{min_y} <= {max_y}");
365    }
366
367    #[test]
368    fn render_tile_returns_none_outside_the_dem() {
369        let dem = alpine_dem();
370        let options = TerrainTilerOptions {
371            tile_size: 32,
372            ..TerrainTilerOptions::default()
373        };
374        let far_away = TileCoord {
375            z: 12,
376            x: 100,
377            y: 100,
378        };
379        assert!(
380            render_tile(&dem, far_away, &options)
381                .expect("render")
382                .is_none(),
383            "tiles with no DEM coverage are skipped entirely"
384        );
385    }
386
387    #[test]
388    fn render_tile_emits_a_valid_png_over_the_dem() {
389        let dem = alpine_dem();
390        let bounds = dem.wgs84_bounds();
391        let options = TerrainTilerOptions {
392            tile_size: 32,
393            ..TerrainTilerOptions::default()
394        };
395        let (min_x, min_y, _, _) = tile_range_for_bounds(bounds, 12);
396        let coord = TileCoord {
397            z: 12,
398            x: min_x,
399            y: min_y,
400        };
401        let png = render_tile(&dem, coord, &options)
402            .expect("render")
403            .expect("tile covers the DEM");
404        assert_eq!(
405            &png[0..8],
406            &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
407            "PNG signature"
408        );
409    }
410
411    #[test]
412    fn rendered_pixels_decode_back_to_source_elevations() {
413        let dem = alpine_dem();
414        let options = TerrainTilerOptions {
415            tile_size: 16,
416            ..TerrainTilerOptions::default()
417        };
418        let bounds = dem.wgs84_bounds();
419        let (min_x, min_y, _, _) = tile_range_for_bounds(bounds, 13);
420        let coord = TileCoord {
421            z: 13,
422            x: min_x,
423            y: min_y,
424        };
425        let png = render_tile(&dem, coord, &options)
426            .expect("render")
427            .expect("tile covers the DEM");
428
429        let decoder = png::Decoder::new(std::io::Cursor::new(&png));
430        let mut reader = decoder.read_info().expect("valid png");
431        let mut buf = vec![0; reader.output_buffer_size().expect("known size")];
432        let info = reader.next_frame(&mut buf).expect("frame");
433        assert_eq!(info.width, 16);
434        assert_eq!(info.height, 16);
435
436        let (min_elev, max_elev) = dem.elevation_range().expect("dem has data");
437        let mut decoded_any = false;
438        for pixel in buf[..info.buffer_size()].as_chunks::<3>().0 {
439            let elevation = options.encoding.decode(*pixel);
440            if elevation.abs() < 0.5 {
441                continue;
442            }
443            decoded_any = true;
444            assert!(
445                elevation >= min_elev - 1.0 && elevation <= max_elev + 1.0,
446                "decoded {elevation} outside DEM range {min_elev}..={max_elev}"
447            );
448        }
449        assert!(decoded_any, "at least one pixel carries elevation");
450    }
451
452    #[test]
453    fn metadata_declares_the_maplibre_contract() {
454        let dem = alpine_dem();
455        let options = TerrainTilerOptions::default();
456        let meta = terrain_metadata(&dem, &options, "belvedere");
457
458        assert_eq!(meta["name"], "belvedere");
459        assert_eq!(meta["format"], "png");
460        assert_eq!(
461            meta["encoding"], "mapbox",
462            "MapLibre raster-dem sources key off this field"
463        );
464        assert_eq!(meta["tileSize"], 512);
465        assert_eq!(meta["elevation"]["source_epsg"], 4326);
466        assert!(
467            meta["bounds"]
468                .as_str()
469                .expect("bounds string")
470                .contains(',')
471        );
472    }
473
474    #[test]
475    fn terrarium_metadata_declares_terrarium_encoding() {
476        let dem = alpine_dem();
477        let options = TerrainTilerOptions {
478            encoding: TerrainEncoding::Terrarium,
479            ..TerrainTilerOptions::default()
480        };
481        let meta = terrain_metadata(&dem, &options, "t");
482        assert_eq!(meta["encoding"], "terrarium");
483    }
484
485    #[test]
486    fn write_terrain_pmtiles_rejects_inverted_zoom_range() {
487        let dem = alpine_dem();
488        let tmp = tempfile::NamedTempFile::new().expect("temp file");
489        let options = TerrainTilerOptions {
490            min_zoom: 10,
491            max_zoom: 5,
492            ..TerrainTilerOptions::default()
493        };
494        let err = write_terrain_pmtiles(&dem, tmp.path(), &options, "t")
495            .expect_err("inverted range is rejected");
496        assert!(matches!(err, GeolithError::PmtilesWrite(_)));
497    }
498
499    #[test]
500    fn write_terrain_pmtiles_rejects_out_of_spec_zoom() {
501        let dem = alpine_dem();
502        let tmp = tempfile::NamedTempFile::new().expect("temp file");
503        let options = TerrainTilerOptions {
504            min_zoom: 0,
505            max_zoom: 23,
506            ..TerrainTilerOptions::default()
507        };
508        assert!(write_terrain_pmtiles(&dem, tmp.path(), &options, "t").is_err());
509    }
510
511    #[test]
512    fn write_terrain_pmtiles_produces_a_readable_archive() {
513        let dem = alpine_dem();
514        let tmp = tempfile::NamedTempFile::new().expect("temp file");
515        let options = TerrainTilerOptions {
516            min_zoom: 10,
517            max_zoom: 12,
518            tile_size: 32,
519            encoding: TerrainEncoding::Mapbox,
520            clip: None,
521        };
522
523        let stats = write_terrain_pmtiles(&dem, tmp.path(), &options, "belvedere")
524            .expect("archive written");
525        assert!(stats.tiles_written > 0, "at least one tile covers the DEM");
526        assert!(stats.unique_tiles > 0);
527
528        let bytes = std::fs::read(tmp.path()).expect("archive readable");
529        assert_eq!(&bytes[0..7], b"PMTiles");
530        assert_eq!(bytes[7], 3, "PMTiles v3");
531        assert_eq!(
532            bytes[99],
533            TileType::Png as u8,
534            "tile_type must be PNG so consumers decode raster-dem tiles"
535        );
536        assert_eq!(
537            bytes[98],
538            Compression::None as u8,
539            "PNG tiles are already compressed and must not be gzipped"
540        );
541    }
542
543    #[test]
544    fn terrain_archive_records_the_dem_footprint_not_world_bounds() {
545        let dem = alpine_dem();
546        let tmp = tempfile::NamedTempFile::new().expect("temp file");
547        let options = TerrainTilerOptions {
548            min_zoom: 10,
549            max_zoom: 12,
550            tile_size: 32,
551            encoding: TerrainEncoding::Mapbox,
552            clip: None,
553        };
554
555        write_terrain_pmtiles(&dem, tmp.path(), &options, "belvedere").expect("archive written");
556        let bytes = std::fs::read(tmp.path()).expect("archive readable");
557
558        let at = |offset: usize| {
559            f64::from(i32::from_le_bytes(
560                bytes[offset..offset + 4].try_into().expect("bbox field"),
561            )) / 10_000_000.0
562        };
563        let (min_lon, min_lat, max_lon, max_lat) = (at(102), at(106), at(110), at(114));
564        // Origin (7.90, 45.94), four 0.005° pixels each way.
565        let expected = (7.90, 45.92, 7.92, 45.94);
566
567        assert!(
568            (min_lon - expected.0).abs() < 1e-5,
569            "header must carry the DEM footprint, got min_lon {min_lon}"
570        );
571        assert!((min_lat - expected.1).abs() < 1e-5);
572        assert!((max_lon - expected.2).abs() < 1e-5);
573        assert!((max_lat - expected.3).abs() < 1e-5);
574        assert!(
575            max_lon - min_lon < 360.0 && max_lat - min_lat < 170.0,
576            "a local DEM must never advertise world bounds"
577        );
578    }
579
580    #[test]
581    fn terrain_archive_records_non_zero_tile_counts() {
582        let dem = alpine_dem();
583        let tmp = tempfile::NamedTempFile::new().expect("temp file");
584        let options = TerrainTilerOptions {
585            min_zoom: 10,
586            max_zoom: 12,
587            tile_size: 32,
588            encoding: TerrainEncoding::Mapbox,
589            clip: None,
590        };
591
592        let stats = write_terrain_pmtiles(&dem, tmp.path(), &options, "belvedere")
593            .expect("archive written");
594        let bytes = std::fs::read(tmp.path()).expect("archive readable");
595        let at = |offset: usize| {
596            u64::from_le_bytes(bytes[offset..offset + 8].try_into().expect("count field"))
597        };
598
599        assert_eq!(
600            at(72),
601            stats.tiles_written,
602            "addressed tiles must match what the tiler wrote"
603        );
604        assert!(at(80) > 0, "tile entries must be reported");
605        assert_eq!(
606            at(88),
607            stats.unique_tiles as u64,
608            "tile contents must match the deduplicated blob count"
609        );
610    }
611
612    /// A flat 1000 m DEM over 7-8°E, 45-46°N at 0.01° pixels, with an
613    /// optional nodata square.
614    fn flat_dem(value: f32, hole: bool) -> Dem {
615        let mut values = vec![value; 100 * 100];
616        if hole {
617            for row in 40..60 {
618                for col in 40..60 {
619                    values[row * 100 + col] = f32::NAN;
620                }
621            }
622        }
623        Dem {
624            width: 100,
625            height: 100,
626            values,
627            transform: GeoTransform {
628                origin_x: 7.0,
629                origin_y: 46.0,
630                pixel_width: 0.01,
631                pixel_height: 0.01,
632            },
633            crs: Crs::Wgs84,
634        }
635    }
636
637    /// Two in-memory DEMs where the first wins and the second fills its gaps.
638    struct Layered(Dem, Dem);
639
640    impl ElevationSource for Layered {
641        fn wgs84_bounds(&self) -> Bounds {
642            self.0.wgs84_bounds()
643        }
644        fn elevation_range(&self) -> Option<(f32, f32)> {
645            self.0.elevation_range()
646        }
647        fn source_epsg(&self) -> u32 {
648            4326
649        }
650        fn patches(
651            &self,
652            _bounds: Bounds,
653            _metres_per_pixel: f64,
654        ) -> Result<Vec<std::borrow::Cow<'_, Dem>>> {
655            Ok(vec![
656                std::borrow::Cow::Borrowed(&self.0),
657                std::borrow::Cow::Borrowed(&self.1),
658            ])
659        }
660    }
661
662    /// Decode a PNG tile into per-pixel elevations.
663    fn decode(png: &[u8], encoding: TerrainEncoding) -> Vec<f32> {
664        let decoder = png::Decoder::new(std::io::Cursor::new(png));
665        let mut reader = decoder.read_info().expect("valid png");
666        let mut buf = vec![0; reader.output_buffer_size().expect("known size")];
667        let info = reader.next_frame(&mut buf).expect("frame");
668        buf[..info.buffer_size()]
669            .as_chunks::<3>()
670            .0
671            .iter()
672            .map(|p| encoding.decode(*p))
673            .collect()
674    }
675
676    /// The nodata square spans 7.40-7.60°E, 45.40-45.60°N. z12 tile
677    /// 2132/1465 covers about 7.38-7.47°E, 45.46-45.52°N, so its west edge
678    /// sits outside the hole and its east edge inside.
679    #[test]
680    fn a_later_source_fills_only_the_first_sources_nodata() {
681        let options = TerrainTilerOptions {
682            tile_size: 64,
683            encoding: TerrainEncoding::Terrarium,
684            ..TerrainTilerOptions::default()
685        };
686        let source = Layered(flat_dem(1000.0, true), flat_dem(500.0, false));
687        let coord = TileCoord {
688            z: 12,
689            x: 2132,
690            y: 1465,
691        };
692        let (west, south, east, north) = tile_wgs84_bounds(coord);
693        assert!(west < 7.40 && east > 7.40, "tile straddles the hole edge");
694        assert!(
695            south > 45.40 && north < 45.60,
696            "tile lies within the hole's rows"
697        );
698        let px = decode(
699            &render_tile(&source, coord, &options)
700                .expect("render")
701                .expect("data"),
702            TerrainEncoding::Terrarium,
703        );
704        let left = px[32 * 64];
705        let right = px[32 * 64 + 63];
706        assert!(
707            (left - 1000.0).abs() < 0.5,
708            "outside the hole the first source wins: {left}"
709        );
710        assert!(
711            (right - 500.0).abs() < 0.5,
712            "inside the hole the fallback fills: {right}"
713        );
714    }
715
716    #[test]
717    fn pixels_outside_the_clip_polygon_are_nodata() {
718        let coord = TileCoord {
719            z: 12,
720            x: 2129,
721            y: 1458,
722        };
723        let (west, south, east, north) = tile_wgs84_bounds(coord);
724        let mid = f64::midpoint(west, east);
725        let clip = ClipMask::from_rings(&[vec![
726            [west - 1.0, south - 1.0],
727            [mid, south - 1.0],
728            [mid, north + 1.0],
729            [west - 1.0, north + 1.0],
730        ]])
731        .expect("clip");
732        let options = TerrainTilerOptions {
733            tile_size: 64,
734            encoding: TerrainEncoding::Terrarium,
735            clip: Some(Arc::new(clip)),
736            ..TerrainTilerOptions::default()
737        };
738        let png = render_tile(&flat_dem(1000.0, false), coord, &options)
739            .expect("render")
740            .expect("left half has data");
741        let px = decode(&png, TerrainEncoding::Terrarium);
742        let nodata = TerrainEncoding::Terrarium.decode(TerrainEncoding::Terrarium.nodata_rgb());
743        for row in [0, 31, 63] {
744            assert!(
745                (px[row * 64 + 5] - 1000.0).abs() < 0.5,
746                "west of the cut, row {row}"
747            );
748            assert_eq!(px[row * 64 + 58], nodata, "east of the cut, row {row}");
749        }
750    }
751
752    #[test]
753    fn a_tile_outside_the_clip_polygon_is_not_written() {
754        let far =
755            ClipMask::from_rings(&[vec![[100.0, 0.0], [101.0, 0.0], [101.0, 1.0]]]).expect("clip");
756        let hollow = ClipMask::from_rings(&[
757            vec![[0.0, 0.0], [20.0, 0.0], [20.0, 60.0], [0.0, 60.0]],
758            vec![[6.0, 44.0], [9.0, 44.0], [9.0, 47.0], [6.0, 47.0]],
759        ])
760        .expect("clip with a hole over the DEM");
761        let coord = TileCoord {
762            z: 12,
763            x: 2129,
764            y: 1458,
765        };
766        for clip in [far, hollow] {
767            let options = TerrainTilerOptions {
768                tile_size: 32,
769                clip: Some(Arc::new(clip)),
770                ..TerrainTilerOptions::default()
771            };
772            assert!(
773                render_tile(&flat_dem(1000.0, false), coord, &options)
774                    .expect("render")
775                    .is_none()
776            );
777        }
778    }
779
780    #[test]
781    fn a_clipped_archive_records_the_overlap_of_dem_and_clip_bounds() {
782        let clip =
783            ClipMask::from_rings(&[vec![[7.5, 45.5], [9.0, 45.5], [9.0, 47.0], [7.5, 47.0]]])
784                .expect("clip");
785        let options = TerrainTilerOptions {
786            min_zoom: 8,
787            max_zoom: 9,
788            tile_size: 32,
789            clip: Some(Arc::new(clip)),
790            ..TerrainTilerOptions::default()
791        };
792        let tmp = tempfile::NamedTempFile::new().expect("temp file");
793        write_terrain_pmtiles(&flat_dem(1000.0, false), tmp.path(), &options, "t")
794            .expect("archive written");
795        let bytes = std::fs::read(tmp.path()).expect("archive readable");
796        let at = |offset: usize| {
797            f64::from(i32::from_le_bytes(
798                bytes[offset..offset + 4].try_into().expect("bbox"),
799            )) / 10_000_000.0
800        };
801        let got = (at(102), at(106), at(110), at(114));
802        for (g, want) in [(got.0, 7.5), (got.1, 45.5), (got.2, 8.0), (got.3, 46.0)] {
803            assert!((g - want).abs() < 1e-6, "bounds {got:?}");
804        }
805        let meta = terrain_metadata(&flat_dem(1000.0, false), &options, "t");
806        assert_eq!(meta["bounds"], "7.5,45.5,8,46");
807    }
808
809    #[test]
810    fn default_options_target_maplibre_defaults() {
811        let options = TerrainTilerOptions::default();
812        assert_eq!(options.tile_size, 512);
813        assert_eq!(options.encoding, TerrainEncoding::Mapbox);
814        assert_eq!(options.min_zoom, 0);
815    }
816}