Skip to main content

basemapper_core/
lib.rs

1// Crate documentation: the guide in guide/, with each example's source
2// (examples/guide_*.rs) and its output (guide/output/, written by
3// scripts/build-docs.ps1). Only read when building docs, so builds
4// without the guide folder (the vendored R copy) are unaffected.
5#![cfg_attr(doc, doc = include_str!("../guide/intro.md"))]
6#![cfg_attr(doc, doc = include_str!("../guide/quickstart.md"))]
7//! ```no_run
8#![cfg_attr(doc, doc = include_str!("../examples/guide_quickstart.rs"))]
9//! ```
10//!
11//! Output:
12//!
13//! ```text
14#![cfg_attr(doc, doc = include_str!("../guide/output/quickstart.txt"))]
15//! ```
16#![cfg_attr(doc, doc = include_str!("../guide/quickstart_after.md"))]
17//!
18#![cfg_attr(doc, doc = include_str!("../guide/formats.md"))]
19//! ```no_run
20#![cfg_attr(doc, doc = include_str!("../examples/guide_formats.rs"))]
21//! ```
22//!
23//! Output:
24//!
25//! ```text
26#![cfg_attr(doc, doc = include_str!("../guide/output/formats.txt"))]
27//! ```
28#![cfg_attr(doc, doc = include_str!("../guide/formats_after.md"))]
29//!
30#![cfg_attr(doc, doc = include_str!("../guide/stack.md"))]
31//! ```no_run
32#![cfg_attr(doc, doc = include_str!("../examples/guide_stack.rs"))]
33//! ```
34//!
35//! Output:
36//!
37//! ```text
38#![cfg_attr(doc, doc = include_str!("../guide/output/stack.txt"))]
39//! ```
40#![cfg_attr(doc, doc = include_str!("../guide/stack_after.md"))]
41//!
42#![cfg_attr(doc, doc = include_str!("../guide/layers.md"))]
43//! ```no_run
44#![cfg_attr(doc, doc = include_str!("../examples/guide_layers.rs"))]
45//! ```
46//!
47//! Output:
48//!
49//! ```text
50#![cfg_attr(doc, doc = include_str!("../guide/output/layers.txt"))]
51//! ```
52#![cfg_attr(doc, doc = include_str!("../guide/layers_after.md"))]
53//!
54#![cfg_attr(doc, doc = include_str!("../guide/pmtiles.md"))]
55//! ```no_run
56#![cfg_attr(doc, doc = include_str!("../examples/guide_pmtiles.rs"))]
57//! ```
58//!
59//! Output:
60//!
61//! ```text
62#![cfg_attr(doc, doc = include_str!("../guide/output/pmtiles.txt"))]
63//! ```
64#![cfg_attr(doc, doc = include_str!("../guide/pmtiles_after.md"))]
65//!
66#![cfg_attr(doc, doc = include_str!("../guide/more.md"))]
67
68pub mod attribution;
69pub mod basemap;
70pub mod bbox;
71pub mod cache;
72pub mod error;
73pub mod features;
74pub mod providers;
75pub mod renderer;
76pub mod style;
77pub mod tile_fetcher;
78pub mod tile_style;
79pub mod vector;
80
81pub use basemap::{Basemap, Crs};
82pub use bbox::{bbox_from_center, compute_zoom, fit_bounds, RenderRequest, RenderResult, SpatialBounds};
83pub use error::BasemapError;
84pub use style::{filter_style_layers, StyleInput};
85/// The version of basemapper (the Rust core, and the R and Python packages
86/// built on it, share it; the release tag is `v` and this).
87pub const VERSION: &str = env!("CARGO_PKG_VERSION");
88
89pub use features::Labels;
90pub use tile_fetcher::{TileSource, TileUrls};
91pub use tile_style::{TileKind, TileStyleOptions};
92pub use vector::fonts::{FontEmbed, SvgOptions, SvgText};
93
94use once_cell::sync::Lazy;
95use tokio::runtime::Runtime;
96
97// Thread-local tokio runtime shared across all render calls from binding crates.
98pub(crate) static RUNTIME: Lazy<Runtime> =
99    Lazy::new(|| Runtime::new().expect("failed to create basemapper tokio runtime"));
100
101/// The User-Agent sent with every request, identifying the app as tile
102/// usage policies ask (e.g. OpenStreetMap's).
103pub(crate) const USER_AGENT: &str =
104    concat!("basemapper/", env!("CARGO_PKG_VERSION"), " (+https://github.com/ar-puuk/basemapper)");
105
106/// The HTTP client for styles, tiles, glyphs and sprites.
107pub(crate) fn http_client(timeout: std::time::Duration) -> Result<reqwest::Client, BasemapError> {
108    reqwest::Client::builder()
109        .timeout(timeout)
110        .use_rustls_tls()
111        .user_agent(USER_AGENT)
112        .build()
113        .map_err(|e| BasemapError::RenderError(e.to_string()))
114}
115
116/// Render a basemap tile mosaic to a flat RGBA byte array.
117///
118/// Supports anti-meridian crossing bboxes (xmin > xmax in EPSG:3857).
119/// Such bboxes are split internally into west and east halves, each rendered
120/// at proportional pixel width, then stitched horizontally.
121pub fn render(request: RenderRequest) -> Result<RenderResult, BasemapError> {
122    let mut requests = expand_stacked(vec![request]);
123    if requests.len() > 1 {
124        return render_stack(requests);
125    }
126    let request = requests.remove(0);
127    request.validate()?;
128    RUNTIME.block_on(render_async(request))
129}
130
131/// The requests with each stacked basemap's name (`UGRC.Lite`) replaced by
132/// one request per style of its stack, bottom to top.
133fn expand_stacked(requests: Vec<RenderRequest>) -> Vec<RenderRequest> {
134    let mut out = Vec::with_capacity(requests.len());
135    for request in requests {
136        match &request.style_input {
137            StyleInput::Url(name) if providers::stack_provider(name).is_some() => {
138                for style in providers::expand_stacks(std::slice::from_ref(name)) {
139                    out.push(RenderRequest { style_input: StyleInput::detect(&style), ..request.clone() });
140                }
141            }
142            _ => out.push(request),
143        }
144    }
145    out
146}
147
148/// Render several styles over the same view and composite them bottom to
149/// top (straight-alpha source-over), e.g. a basemap published as separate
150/// services. All requests must share bbox, size and pixel ratio.
151///
152/// `layers`, `labels` and `features` apply to the stack as one basemap: a
153/// style they leave nothing of (the hillshade under `labels = Only`, the
154/// labels over `features = ["terrain"]`) is skipped, and it is an error
155/// only when they leave nothing of the whole stack. A name warns only when
156/// it matches nothing in any style of the stack.
157pub fn render_stack(requests: Vec<RenderRequest>) -> Result<RenderResult, BasemapError> {
158    let mut requests = expand_stacked(requests);
159    let first = requests.first().ok_or_else(|| BasemapError::RenderError("no styles to render".into()))?;
160    let (bbox, w, h, r) = (first.bbox, first.width, first.height, first.pixel_ratio);
161    if requests.iter().any(|q| q.bbox != bbox || q.width != w || q.height != h || q.pixel_ratio != r) {
162        return Err(BasemapError::RenderError("all styles in a stack must share bbox, size and pixel ratio".into()));
163    }
164    if requests.len() == 1 {
165        return render(requests.remove(0));
166    }
167    for q in &requests {
168        q.validate()?;
169    }
170    let mut acc: Option<RenderResult> = None;
171    let mut warnings: Option<Vec<String>> = None;
172    let mut present: Vec<&'static str> = Vec::new();
173    for q in requests {
174        let part = RUNTIME.block_on(render_part(q))?;
175        warnings = Some(match warnings {
176            None => part.warnings,
177            Some(prev) => prev.into_iter().filter(|w| part.warnings.contains(w)).collect(),
178        });
179        for f in part.present {
180            if !present.contains(&f) {
181                present.push(f);
182            }
183        }
184        let Some(top) = part.result else { continue };
185        acc = Some(match acc {
186            None => top,
187            Some(mut below) => {
188                if below.pixels.len() != top.pixels.len() {
189                    return Err(BasemapError::RenderError("stacked renders differ in size".into()));
190                }
191                composite_over(&mut below.pixels, &top.pixels);
192                below.zoom_used = below.zoom_used.max(top.zoom_used);
193                below
194            }
195        });
196    }
197    let mut out = acc.ok_or_else(|| empty_filter_error(&present, "stack"))?;
198    out.warnings = warnings.unwrap_or_default();
199    Ok(out)
200}
201
202/// `dst = src over dst`, both straight-alpha RGBA.
203fn composite_over(dst: &mut [u8], src: &[u8]) {
204    for (o, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) {
205        let (sa, da) = (s[3] as f64 / 255.0, o[3] as f64 / 255.0);
206        let a = sa + da * (1.0 - sa);
207        if a <= 0.0 {
208            o.copy_from_slice(&[0, 0, 0, 0]);
209            continue;
210        }
211        for i in 0..3 {
212            let c = (s[i] as f64 / 255.0 * sa + o[i] as f64 / 255.0 * da * (1.0 - sa)) / a;
213            o[i] = (c * 255.0).round().clamp(0.0, 255.0) as u8;
214        }
215        o[3] = (a * 255.0).round() as u8;
216    }
217}
218
219/// A style for tile data, with overrides: a tile URL template, TileJSON,
220/// PMTiles archive (URL or path) or ArcGIS service, as raster tiles or a
221/// default vector style over its source layers (see the
222/// [`tile_style`](mod@tile_style) module). A style URL or file is returned as is (relative URLs made
223/// absolute). Detecting raster or vector may fetch a tile or the archive
224/// header. Returns the style JSON and the `paint` keys that matched no
225/// generated layer.
226pub fn tile_style(
227    input: &str,
228    options: &TileStyleOptions,
229    auth_token: Option<&str>,
230) -> Result<(String, Vec<String>), BasemapError> {
231    RUNTIME.block_on(async {
232        let client = http_client(std::time::Duration::from_secs(30))?;
233        tile_style::tile_style(input, options, &client, auth_token).await
234    })
235}
236
237/// A style layer, as [`list_layers`] lists it.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct LayerInfo {
240    /// What the `layers` filter matches.
241    pub id: String,
242    /// The layer type (`symbol` layers are the labels).
243    pub kind: String,
244    /// The vector tile layer it draws, if any.
245    pub source_layer: Option<String>,
246    /// What the `features` filter matches (see [`features`]).
247    pub feature: String,
248}
249
250/// Filters to preview with [`list_layers`], as the renderers take them.
251#[derive(Debug, Clone, Default)]
252pub struct LayerFilter {
253    pub layers: Option<Vec<String>>,
254    pub labels: Labels,
255    pub features: Option<Vec<String>>,
256}
257
258/// A style's layers in drawing order; with a filter, the layers a render
259/// with that filter draws (none when it leaves nothing).
260///
261/// `style` is anything [`render`] accepts: a style, or tile data (a tile
262/// URL, TileJSON, PMTiles archive or ArcGIS service) with its built style.
263pub fn list_layers(style: &str, auth_token: Option<&str>, filter: &LayerFilter) -> Result<Vec<LayerInfo>, BasemapError> {
264    if providers::stack_provider(style).is_some() {
265        // A stacked basemap: every style's layers, bottom to top.
266        let mut all = Vec::new();
267        for part in providers::expand_stacks(&[style.to_owned()]) {
268            all.extend(list_layers(&part, auth_token, filter)?);
269        }
270        return Ok(all);
271    }
272    let json = RUNTIME.block_on(async {
273        let client = http_client(std::time::Duration::from_secs(30))?;
274        StyleInput::detect(style).resolve(&client, auth_token).await
275    })?;
276    if let Some(f) = &filter.features {
277        features::validate_features(f)?;
278    }
279    let (selection, _) = apply_filters(&json, filter.layers.as_deref(), filter.labels, filter.features.as_deref())?;
280    let v: serde_json::Value =
281        serde_json::from_str(&selection.style).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
282    Ok(v["layers"]
283        .as_array()
284        .map(|ls| {
285            ls.iter()
286                .map(|l| LayerInfo {
287                    id: l["id"].as_str().unwrap_or("").to_owned(),
288                    kind: l["type"].as_str().unwrap_or("").to_owned(),
289                    source_layer: l["source-layer"].as_str().map(str::to_owned),
290                    feature: features::layer_feature(l).to_owned(),
291                })
292                .collect()
293        })
294        .unwrap_or_default())
295}
296
297/// The attribution text of `styles` (stacked styles, the strings
298/// [`Basemap`] takes): every source the styles draw from contributes its
299/// attribution (from the style, its TileJSON or PMTiles metadata), as plain
300/// text, without duplicates, joined with `" | "`. Empty when none is given.
301pub fn attribution(styles: &[String], auth_token: Option<&str>) -> Result<String, BasemapError> {
302    RUNTIME.block_on(async {
303        let client = http_client(std::time::Duration::from_secs(30))?;
304        attribution::attribution(styles, &client, auth_token).await
305    })
306}
307
308/// Encode straight-alpha RGBA pixels as a PNG file.
309pub fn encode_png(pixels: &[u8], width: u32, height: u32) -> Result<Vec<u8>, BasemapError> {
310    use image::ImageEncoder;
311    let mut buf = Vec::new();
312    image::codecs::png::PngEncoder::new(&mut buf)
313        .write_image(pixels, width, height, image::ExtendedColorType::Rgba8)
314        .map_err(|e| BasemapError::RenderError(format!("PNG encoding failed: {e}")))?;
315    Ok(buf)
316}
317
318// ──────────────────────────────────────────────────────────────────────────────
319// Async rendering pipeline
320// ──────────────────────────────────────────────────────────────────────────────
321
322/// The style with `layers`, `labels` and `features` applied, and warnings
323/// for the names that matched no layer of it.
324fn apply_filters(
325    raw_json: &str,
326    layers: Option<&[String]>,
327    labels: Labels,
328    features: Option<&[String]>,
329) -> Result<(features::Selection, Vec<String>), BasemapError> {
330    let (json, unmatched_layers) = match layers {
331        Some(l) => style::filter_layers(raw_json, l)?,
332        None => (raw_json.to_owned(), Vec::new()),
333    };
334    let selection = features::select(&json, labels, features.unwrap_or(&[]))?;
335    let mut warnings: Vec<String> =
336        unmatched_layers.iter().map(|l| format!("layers: {l:?} matches no layer")).collect();
337    warnings.extend(selection.unmatched.iter().map(|f| format!("features: {f:?} matches no layer")));
338    Ok((selection, warnings))
339}
340
341/// The error for `labels` / `features` leaving nothing to draw, listing the
342/// features there are (`what`: "style" or "stack").
343fn empty_filter_error(present: &[&str], what: &str) -> BasemapError {
344    BasemapError::InvalidLayerFilter(format!(
345        "labels and features leave nothing of this {what} to draw; its features are {}",
346        present.join(", ")
347    ))
348}
349
350/// The style a request draws: its filters applied (an error when they leave
351/// nothing to draw), with warnings for names that matched no layer.
352fn select_style_layers(raw_json: &str, request: &RenderRequest) -> Result<(String, Vec<String>), BasemapError> {
353    let (selection, warnings) =
354        apply_filters(raw_json, request.layers.as_deref(), request.labels, request.features.as_deref())?;
355    // `layers` may leave nothing (as before); `labels` / `features` emptying a
356    // style that had layers is an error.
357    if selection.empty && !selection.present.is_empty() {
358        return Err(empty_filter_error(&selection.present, "style"));
359    }
360    Ok((selection.style, warnings))
361}
362
363/// One style of a stack, rendered with its filters: no result when
364/// `labels` / `features` leave nothing of it, with the warnings and the
365/// features it has either way.
366struct StackPart {
367    result: Option<RenderResult>,
368    warnings: Vec<String>,
369    present: Vec<&'static str>,
370}
371
372async fn render_part(request: RenderRequest) -> Result<StackPart, BasemapError> {
373    let client = http_client(std::time::Duration::from_millis(request.tile_timeout_ms as u64))?;
374    let raw_json = request.style_input.resolve(&client, request.auth_token.as_deref()).await?;
375    style::validate_maplibre_style(&raw_json)?;
376    let (selection, warnings) =
377        apply_filters(&raw_json, request.layers.as_deref(), request.labels, request.features.as_deref())?;
378    if selection.empty && !selection.present.is_empty() {
379        return Ok(StackPart { result: None, warnings, present: selection.present });
380    }
381    let mut result = render_style(request, client, selection.style).await?;
382    result.warnings = warnings.clone();
383    Ok(StackPart { result: Some(result), warnings, present: selection.present })
384}
385
386async fn render_async(request: RenderRequest) -> Result<RenderResult, BasemapError> {
387    let client = http_client(std::time::Duration::from_millis(request.tile_timeout_ms as u64))?;
388
389    // Resolve style once — shared across both halves for anti-meridian renders.
390    let raw_json = request
391        .style_input
392        .resolve(&client, request.auth_token.as_deref())
393        .await?;
394    style::validate_maplibre_style(&raw_json)?;
395
396    let (style_json, warnings) = select_style_layers(&raw_json, &request)?;
397    let mut result = render_style(request, client, style_json).await?;
398    result.warnings = warnings;
399    Ok(result)
400}
401
402/// Render a request with its resolved, filtered style.
403async fn render_style(request: RenderRequest, client: reqwest::Client, style_json: String) -> Result<RenderResult, BasemapError> {
404    // Extract tile source (may fetch TileJSON).
405    let style_val: serde_json::Value = serde_json::from_str(&style_json)
406        .map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
407    // Filtered styles and label-only tiles go over other maps: no background fill.
408    let transparent = request.layers.is_some()
409        || request.labels != Labels::All
410        || request.features.is_some()
411        || style_val.pointer("/metadata/basemapper:transparent") == Some(&serde_json::Value::Bool(true));
412    let style_base_url = match &request.style_input {
413        StyleInput::Url(u) => Some(u.as_str()),
414        StyleInput::InlineJson(_) => None,
415    };
416    let tile_source = extract_tile_source_from_style(
417        &style_val,
418        &client,
419        request.auth_token.as_deref(),
420        style_base_url,
421    )
422    .await?;
423
424    // Compute zoom for the full bbox — handles anti-meridian via compute_zoom.
425    let zoom = {
426        let raw = request.tile_zoom.unwrap_or_else(|| {
427            let mut z = bbox::raster_tile_zoom(request.bbox, request.width, raster_tile_size(&style_val));
428            while z > 0 && bbox::tile_count(request.bbox, z) > request.max_tiles {
429                z -= 1;
430            }
431            z
432        });
433        tile_source.maxzoom().map_or(raw, |mz| raw.min(mz))
434    };
435
436    // Guard: tile_count handles anti-meridian correctly now.
437    let total_tiles = bbox::tile_count(request.bbox, zoom);
438    if total_tiles > request.max_tiles {
439        return Err(BasemapError::MaxTilesExceeded {
440            requested: total_tiles,
441            limit: request.max_tiles,
442        });
443    }
444
445    let [xmin, _ymin, xmax, _ymax] = request.bbox;
446    let half = 20_037_508.342_789_244;
447    let wraps = xmin < xmax && (xmin < -half || xmax > half);
448    let is_vector = matches!(tile_source, TileSource::MapboxVectorTile { .. });
449    if xmin > xmax {
450        render_antimeridian_split(&request, &client, &style_json, &tile_source, transparent, zoom)
451            .await
452    } else if wraps && !is_vector {
453        // Raster sources: express a view past ±180° as an anti-meridian bbox.
454        // (Vector sources draw the wrapped world copy directly.)
455        let mut req = request.clone();
456        if req.bbox[0] < -half {
457            req.bbox[0] += 2.0 * half;
458        }
459        if req.bbox[2] > half {
460            req.bbox[2] -= 2.0 * half;
461        }
462        render_antimeridian_split(&req, &client, &style_json, &tile_source, transparent, zoom).await
463    } else {
464        render_single_bbox(
465            &request,
466            &client,
467            &style_json,
468            &tile_source,
469            transparent,
470            request.bbox,
471            request.width,
472            request.height,
473            zoom,
474        )
475        .await
476    }
477}
478
479/// Render one non-crossing bbox at the given zoom level and pixel dimensions.
480///
481/// Called both for normal bboxes and for each half of an anti-meridian split.
482async fn render_single_bbox(
483    request: &RenderRequest,
484    client: &reqwest::Client,
485    style_json: &str,
486    tile_source: &TileSource,
487    transparent: bool,
488    bbox: [f64; 4],
489    width: u32,
490    height: u32,
491    zoom: u8,
492) -> Result<RenderResult, BasemapError> {
493    let bounds = SpatialBounds {
494        xmin: bbox[0],
495        ymin: bbox[1],
496        xmax: bbox[2],
497        ymax: bbox[3],
498        crs_epsg: 3857,
499    };
500
501    // Vector tiles: in-house CPU renderer (core/src/vector/).
502    if matches!(tile_source, TileSource::MapboxVectorTile { .. }) {
503        // MapLibre convention: style evaluated at the true scale zoom; vector
504        // tiles (512 px) fetched at floor(scale zoom), clamped to the source
505        // maxzoom. An explicit request zoom is on the 256 px raster grid, which
506        // is one level above the equivalent 512 px tile zoom.
507        let (style_val, placed, assets, tz) =
508            fetch_vector_inputs(request, client, style_json, tile_source, bbox, width).await?;
509        let out = vector::render::render(&style_val, &placed, &assets, bbox, width, height, request.pixel_ratio)
510            .map_err(BasemapError::RenderError)?;
511        if !out.skipped_layer_types.is_empty() {
512            log::warn!(
513                "vector renderer does not draw these layer types yet: {}",
514                out.skipped_layer_types.join(", ")
515            );
516        }
517        return Ok(RenderResult {
518            bounds,
519            zoom_used: tz.saturating_add(1),
520            warnings: Vec::new(),
521            width: out.width,
522            height: out.height,
523            pixels: out.pixels,
524        });
525    }
526    // Raster sources: tiles chosen for the CSS size, composited at device size.
527    let (width, height) = (
528        vector::render::device_px(width, request.pixel_ratio),
529        vector::render::device_px(height, request.pixel_ratio),
530    );
531    // PMTiles: fetch via HTTP range requests.
532    if let TileSource::PMTiles { ref url, .. } = tile_source {
533        let coords = tile_fetcher::build_tile_coords(bbox, zoom);
534        let tiles = fetch_pmtiles_tiles(url, &coords, client).await?;
535        let canvas =
536            renderer::composite_raster_tiles(&tiles, bbox, zoom, width, height, transparent, request.pixel_ratio)?;
537        return Ok(RenderResult {
538            bounds,
539            zoom_used: zoom,
540            warnings: Vec::new(),
541            width,
542            height,
543            pixels: canvas.into_raw(),
544        });
545    }
546
547    // Raster XYZ (also WMS, through {bbox-epsg-3857}).
548    let coords = tile_fetcher::build_tile_coords(bbox, zoom);
549    let urls = tile_fetcher::build_tile_urls(tile_source, &coords, request.pixel_ratio);
550    let tiles = tile_fetcher::fetch_all_tiles(
551        client,
552        urls,
553        tile_source,
554        request.tile_timeout_ms,
555        request.tile_concurrency,
556        request.fail_on_tile_error,
557    )
558    .await?;
559    let canvas =
560        renderer::composite_raster_tiles(&tiles, bbox, zoom, width, height, transparent, request.pixel_ratio)?;
561    Ok(RenderResult {
562        bounds,
563        zoom_used: zoom,
564        warnings: Vec::new(),
565        width,
566        height,
567        pixels: canvas.into_raw(),
568    })
569}
570
571/// Split an anti-meridian bbox into west and east halves, render each, then
572/// stitch the pixel arrays horizontally (west first).
573async fn render_antimeridian_split(
574    request: &RenderRequest,
575    client: &reqwest::Client,
576    style_json: &str,
577    tile_source: &TileSource,
578    transparent: bool,
579    zoom: u8,
580) -> Result<RenderResult, BasemapError> {
581    const EARTH_HALF: f64 = 20_037_508.342_789_244;
582    let [xmin, ymin, xmax, ymax] = request.bbox;
583
584    // West half: from xmin → +EARTH_HALF (right edge of the tile grid).
585    // East half: from −EARTH_HALF (left edge) → xmax.
586    let west_bbox = [xmin, ymin, EARTH_HALF, ymax];
587    let east_bbox = [-EARTH_HALF, ymin, xmax, ymax];
588
589    let west_m = EARTH_HALF - xmin;
590    let east_m = xmax + EARTH_HALF;
591    let total_m = west_m + east_m;
592
593    // Proportional pixel widths; guarantee at least 1 px per half.
594    let west_px = ((request.width as f64 * west_m / total_m).round() as u32).max(1);
595    let east_px = request.width.saturating_sub(west_px).max(1);
596
597    let west = render_single_bbox(
598        request, client, style_json, tile_source, transparent,
599        west_bbox, west_px, request.height, zoom,
600    )
601    .await?;
602    let east = render_single_bbox(
603        request, client, style_json, tile_source, transparent,
604        east_bbox, east_px, request.height, zoom,
605    )
606    .await?;
607
608    // Stitch row by row: west pixels then east pixels per scanline.
609    let row_w = west.width as usize * 4;
610    let row_e = east.width as usize * 4;
611    let row_out = row_w + row_e;
612    let rows = west.height.min(east.height) as usize;
613    let mut pixels = vec![0u8; row_out * rows];
614    for row in 0..rows {
615        let out = &mut pixels[row * row_out..][..row_out];
616        out[..row_w].copy_from_slice(&west.pixels[row * row_w..][..row_w]);
617        out[row_w..].copy_from_slice(&east.pixels[row * row_e..][..row_e]);
618    }
619
620    Ok(RenderResult {
621        bounds: SpatialBounds { xmin, ymin, xmax, ymax, crs_epsg: 3857 },
622        zoom_used: zoom,
623        warnings: Vec::new(),
624        width: west.width + east.width,
625        height: rows as u32,
626        pixels,
627    })
628}
629
630// ──────────────────────────────────────────────────────────────────────────────
631// Style and tile source helpers
632// ──────────────────────────────────────────────────────────────────────────────
633
634/// Extract a `TileSource` from the first raster or vector source in the style.
635///
636/// Skips non-tile source types (geojson, image, video).  If the source has a
637/// "url" field (TileJSON reference) instead of an inline "tiles" array, the
638/// TileJSON endpoint is fetched to obtain the tile URL template.
639async fn extract_tile_source_from_style(
640    style: &serde_json::Value,
641    client: &reqwest::Client,
642    auth_token: Option<&str>,
643    style_base_url: Option<&str>,
644) -> Result<TileSource, BasemapError> {
645    let sources = style
646        .get("sources")
647        .and_then(|s| s.as_object())
648        .ok_or_else(|| BasemapError::StyleParseError("missing \"sources\" object".into()))?;
649    static GEOJSON_ONLY: Lazy<serde_json::Value> = Lazy::new(|| serde_json::json!({"type": "vector", "tiles": [""], "maxzoom": 22}));
650
651    // Prefer vector sources over raster; prevents multi-source styles from
652    // routing through the raster pipeline when a vector source is present.
653    let vector_entry = sources.values().find_map(|s| {
654        if s.get("type").and_then(|t| t.as_str()) == Some("vector") {
655            Some(("vector", s))
656        } else {
657            None
658        }
659    });
660    // Sources only the vector path draws (GeoJSON, DEM for hillshade): such
661    // styles render through it even without a vector source.
662    let needs_vector_path = sources.values().any(|s| matches!(s["type"].as_str(), Some("geojson" | "raster-dem")));
663    let (src_type, source) = if let Some(entry) = vector_entry {
664        entry
665    } else if needs_vector_path {
666        ("vector", &*GEOJSON_ONLY)
667    } else {
668        sources
669            .values()
670            .find_map(|s| {
671                let t = s.get("type").and_then(|t| t.as_str()).unwrap_or("raster");
672                if matches!(t, "geojson" | "image" | "video") {
673                    None
674                } else {
675                    Some((t, s))
676                }
677            })
678            .or_else(|| {
679                // GeoJSON-only (or source-less) styles render through the
680                // vector path, which reads every source the layers use.
681                (sources.is_empty() || sources.values().any(|s| s["type"] == "geojson"))
682                    .then(|| ("vector", &*GEOJSON_ONLY))
683            })
684            .ok_or_else(|| {
685                BasemapError::StyleParseError("no raster or vector tile source found".into())
686            })?
687    };
688
689    let resolved = resolve_source(source, src_type, client, auth_token, style_base_url).await?.source;
690    Ok(match resolved {
691        // A vector archive: the vector path, which fetches every source
692        // itself (from the archive), with the archive's max zoom.
693        TileSource::PMTiles { maxzoom, .. } if src_type == "vector" => {
694            TileSource::MapboxVectorTile { urls: TileUrls::default(), api_key: None, maxzoom }
695        }
696        other => other,
697    })
698}
699
700/// A style source resolved to its tile URL template (inline `tiles` or
701/// TileJSON), with the zoom range and tile size MapLibre uses for it.
702struct ResolvedSource {
703    source: TileSource,
704    minzoom: u8,
705    /// Raster tile size in px (MapLibre's default for raster sources: 512).
706    tile_size: f64,
707}
708
709/// The URL a TileJSON's relative `tiles` resolve against. An ArcGIS
710/// service's JSON (`.../VectorTileServer`) lists them relative to the
711/// service itself (`tile/{z}/{y}/{x}.pbf`), as if its URL ended in `/`.
712fn tilejson_base(url: &str) -> String {
713    let (path, query) = url.split_once('?').map_or((url, None), |(p, q)| (p, Some(q)));
714    let lower = path.to_ascii_lowercase();
715    if lower.ends_with("/vectortileserver") || lower.ends_with("/mapserver") {
716        match query {
717            Some(q) => format!("{path}/?{q}"),
718            None => format!("{path}/"),
719        }
720    } else {
721        url.to_owned()
722    }
723}
724
725async fn resolve_source(
726    source: &serde_json::Value,
727    src_type: &str,
728    client: &reqwest::Client,
729    auth_token: Option<&str>,
730    style_base_url: Option<&str>,
731) -> Result<ResolvedSource, BasemapError> {
732    let num = |v: &serde_json::Value, k: &str| v.get(k).and_then(|x| x.as_f64());
733    let tile_list = |v: &serde_json::Value| -> Vec<String> {
734        v.get("tiles")
735            .and_then(|t| t.as_array())
736            .map(|a| a.iter().filter_map(|u| u.as_str().map(str::to_owned)).collect())
737            .unwrap_or_default()
738    };
739    let mut minzoom = num(source, "minzoom");
740    let mut tile_size = num(source, "tileSize");
741    // `scheme` from the source, else from its TileJSON (as MapLibre's
742    // loadTileJson, where explicit source options take precedence).
743    let mut scheme = source.get("scheme").and_then(|v| v.as_str()).map(str::to_owned);
744    // Resolve the tile URL templates and maxzoom.
745    let (tiles, source_maxzoom): (Vec<String>, Option<u8>) = if !tile_list(source).is_empty() {
746        let mz = source
747            .get("maxzoom")
748            .and_then(|v| v.as_u64())
749            .map(|v| v.min(22) as u8);
750        (tile_list(source), mz)
751    } else if let Some(archive) = source.get("url").and_then(|u| u.as_str()).and_then(|u| u.strip_prefix("pmtiles://")) {
752        // The pmtiles protocol's TileJSON: zoom range from the archive
753        // header; the source's own minzoom / maxzoom take precedence.
754        let url = resolve_url(archive, style_base_url);
755        let reader = open_pmtiles(&url, client).await?;
756        let header = reader.get_header();
757        minzoom = minzoom.or(Some(header.min_zoom as f64));
758        let mz = source
759            .get("maxzoom")
760            .and_then(|v| v.as_u64())
761            .map_or(header.max_zoom, |v| v as u8)
762            .min(22);
763        (vec![format!("pmtiles://{url}")], Some(mz))
764    } else if let Some(tilejson_url_raw) = source.get("url").and_then(|u| u.as_str()) {
765        let tilejson_url = resolve_url(tilejson_url_raw, style_base_url);
766        let mut tilejson_req = client.get(&tilejson_url);
767        if let Some(token) = auth_token {
768            tilejson_req = tilejson_req.header("Authorization", format!("Bearer {token}"));
769        }
770        let resp = tilejson_req
771            .send()
772            .await
773            .map_err(|_| BasemapError::StyleFetchFailed {
774                url: tilejson_url.clone(),
775                status: 0,
776            })?;
777        if !resp.status().is_success() {
778            return Err(BasemapError::StyleFetchFailed {
779                url: tilejson_url.clone(),
780                status: resp.status().as_u16(),
781            });
782        }
783        let tilejson: serde_json::Value = resp.json().await.map_err(|_| {
784            BasemapError::StyleParseError("could not parse TileJSON response".into())
785        })?;
786        let base = tilejson_base(&tilejson_url);
787        let tiles: Vec<String> = tile_list(&tilejson).iter().map(|t| resolve_url(t, Some(&base))).collect();
788        if tiles.is_empty() {
789            return Err(BasemapError::StyleParseError("TileJSON missing \"tiles\" array".into()));
790        }
791        let mz = source
792            .get("maxzoom")
793            .or_else(|| tilejson.get("maxzoom"))
794            .and_then(|v| v.as_u64())
795            .map(|v| v.min(22) as u8);
796        minzoom = minzoom.or_else(|| num(&tilejson, "minzoom"));
797        tile_size = tile_size.or_else(|| num(&tilejson, "tileSize"));
798        scheme = scheme.or_else(|| tilejson.get("scheme").and_then(|v| v.as_str()).map(str::to_owned));
799        (tiles, mz)
800    } else {
801        return Err(BasemapError::StyleParseError(
802            "source has neither \"tiles\" array nor \"url\" TileJSON reference".into(),
803        ));
804    };
805
806    let urls = TileUrls { templates: tiles, tms: scheme.as_deref() == Some("tms") };
807    let source = if let Some(archive) = urls.templates.first().and_then(|t| t.strip_prefix("pmtiles://")) {
808        TileSource::PMTiles { url: archive.to_owned(), maxzoom: source_maxzoom }
809    } else if src_type == "vector" {
810        TileSource::MapboxVectorTile {
811            urls,
812            api_key: auth_token.map(str::to_owned),
813            maxzoom: source_maxzoom,
814        }
815    } else {
816        TileSource::XyzRaster {
817            urls,
818            auth_header: auth_token.map(|t| format!("Bearer {t}")),
819            maxzoom: source_maxzoom,
820        }
821    };
822    Ok(ResolvedSource {
823        source,
824        minzoom: minzoom.unwrap_or(0.0).clamp(0.0, 22.0) as u8,
825        tile_size: tile_size.unwrap_or(512.0),
826    })
827}
828
829/// Fetch tiles from a PMTiles archive over HTTP using range requests.
830///
831/// Opens the archive (header + root directory via two range requests), then
832/// fetches each requested tile.  Tiles absent from the archive (sparse
833/// coverage) are silently skipped.
834async fn fetch_pmtiles_tiles(
835    url: &str,
836    coords: &[tile_fetcher::TileCoord],
837    client: &reqwest::Client,
838) -> Result<Vec<(tile_fetcher::TileCoord, tile_fetcher::TileData)>, BasemapError> {
839    let reader = std::sync::Arc::new(open_pmtiles(url, client).await?);
840    // Tiles are fetched concurrently and decompressed (tile_compression).
841    let mut set = tokio::task::JoinSet::new();
842    for (i, &coord) in coords.iter().enumerate() {
843        let pm_coord = pmtiles::TileCoord::new(coord.z, coord.x, coord.y)
844            .map_err(|e| BasemapError::RenderError(format!("PMTiles coord error: {e}")))?;
845        let reader = reader.clone();
846        set.spawn(async move { (i, coord, reader.get_tile_decompressed(pm_coord).await) });
847    }
848    let mut results = Vec::new();
849    while let Some(joined) = set.join_next().await {
850        let Ok((i, coord, res)) = joined else { continue };
851        match res {
852            Ok(Some(bytes)) => results.push((i, coord, bytes.to_vec())),
853            Ok(None) => {}
854            Err(e) => {
855                log::warn!(
856                    "PMTiles tile {}/{}/{} fetch error (skipped): {e}",
857                    coord.z,
858                    coord.x,
859                    coord.y,
860                );
861            }
862        }
863    }
864    results.sort_by_key(|r| r.0);
865    Ok(results.into_iter().map(|(_, c, d)| (c, d)).collect())
866}
867
868/// Open a PMTiles archive over HTTP (header and root directory).
869pub(crate) async fn open_pmtiles(
870    url: &str,
871    client: &reqwest::Client,
872) -> Result<pmtiles::AsyncPmTilesReader<tile_fetcher::ArchiveBackend>, BasemapError> {
873    let backend = tile_fetcher::ArchiveBackend::new(url.to_owned(), client.clone());
874    pmtiles::AsyncPmTilesReader::try_from_source(backend)
875        .await
876        .map_err(|e| BasemapError::RenderError(format!("PMTiles open failed ({url}): {e}")))
877}
878
879/// Resolve a potentially-relative URL against a base URL.
880///
881/// `reqwest::Url::join` percent-encodes `{` and `}` in tile template
882/// placeholders, so we decode them back after joining.
883pub(crate) fn resolve_url(url: &str, base: Option<&str>) -> String {
884    if url.starts_with("http://") || url.starts_with("https://") {
885        return url.to_owned();
886    }
887    if let Some(base_str) = base {
888        if let Ok(base_parsed) = reqwest::Url::parse(base_str) {
889            if let Ok(resolved) = base_parsed.join(url) {
890                return resolved
891                    .to_string()
892                    .replace("%7B", "{")
893                    .replace("%7D", "}")
894                    .replace("%7b", "{")
895                    .replace("%7d", "}");
896            }
897        }
898    }
899    url.to_owned()
900}
901
902/// `tileSize` of the style's first raster source (MapLibre's default: 512).
903fn raster_tile_size(style: &serde_json::Value) -> f64 {
904    style["sources"]
905        .as_object()
906        .and_then(|s| s.values().find(|v| v["type"] == "raster"))
907        .and_then(|v| v["tileSize"].as_f64())
908        .unwrap_or(512.0)
909}
910
911fn style_base_url_of(request: &RenderRequest) -> Option<&str> {
912    match &request.style_input {
913        StyleInput::Url(u) => Some(u.as_str()),
914        StyleInput::InlineJson(_) => None,
915    }
916}
917
918/// Fetch the glyph PBF ranges the visible text labels need, from the style's
919/// `glyphs` URL template. Failures are logged and skipped (labels whose glyphs
920/// are missing are not drawn), as MapLibre does.
921async fn fetch_glyphs(
922    client: &reqwest::Client,
923    style: &serde_json::Value,
924    style_base_url: Option<&str>,
925    tiles: &[(tile_fetcher::TileCoord, tile_fetcher::TileData)],
926    zoom: f64,
927) -> vector::symbol::GlyphMap {
928    let mut map = vector::symbol::GlyphMap::default();
929    let Some(template) = style["glyphs"].as_str() else { return map };
930    let template = resolve_url(template, style_base_url);
931    let decoded: Vec<vector::mvt::Tile> = tiles.iter().filter_map(|(_, b)| vector::mvt::decode(b).ok()).collect();
932    let mut needed: Vec<(String, u32)> =
933        vector::symbol::required_glyph_ranges(style, decoded.iter(), zoom).into_iter().collect();
934    needed.sort();
935    let mut set = tokio::task::JoinSet::new();
936    for (stack, start) in needed {
937        let url = template
938            .replace("{fontstack}", &stack)
939            .replace("{range}", &format!("{}-{}", start, start + 255));
940        let client = client.clone();
941        set.spawn(async move {
942            let resp = client.get(&url).send().await.ok()?;
943            if !resp.status().is_success() {
944                log::warn!("glyphs {url}: HTTP {}", resp.status());
945                return None;
946            }
947            Some((stack, resp.bytes().await.ok()?.to_vec()))
948        });
949    }
950    let mut results = Vec::new();
951    while let Some(r) = set.join_next().await {
952        if let Ok(Some(x)) = r {
953            results.push(x);
954        }
955    }
956    results.sort_by(|a, b| a.0.cmp(&b.0));
957    for (stack, bytes) in results {
958        if let Err(e) = map.add_pbf(&stack, &bytes) {
959            log::warn!("glyphs for {stack}: {e}");
960        }
961    }
962    map
963}
964
965/// Fetch the style's 1x sprite (`<sprite>.json` + `<sprite>.png`). A missing
966/// or broken sprite only disables icons.
967/// The style's sprite; above pixel ratio 1 the `@2x` sheet (as MapLibre
968/// loads it), falling back to 1x. Multi-sprite styles (`[{id, url}, ...]`)
969/// load every sheet; images of sprites other than `default` are named
970/// `id:name`, as MapLibre addresses them.
971async fn fetch_sprite(
972    client: &reqwest::Client,
973    style: &serde_json::Value,
974    style_base_url: Option<&str>,
975    pixel_ratio: f64,
976) -> vector::symbol::Sprite {
977    let entries: Vec<(String, String)> = match &style["sprite"] {
978        serde_json::Value::String(u) => vec![("default".to_owned(), u.clone())],
979        serde_json::Value::Array(list) => list
980            .iter()
981            .filter_map(|e| Some((e["id"].as_str()?.to_owned(), e["url"].as_str()?.to_owned())))
982            .collect(),
983        _ => Vec::new(),
984    };
985    let mut sprite = vector::symbol::Sprite::default();
986    for (id, url) in entries {
987        let base = resolve_url(&url, style_base_url);
988        let get = |url: String| {
989            let client = client.clone();
990            async move {
991                let resp = client.get(&url).send().await.ok()?;
992                if !resp.status().is_success() {
993                    log::warn!("sprite {url}: HTTP {}", resp.status());
994                    return None;
995                }
996                resp.bytes().await.ok().map(|b| b.to_vec())
997            }
998        };
999        let mut fetched = None;
1000        if pixel_ratio > 1.0 {
1001            let (json, png) = tokio::join!(get(format!("{base}@2x.json")), get(format!("{base}@2x.png")));
1002            if let (Some(j), Some(p)) = (json, png) {
1003                fetched = Some((j, p));
1004            }
1005        }
1006        if fetched.is_none() {
1007            let (json, png) = tokio::join!(get(format!("{base}.json")), get(format!("{base}.png")));
1008            if let (Some(j), Some(p)) = (json, png) {
1009                fetched = Some((j, p));
1010            }
1011        }
1012        let Some((j, p)) = fetched else { continue };
1013        match vector::symbol::Sprite::from_json_png(&j, &p) {
1014            Ok(sheet) => {
1015                for (name, img) in sheet.images {
1016                    let key = if id == "default" { name } else { format!("{id}:{name}") };
1017                    sprite.images.insert(key, img);
1018                }
1019            }
1020            Err(e) => log::warn!("{e}"),
1021        }
1022    }
1023    sprite.device_pixel_ratio = pixel_ratio;
1024    sprite
1025}
1026
1027/// Tiles for every tile source the style's layers use, plus glyphs and
1028/// sprite, fetched as MapLibre would: the style is evaluated at the true
1029/// scale zoom; vector sources (512 px tiles) at floor(zoom), raster sources
1030/// at round(zoom + log2(512 / tileSize)), each clamped to its zoom range.
1031/// `primary` is the style's main vector source: its tile zoom is returned.
1032/// An explicit request zoom is on the 256 px raster grid, one level above
1033/// the equivalent 512 px vector tile zoom.
1034#[allow(clippy::type_complexity)]
1035async fn fetch_vector_inputs(
1036    request: &RenderRequest,
1037    client: &reqwest::Client,
1038    style_json: &str,
1039    primary: &TileSource,
1040    bbox: [f64; 4],
1041    width: u32,
1042) -> Result<(serde_json::Value, vector::render::SourceTiles, vector::symbol::SymbolAssets, u8), BasemapError> {
1043    let style_val: serde_json::Value =
1044        serde_json::from_str(style_json).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
1045    // 3D terrain is out of scope for flat basemaps (with a straight-down
1046    // camera MapLibre's terrain only resamples and displaces the map).
1047    if style_val.get("terrain").is_some_and(|t| !t.is_null()) {
1048        log::warn!("style terrain is not supported; the map is drawn flat");
1049    }
1050    let sz = vector::render::scale_zoom(bbox, width);
1051    let vector_tz = |maxzoom: Option<u8>, minzoom: u8| -> Option<u8> {
1052        let tz = match request.tile_zoom {
1053            Some(z) => z.saturating_sub(1),
1054            None => vector::render::tile_zoom(sz, None),
1055        };
1056        let tz = maxzoom.map_or(tz, |m| tz.min(m));
1057        (tz >= minzoom).then_some(tz)
1058    };
1059    let primary_tz = vector_tz(primary.maxzoom(), 0).unwrap_or(0);
1060
1061    // Sources used by layers visible at this zoom, in style order.
1062    let mut used: Vec<String> = Vec::new();
1063    for l in style_val["layers"].as_array().map(|v| v.as_slice()).unwrap_or(&[]) {
1064        if !vector::symbol::layer_visible(l, sz) {
1065            continue;
1066        }
1067        if let Some(src) = l["source"].as_str() {
1068            if !used.iter().any(|u| u == src) {
1069                used.push(src.to_owned());
1070            }
1071        }
1072    }
1073    let mut sources = vector::render::SourceTiles::default();
1074    let mut all_vector: Vec<(tile_fetcher::TileCoord, tile_fetcher::TileData)> = Vec::new();
1075    for id in used {
1076        let src = &style_val["sources"][&id];
1077        let kind = src["type"].as_str().unwrap_or("");
1078        if kind == "geojson" {
1079            if src["cluster"].as_bool() == Some(true) {
1080                log::warn!("source {id}: GeoJSON clustering is not supported; drawing unclustered features");
1081            }
1082            let data = match &src["data"] {
1083                serde_json::Value::String(url) => {
1084                    let url = resolve_url(url, style_base_url_of(request));
1085                    match client.get(&url).send().await {
1086                        Ok(r) if r.status().is_success() => r.json::<serde_json::Value>().await.unwrap_or_default(),
1087                        Ok(r) => {
1088                            log::warn!("source {id}: GeoJSON {url}: HTTP {}", r.status());
1089                            continue;
1090                        }
1091                        Err(e) => {
1092                            log::warn!("source {id}: GeoJSON {url}: {e}");
1093                            continue;
1094                        }
1095                    }
1096                }
1097                other => other.clone(),
1098            };
1099            let opts = vector::geojson::GeoJsonOptions::from_source(src);
1100            let index = vector::geojson::GeoJsonIndex::new(&data, opts);
1101            let tz = match vector_tz(Some(opts.max_zoom), 0) {
1102                Some(z) => z,
1103                None => continue,
1104            };
1105            let tiles: Vec<_> = vector::render::covering_tiles(bbox, tz)
1106                .into_iter()
1107                .map(|(c, wrap)| (c, wrap, index.tile(c.z, c.x, c.y)))
1108                .collect();
1109            all_vector.extend(tiles.iter().map(|(c, _, b)| (*c, b.clone())));
1110            sources.vector.insert(id, tiles);
1111            continue;
1112        }
1113        if kind != "vector" && kind != "raster" && kind != "raster-dem" {
1114            if !kind.is_empty() {
1115                log::warn!("source {id}: type {kind} is not supported yet");
1116            }
1117            continue;
1118        }
1119        let resolved = resolve_source(src, kind, client, request.auth_token.as_deref(), style_base_url_of(request)).await?;
1120        let source = &resolved.source;
1121        let fetch = |coords: Vec<tile_fetcher::TileCoord>| async move {
1122            if let TileSource::PMTiles { url, .. } = source {
1123                return fetch_pmtiles_tiles(url, &coords, client).await;
1124            }
1125            let urls = tile_fetcher::build_tile_urls(source, &coords, request.pixel_ratio);
1126            tile_fetcher::fetch_all_tiles(
1127                client,
1128                urls,
1129                source,
1130                request.tile_timeout_ms,
1131                request.tile_concurrency,
1132                request.fail_on_tile_error,
1133            )
1134            .await
1135        };
1136        if kind == "vector" {
1137            let Some(tz) = vector_tz(resolved.source.maxzoom(), resolved.minzoom) else { continue };
1138            let covering = vector::render::covering_tiles(bbox, tz);
1139            let mut coords: Vec<tile_fetcher::TileCoord> = covering.iter().map(|c| c.0).collect();
1140            coords.sort_by_key(|c| (c.z, c.x, c.y));
1141            coords.dedup();
1142            let tiles = fetch(coords).await?;
1143            let by_coord: std::collections::HashMap<(u8, u32, u32), &tile_fetcher::TileData> =
1144                tiles.iter().map(|(c, d)| ((c.z, c.x, c.y), d)).collect();
1145            let placed: Vec<_> = covering
1146                .iter()
1147                .filter_map(|(c, wrap)| by_coord.get(&(c.z, c.x, c.y)).map(|d| (*c, *wrap, (*d).clone())))
1148                .collect();
1149            all_vector.extend(tiles);
1150            sources.vector.insert(id, placed);
1151        } else {
1152            let z = bbox::raster_tile_zoom(bbox, width, resolved.tile_size);
1153            let z = resolved.source.maxzoom().map_or(z, |m| z.min(m));
1154            if z < resolved.minzoom {
1155                continue;
1156            }
1157            let tiles = fetch(tile_fetcher::build_tile_coords(bbox, z)).await?;
1158            if kind == "raster-dem" {
1159                let unpack = vector::hillshade::unpack_vector(src);
1160                sources.dem.insert(id, vector::hillshade::DemTiles { zoom: z, tiles, unpack });
1161            } else {
1162                sources.raster.insert(id, vector::render::RasterTiles { zoom: z, tiles });
1163            }
1164        }
1165    }
1166    let assets = vector::symbol::SymbolAssets {
1167        glyphs: fetch_glyphs(client, &style_val, style_base_url_of(request), &all_vector, sz).await,
1168        sprite: fetch_sprite(client, &style_val, style_base_url_of(request), request.pixel_ratio).await,
1169    };
1170    Ok((style_val, sources, assets, primary_tz))
1171}
1172
1173// ──────────────────────────────────────────────────────────────────────────────
1174// SVG output
1175// ──────────────────────────────────────────────────────────────────────────────
1176
1177/// Render a vector style as an SVG document (see [`render_svg_stack`]).
1178pub fn render_svg(request: RenderRequest) -> Result<String, BasemapError> {
1179    render_svg_stack(vec![request])
1180}
1181
1182/// [`render_svg`] with options (see [`render_svg_stack_with`]).
1183pub fn render_svg_with(request: RenderRequest, options: &SvgOptions) -> Result<String, BasemapError> {
1184    render_svg_stack_with(vec![request], options)
1185}
1186
1187/// Render several styles over the same view as one SVG document, bottom to
1188/// top, each style in its own group (e.g. a basemap built from separate
1189/// services). Fills, lines and circles are vector paths; labels are glyph
1190/// outlines traced from the style's SDF glyphs; non-SDF icons are embedded
1191/// sprite images. All requests must share bbox, width and height, and use
1192/// vector tile sources.
1193pub fn render_svg_stack(requests: Vec<RenderRequest>) -> Result<String, BasemapError> {
1194    render_svg_stack_with(requests, &SvgOptions::default())
1195}
1196
1197/// [`render_svg_stack`] with options: label text as editable `<text>` with
1198/// embedded fonts (default) or as traced glyph outlines.
1199pub fn render_svg_stack_with(requests: Vec<RenderRequest>, options: &SvgOptions) -> Result<String, BasemapError> {
1200    use std::fmt::Write as _;
1201    let requests = expand_stacked(requests);
1202    let first = requests.first().ok_or_else(|| BasemapError::RenderError("no styles to render".into()))?;
1203    let (bbox, width, height) = (first.bbox, first.width, first.height);
1204    if bbox[0] > bbox[2] {
1205        return Err(BasemapError::InvalidBbox("SVG output does not support anti-meridian (xmin > xmax) bboxes".into()));
1206    }
1207    for request in &requests {
1208        if request.bbox != bbox || request.width != width || request.height != height {
1209            return Err(BasemapError::RenderError("all styles in an SVG stack must share bbox and size".into()));
1210        }
1211        request.validate()?;
1212    }
1213    let timeout = requests.iter().map(|r| r.tile_timeout_ms).max().unwrap_or(10_000);
1214    RUNTIME.block_on(async {
1215        let client = http_client(std::time::Duration::from_millis(timeout.max(15_000) as u64))?;
1216        // Every style's tiles and assets first, so the fonts of the whole
1217        // document are resolved (and embedded) once.
1218        // As render_stack: filters apply to the stack as one basemap.
1219        let stacked = requests.len() > 1;
1220        let mut present: Vec<&'static str> = Vec::new();
1221        let mut inputs = Vec::new();
1222        for request in &requests {
1223            let raw_json = request.style_input.resolve(&client, request.auth_token.as_deref()).await?;
1224            style::validate_maplibre_style(&raw_json)?;
1225            let style_json = if stacked {
1226                let (selection, _) =
1227                    apply_filters(&raw_json, request.layers.as_deref(), request.labels, request.features.as_deref())?;
1228                for f in &selection.present {
1229                    if !present.contains(f) {
1230                        present.push(f);
1231                    }
1232                }
1233                if selection.empty && !selection.present.is_empty() {
1234                    continue;
1235                }
1236                selection.style
1237            } else {
1238                select_style_layers(&raw_json, request)?.0
1239            };
1240            let style_val: serde_json::Value =
1241                serde_json::from_str(&style_json).map_err(|e| BasemapError::StyleParseError(e.to_string()))?;
1242            let tile_source =
1243                extract_tile_source_from_style(&style_val, &client, request.auth_token.as_deref(), style_base_url_of(request)).await?;
1244            // Raster-only styles take the same path: raster layers are
1245            // embedded as images (vector layers are paths and text).
1246            let (style_val, sources, assets, _) =
1247                fetch_vector_inputs(request, &client, &style_json, &tile_source, bbox, width).await?;
1248            inputs.push((style_val, sources, assets));
1249        }
1250        if inputs.is_empty() {
1251            return Err(empty_filter_error(&present, "stack"));
1252        }
1253        let mut fonts = if options.text == SvgText::Editable {
1254            let mut stacks: Vec<String> = inputs.iter().flat_map(|i| i.2.glyphs.stacks.keys().cloned()).collect();
1255            stacks.sort();
1256            stacks.dedup();
1257            Some(vector::fonts::resolve(&client, &stacks, options).await)
1258        } else {
1259            None
1260        };
1261        let mut defs = String::new();
1262        let mut body = String::new();
1263        for (k, (style_val, sources, assets)) in inputs.iter().enumerate() {
1264            let parts = vector::render::render_svg(style_val, sources, assets, bbox, width, height, &format!("s{k}_"), options.text, fonts.as_ref())
1265                .map_err(BasemapError::RenderError)?;
1266            if !parts.skipped_layer_types.is_empty() {
1267                log::warn!("SVG output does not draw these layer types yet: {}", parts.skipped_layer_types.join(", "));
1268            }
1269            defs.push_str(&parts.defs);
1270            let _ = write!(body, r#"<g id="style{k}">{}</g>"#, parts.body);
1271        }
1272        if let Some(f) = fonts.as_mut() {
1273            f.finish(&client, options).await;
1274            let css = f.font_face_css(options.embed_fonts);
1275            if !css.is_empty() {
1276                defs = format!("<style>{css}</style>{defs}");
1277            }
1278        }
1279        Ok(format!(
1280            concat!(
1281                r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" "#,
1282                r#"width="{w}" height="{h}" viewBox="0 0 {w} {h}">"#,
1283                r#"<defs>{defs}</defs>{body}</svg>"#
1284            ),
1285            w = width,
1286            h = height,
1287            defs = defs,
1288            body = body
1289        ))
1290    })
1291}