1use 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#[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Crs {
47 LonLat,
49 WebMercator,
51}
52
53impl Crs {
54 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 pub fn new(style: impl Into<String>) -> Self {
81 Self::stack(vec![style.into()])
82 }
83
84 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 pub fn size(mut self, width: u32, height: u32) -> Self {
109 self.width = width;
110 self.height = height;
111 self
112 }
113
114 pub fn center(mut self, longitude: f64, latitude: f64) -> Self {
116 self.center = (longitude, latitude);
117 self
118 }
119
120 pub fn zoom(mut self, zoom: f64) -> Self {
122 self.zoom = zoom;
123 self
124 }
125
126 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 pub fn pixel_ratio(mut self, pixel_ratio: f64) -> Self {
135 self.pixel_ratio = pixel_ratio;
136 self
137 }
138
139 pub fn layers(mut self, layers: Vec<String>) -> Self {
142 self.layers = Some(layers);
143 self
144 }
145
146 pub fn labels(mut self, labels: crate::Labels) -> Self {
148 self.labels = labels;
149 self
150 }
151
152 pub fn features(mut self, features: Vec<String>) -> Self {
155 self.features = Some(features);
156 self
157 }
158
159 pub fn auth_token(mut self, token: impl Into<String>) -> Self {
161 self.auth_token = Some(token.into());
162 self
163 }
164
165 pub fn tile_timeout_ms(mut self, ms: u32) -> Self {
167 self.tile_timeout_ms = ms;
168 self
169 }
170
171 pub fn max_tiles(mut self, n: u32) -> Self {
173 self.max_tiles = n;
174 self
175 }
176
177 pub fn tile_concurrency(mut self, n: u32) -> Self {
179 self.tile_concurrency = n;
180 self
181 }
182
183 pub fn fail_on_tile_error(mut self, fail: bool) -> Self {
185 self.fail_on_tile_error = fail;
186 self
187 }
188
189 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 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 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 pub fn get_center(&self) -> (f64, f64) {
238 self.center
239 }
240
241 pub fn get_zoom(&self) -> f64 {
243 self.zoom
244 }
245
246 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 pub fn get_attribution(&self) -> Result<String, BasemapError> {
255 crate::attribution(&self.styles, self.auth_token.as_deref())
256 }
257
258 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 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 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 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 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}