Skip to main content

basemapper_core/
basemap.rs

1//! `Basemap`: a map view to render, the Rust counterpart of R's
2//! `basemap()` and Python's `basemapper.basemap()` / `Basemap`.
3//!
4//! The same verbs exist in all three languages: R `verb(m, ...)`, Python
5//! `m.verb(...)`, Rust `m.verb(...)`:
6//!
7//! | Task | Rust |
8//! |---|---|
9//! | create | `Basemap::new(style)` + `.size()`, `.center()`, `.zoom()`, `.bounds()`, `.pixel_ratio()`, ... |
10//! | change the view | `set_view(center, zoom)`, `set_bounds(bounds, crs)` |
11//! | read the view | `get_bounds(lonlat)`, `get_center()`, `get_zoom()`, `get_size()` |
12//! | render | `render_array()`, `render_png(path)`, `render_svg(path, options)` |
13
14use crate::bbox::{bbox_from_center, fit_bounds, RenderRequest, RenderResult};
15use crate::{encode_png, render, render_stack, render_svg_stack_with, BasemapError, StyleInput, SvgOptions};
16use std::path::Path;
17
18const EARTH_HALF: f64 = 20_037_508.342_789_244;
19
20/// A map view: one style, or several stacked bottom to top, a size in CSS
21/// pixels, a centre and MapLibre zoom (512 px tiles, fractional allowed),
22/// and a device pixel ratio (images are `pixel_ratio` times larger with the
23/// same view and label layout).
24#[derive(Clone, Debug)]
25pub struct Basemap {
26    styles: Vec<String>,
27    width: u32,
28    height: u32,
29    center: (f64, f64),
30    zoom: f64,
31    pixel_ratio: f64,
32    layers: Option<Vec<String>>,
33    labels: crate::Labels,
34    features: Option<Vec<String>>,
35    auth_token: Option<String>,
36    tile_timeout_ms: u32,
37    max_tiles: u32,
38    tile_concurrency: u32,
39    fail_on_tile_error: bool,
40}
41
42/// Coordinate reference system of bounds given to [`Basemap::set_bounds`]:
43/// the core reads longitude/latitude and Web Mercator (R and Python
44/// reproject other CRSs before calling it).
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Crs {
47    /// EPSG:4326 longitude/latitude degrees.
48    LonLat,
49    /// EPSG:3857 Web Mercator metres.
50    WebMercator,
51}
52
53impl Crs {
54    /// `"EPSG:4326"` / `4326` / `"WGS84"` or `"EPSG:3857"` / `3857`.
55    pub fn parse(s: &str) -> Result<Crs, BasemapError> {
56        match s.trim().to_ascii_uppercase().as_str() {
57            "EPSG:4326" | "4326" | "WGS84" | "CRS84" | "OGC:CRS84" => Ok(Crs::LonLat),
58            "EPSG:3857" | "3857" | "EPSG:900913" => Ok(Crs::WebMercator),
59            other => Err(BasemapError::InvalidInput(format!(
60                "unsupported crs '{other}': the Rust core reads EPSG:4326 or EPSG:3857"
61            ))),
62        }
63    }
64}
65
66fn lonlat_to_3857(lon: f64, lat: f64) -> (f64, f64) {
67    let lat = lat.clamp(-85.051_128_779_806_59, 85.051_128_779_806_59);
68    let r = EARTH_HALF / std::f64::consts::PI;
69    (lon.to_radians() * r, (std::f64::consts::FRAC_PI_4 + lat.to_radians() / 2.0).tan().ln() * r)
70}
71
72fn mercator_to_lonlat(x: f64, y: f64) -> (f64, f64) {
73    let r = EARTH_HALF / std::f64::consts::PI;
74    ((x / r).to_degrees(), (2.0 * (y / r).exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees())
75}
76
77impl Basemap {
78    /// A view of one style (a URL or style JSON, e.g. from
79    /// [`crate::providers`]): 800 x 600 CSS pixels at zoom 0.
80    pub fn new(style: impl Into<String>) -> Self {
81        Self::stack(vec![style.into()])
82    }
83
84    /// A view of several styles drawn bottom to top (e.g. a basemap published
85    /// as separate hillshade, base and label services).
86    pub fn stack(styles: Vec<String>) -> Self {
87        Basemap {
88            styles,
89            width: 800,
90            height: 600,
91            center: (0.0, 0.0),
92            zoom: 0.0,
93            pixel_ratio: 1.0,
94            layers: None,
95            labels: crate::Labels::All,
96            features: None,
97            auth_token: None,
98            tile_timeout_ms: 10_000,
99            max_tiles: 256,
100            tile_concurrency: 16,
101            fail_on_tile_error: false,
102        }
103    }
104
105    // ── Builder (the constructor arguments of R / Python) ───────────────────
106
107    /// View size in CSS pixels.
108    pub fn size(mut self, width: u32, height: u32) -> Self {
109        self.width = width;
110        self.height = height;
111        self
112    }
113
114    /// View centre as (longitude, latitude).
115    pub fn center(mut self, longitude: f64, latitude: f64) -> Self {
116        self.center = (longitude, latitude);
117        self
118    }
119
120    /// MapLibre zoom (0-22, fractional allowed).
121    pub fn zoom(mut self, zoom: f64) -> Self {
122        self.zoom = zoom;
123        self
124    }
125
126    /// Fit `bounds` (`[xmin, ymin, xmax, ymax]` in `crs`) instead of a
127    /// centre and zoom. Apply after [`size`](Self::size).
128    pub fn bounds(mut self, bounds: [f64; 4], crs: Crs) -> Result<Self, BasemapError> {
129        self.set_bounds(bounds, crs)?;
130        Ok(self)
131    }
132
133    /// Device pixels per CSS pixel (MapLibre's `devicePixelRatio`).
134    pub fn pixel_ratio(mut self, pixel_ratio: f64) -> Self {
135        self.pixel_ratio = pixel_ratio;
136        self
137    }
138
139    /// Layer filter applied to every style: plain IDs keep only those
140    /// layers, `-`-prefixed IDs drop them.
141    pub fn layers(mut self, layers: Vec<String>) -> Self {
142        self.layers = Some(layers);
143        self
144    }
145
146    /// Labels to keep in every style: all, none, or only the labels.
147    pub fn labels(mut self, labels: crate::Labels) -> Self {
148        self.labels = labels;
149        self
150    }
151
152    /// Feature filter applied to every style: plain names keep those
153    /// features (`"water"`, `"roads"`, ...), `-`-prefixed names drop them.
154    pub fn features(mut self, features: Vec<String>) -> Self {
155        self.features = Some(features);
156        self
157    }
158
159    /// Access token for the tile service.
160    pub fn auth_token(mut self, token: impl Into<String>) -> Self {
161        self.auth_token = Some(token.into());
162        self
163    }
164
165    /// Per-tile HTTP timeout in milliseconds.
166    pub fn tile_timeout_ms(mut self, ms: u32) -> Self {
167        self.tile_timeout_ms = ms;
168        self
169    }
170
171    /// Maximum tiles fetched per style.
172    pub fn max_tiles(mut self, n: u32) -> Self {
173        self.max_tiles = n;
174        self
175    }
176
177    /// Parallel tile downloads.
178    pub fn tile_concurrency(mut self, n: u32) -> Self {
179        self.tile_concurrency = n;
180        self
181    }
182
183    /// Abort on a failed tile instead of leaving it empty.
184    pub fn fail_on_tile_error(mut self, fail: bool) -> Self {
185        self.fail_on_tile_error = fail;
186        self
187    }
188
189    // ── View ────────────────────────────────────────────────────────────────
190
191    /// Set the centre and/or zoom (`None` keeps the current value).
192    pub fn set_view(&mut self, center: Option<(f64, f64)>, zoom: Option<f64>) -> Result<&mut Self, BasemapError> {
193        if let Some(z) = zoom {
194            if !(0.0..=22.0).contains(&z) {
195                return Err(BasemapError::InvalidInput("zoom must be between 0 and 22".into()));
196            }
197            self.zoom = z;
198        }
199        if let Some(c) = center {
200            self.center = c;
201        }
202        Ok(self)
203    }
204
205    /// Fit the view to `bounds` in `crs`, keeping its size.
206    pub fn set_bounds(&mut self, bounds: [f64; 4], crs: Crs) -> Result<&mut Self, BasemapError> {
207        let b = match crs {
208            Crs::WebMercator => bounds,
209            Crs::LonLat => {
210                let (x0, y0) = lonlat_to_3857(bounds[0], bounds[1]);
211                let (x1, y1) = lonlat_to_3857(bounds[2], bounds[3]);
212                [x0, y0, x1, y1]
213            }
214        };
215        if !(b[2] > b[0] && b[3] > b[1]) {
216            return Err(BasemapError::InvalidBbox("bounds must have xmin < xmax and ymin < ymax".into()));
217        }
218        let (lon, lat, zoom) = fit_bounds(b, self.width, self.height);
219        self.center = (lon, lat);
220        self.zoom = zoom.clamp(0.0, 22.0);
221        Ok(self)
222    }
223
224    /// The view's `[xmin, ymin, xmax, ymax]`: EPSG:3857 metres, or degrees
225    /// with `lonlat`.
226    pub fn get_bounds(&self, lonlat: bool) -> [f64; 4] {
227        let b = bbox_from_center(self.center.0, self.center.1, self.zoom, self.width, self.height);
228        if !lonlat {
229            return b;
230        }
231        let (w, s) = mercator_to_lonlat(b[0], b[1]);
232        let (e, n) = mercator_to_lonlat(b[2], b[3]);
233        [w, s, e, n]
234    }
235
236    /// The view centre as (longitude, latitude).
237    pub fn get_center(&self) -> (f64, f64) {
238        self.center
239    }
240
241    /// The view's MapLibre zoom.
242    pub fn get_zoom(&self) -> f64 {
243        self.zoom
244    }
245
246    /// Size of rendered images in device pixels (`width`, `height` times
247    /// `pixel_ratio`).
248    pub fn get_size(&self) -> (u32, u32) {
249        (crate::vector::render::device_px(self.width, self.pixel_ratio), crate::vector::render::device_px(self.height, self.pixel_ratio))
250    }
251
252    /// The attribution text the view's styles ask maps to show (see
253    /// [`crate::attribution()`]).
254    pub fn get_attribution(&self) -> Result<String, BasemapError> {
255        crate::attribution(&self.styles, self.auth_token.as_deref())
256    }
257
258    // ── Rendering ───────────────────────────────────────────────────────────
259
260    fn requests(&self) -> Vec<RenderRequest> {
261        let bbox = self.get_bounds(false);
262        self.styles
263            .iter()
264            .map(|s| RenderRequest {
265                layers: self.layers.clone(),
266                labels: self.labels,
267                features: self.features.clone(),
268                auth_token: self.auth_token.clone(),
269                tile_timeout_ms: self.tile_timeout_ms,
270                max_tiles: self.max_tiles,
271                tile_concurrency: self.tile_concurrency,
272                fail_on_tile_error: self.fail_on_tile_error,
273                pixel_ratio: self.pixel_ratio,
274                ..RenderRequest::new(bbox, self.width, self.height, StyleInput::detect(s))
275            })
276            .collect()
277    }
278
279    /// Render to straight-alpha RGBA pixels (device pixels).
280    pub fn render_array(&self) -> Result<RenderResult, BasemapError> {
281        let mut requests = self.requests();
282        if requests.len() == 1 {
283            render(requests.remove(0))
284        } else {
285            render_stack(requests)
286        }
287    }
288
289    /// Render a PNG, written to `path` when given; returns its bytes.
290    pub fn render_png(&self, path: Option<&Path>) -> Result<Vec<u8>, BasemapError> {
291        let r = self.render_array()?;
292        let png = encode_png(&r.pixels, r.width, r.height)?;
293        if let Some(p) = path {
294            std::fs::write(p, &png).map_err(|e| BasemapError::RenderError(format!("writing {}: {e}", p.display())))?;
295        }
296        Ok(png)
297    }
298
299    /// Render a vector SVG (`width` x `height` user units; `pixel_ratio`
300    /// does not apply), written to `path` when given; returns the document.
301    pub fn render_svg(&self, path: Option<&Path>, options: &SvgOptions) -> Result<String, BasemapError> {
302        let svg = render_svg_stack_with(self.requests(), options)?;
303        if let Some(p) = path {
304            std::fs::write(p, &svg).map_err(|e| BasemapError::RenderError(format!("writing {}: {e}", p.display())))?;
305        }
306        Ok(svg)
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    #[test]
315    fn view_round_trips() {
316        let mut m = Basemap::new("https://example.com/style.json").size(800, 600).pixel_ratio(2.0);
317        m.set_view(Some((-111.89, 40.76)), Some(12.5)).unwrap();
318        assert_eq!(m.get_center(), (-111.89, 40.76));
319        assert_eq!(m.get_zoom(), 12.5);
320        assert_eq!(m.get_size(), (1600, 1200));
321        let b = m.get_bounds(true);
322        assert!(b[0] < -111.89 && b[2] > -111.89 && b[1] < 40.76 && b[3] > 40.76);
323        // Fitting the view's own bounds gives the same view back.
324        let mut n = Basemap::new("x").size(800, 600);
325        n.set_bounds(m.get_bounds(false), Crs::WebMercator).unwrap();
326        assert!((n.get_zoom() - 12.5).abs() < 1e-9);
327        assert!((n.get_center().0 + 111.89).abs() < 1e-9 && (n.get_center().1 - 40.76).abs() < 1e-9);
328        let mut l = Basemap::new("x").size(800, 600);
329        l.set_bounds(m.get_bounds(true), Crs::LonLat).unwrap();
330        assert!((l.get_zoom() - 12.5).abs() < 1e-6);
331        assert!(m.set_view(None, Some(23.0)).is_err());
332        assert_eq!(Crs::parse("epsg:3857").unwrap(), Crs::WebMercator);
333        assert!(Crs::parse("EPSG:2163").is_err());
334    }
335}