Skip to main content

basemapper_core/
renderer.rs

1use crate::error::BasemapError;
2use crate::tile_fetcher::{TileCoord, TileData};
3use image::RgbaImage;
4use std::collections::HashMap;
5
6/// Composite raster tiles onto a single RGBA canvas.
7///
8/// Each tile occupies an exact (tile_px × tile_px) region on the canvas.
9/// The canvas extends from bbox[0..3] at the given zoom; pixel offsets
10/// are computed from the tile index relative to the top-left tile.
11pub fn composite_raster_tiles(
12    tiles: &[(TileCoord, TileData)],
13    bbox: [f64; 4],
14    zoom: u8,
15    width: u32,
16    height: u32,
17    transparent_background: bool,
18    pixel_ratio: f64,
19) -> Result<RgbaImage, BasemapError> {
20    let mut canvas = if transparent_background {
21        RgbaImage::new(width, height)
22    } else {
23        let mut img = RgbaImage::new(width, height);
24        for px in img.pixels_mut() {
25            *px = image::Rgba([255, 255, 255, 255]);
26        }
27        img
28    };
29
30    let half_circ = 20_037_508.342789244_f64;
31    let tile_size_m = (2.0 * half_circ) / 2u64.pow(zoom as u32) as f64;
32    let scale_x = width as f64 / (bbox[2] - bbox[0]);
33    let scale_y = height as f64 / (bbox[3] - bbox[1]);
34    let tile_map: HashMap<(u32, u32), &[u8]> = tiles
35        .iter()
36        .map(|(c, d)| ((c.x, c.y), d.as_slice()))
37        .collect();
38
39    for (&(tx, ty), data) in &tile_map {
40        let img = image::load_from_memory(data)
41            .map_err(|e| BasemapError::TileDecodeError(e.to_string()))?
42            .to_rgba8();
43        // Tiles snap to the CSS pixel grid (MapLibre's alignedProjMatrix
44        // for raster tiles), then scale to device pixels. Each tile spans
45        // from its own snapped edge to its neighbour's, so tiles meet with
46        // no gap or overlap at any pixel ratio.
47        let snap = |v: f64| ((v / pixel_ratio).round() * pixel_ratio).round() as i64;
48        let edge_x = |i: f64| snap((i * tile_size_m - half_circ - bbox[0]) * scale_x);
49        let edge_y = |j: f64| snap((half_circ - j * tile_size_m - bbox[3]) * -scale_y);
50        let (px_x, px_y) = (edge_x(tx as f64), edge_y(ty as f64));
51        let (w, h) = (edge_x(tx as f64 + 1.0) - px_x, edge_y(ty as f64 + 1.0) - px_y);
52        if w <= 0 || h <= 0 {
53            continue;
54        }
55        let resized = image::imageops::resize(&img, w as u32, h as u32, image::imageops::FilterType::Triangle);
56        image::imageops::overlay(&mut canvas, &resized, px_x, px_y);
57    }
58
59    Ok(canvas)
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    fn solid_png() -> TileData {
67        let img = RgbaImage::from_pixel(256, 256, image::Rgba([20, 40, 60, 255]));
68        let mut out = std::io::Cursor::new(Vec::new());
69        img.write_to(&mut out, image::ImageFormat::Png).unwrap();
70        out.into_inner()
71    }
72
73    /// Fractional pixel ratios (from a figure's dpi) once left a white row
74    /// or column between tiles.
75    #[test]
76    fn tiles_meet_without_seams_at_fractional_ratios() {
77        let half = 20_037_508.342789244_f64;
78        let tile_m = 2.0 * half / 4.0; // zoom 2
79        let png = solid_png();
80        let tiles: Vec<(TileCoord, TileData)> = [(1, 1), (2, 1), (1, 2), (2, 2)]
81            .iter()
82            .map(|&(x, y)| (TileCoord { z: 2, x, y }, png.clone()))
83            .collect();
84        // A view straddling the four tiles' shared corner, off-grid.
85        let (cx, cy) = (0.0137 * tile_m, -0.0291 * tile_m);
86        let bbox = [cx - 0.4 * tile_m, cy - 0.3 * tile_m, cx + 0.4 * tile_m, cy + 0.3 * tile_m];
87        for ratio in [1.0, 1.04, 1.146, 1.5, 2.0, 2.37] {
88            let w = (300.0 * ratio) as u32;
89            let h = (225.0 * ratio) as u32;
90            let img = composite_raster_tiles(&tiles, bbox, 2, w, h, false, ratio).unwrap();
91            let white = img.pixels().filter(|p| p.0 == [255, 255, 255, 255]).count();
92            assert_eq!(white, 0, "ratio {ratio}: {white} canvas pixels show between tiles");
93        }
94    }
95}