Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/korp-map

crates/korp-map-quality/src/view.rs

//! **The reference views** — six places, each at a fixed ladder of ground resolutions on
//! a fixed 1920×1080 canvas, and the requests a viewer makes for each one.
//!
//! The view is defined in metres per pixel (`res`), never in zoom. Two request styles
//! turn a view into wire queries:
//!
//! * [`RequestStyle::Lod`] — today's wire (`lod=<int>`), exactly as facett-map 0.3.1's
//!   feed asks (`facet-wrapped/src/mapserver/feed.rs`): `lod = round(zoom)` clamped to
//!   `6..=20`, the viewport grown by 25 % on every side and cut to the region,
//!   `areas` + `lines` (+ `points` from lod 14, capped at 5 000), the per-kind cap by lod
//!   (200 000 to lod 9, 100 000 to lod 12, then 30 000) and `compress=zstd`.
//! * [`RequestStyle::Res`] — the v3 wire (`res=<m/px>`): the same padded box, every kind,
//!   no `lod`, no cap (the server sends what the resolution needs).

use serde::{Deserialize, Serialize};

use crate::geo::{self, Grid};

/// The canvas every reference view is rendered and measured on.
pub const WIDTH: u32 = 1920;
pub const HEIGHT: u32 = 1080;

/// The resolution ladder, metres per pixel: country scale (1600 m/px fits all of Sweden
/// in 1080 px) to street scale (1.6 m/px), a factor √10 per step.
pub const LADDER: [f64; 7] = [1600.0, 500.0, 160.0, 50.0, 16.0, 5.0, 1.6];

/// A reference place: a name and the centre every step of the ladder looks at.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Place {
    pub name: &'static str,
    pub lon: f64,
    pub lat: f64,
    pub what: &'static str,
}

/// The six places of the plan (item 6).
pub const PLACES: [Place; 6] = [
    Place {
        name: "sweden",
        lon: 17.385,
        lat: 62.913,
        what: "the whole country (centre of the region's mercator box)",
    },
    Place {
        name: "stockholm",
        lon: 18.0686,
        lat: 59.3293,
        what: "Stockholm city (Gamla stan)",
    },
    Place {
        name: "goteborg",
        lon: 11.9668,
        lat: 57.7072,
        what: "Göteborg (Gustaf Adolfs torg)",
    },
    Place {
        name: "kiruna",
        lon: 20.2253,
        lat: 67.8558,
        what: "Kiruna town",
    },
    Place {
        name: "archipelago",
        lon: 18.72,
        lat: 59.40,
        what: "the Stockholm archipelago (Värmdö–Möja)",
    },
    Place {
        name: "sarek",
        lon: 17.70,
        lat: 67.28,
        what: "Sarek national park (mountains, glaciers)",
    },
];

/// One reference view.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct View {
    /// `<place>-<res>m`, e.g. `stockholm-16m`; the file stem of every artefact.
    pub name: String,
    pub place: String,
    pub lon: f64,
    pub lat: f64,
    /// Ground metres per pixel at the centre — THE definition of the view.
    pub res: f64,
    pub width: u32,
    pub height: u32,
    /// The slippy zoom equivalent (what today's viewer is opened at).
    pub zoom: f64,
    /// Today's wire level for this view (the viewer's `round(zoom)` clamped to 6..=20).
    pub lod: u32,
    /// The canvas' lon/lat box.
    pub bbox: [f64; 4],
}

impl View {
    #[must_use]
    pub fn new(place: &Place, res: f64) -> Self {
        let zoom = geo::zoom_for_res(res, place.lat);
        let grid = Grid::new(place.lon, place.lat, zoom, WIDTH, HEIGHT);
        Self {
            name: format!("{}-{}m", place.name, fmt_res(res)),
            place: place.name.into(),
            lon: place.lon,
            lat: place.lat,
            res,
            width: WIDTH,
            height: HEIGHT,
            zoom,
            lod: lod_for_zoom(zoom),
            bbox: grid.bbox(),
        }
    }

    /// The pixel grid of this view.
    #[must_use]
    pub fn grid(&self) -> Grid {
        Grid::new(self.lon, self.lat, self.zoom, self.width, self.height)
    }

    /// The wire queries a viewer makes for this view.
    #[must_use]
    pub fn requests(&self, style: RequestStyle, region: &[f64; 4]) -> Vec<Request> {
        let Some(bbox) = intersect(&padded(&self.bbox, PAD), region) else {
            return Vec::new();
        };
        let mut out = Vec::new();
        match style {
            RequestStyle::Lod => {
                let lod = self.lod;
                let mut kinds = vec![Kind::Areas, Kind::Lines];
                if lod >= POINTS_MIN_LOD {
                    kinds.push(Kind::Points);
                }
                for kind in kinds {
                    let max = if kind == Kind::Points {
                        POINTS_MAX
                    } else {
                        cap_for_lod(lod)
                    };
                    out.push(Request {
                        kind,
                        bbox,
                        level: format!("lod={lod}"),
                        max: Some(max),
                    });
                }
            }
            RequestStyle::Res => {
                for kind in [Kind::Areas, Kind::Lines, Kind::Points] {
                    out.push(Request {
                        kind,
                        bbox,
                        level: format!("res={}", fmt_res(self.res)),
                        max: None,
                    });
                }
            }
        }
        out
    }
}

/// Every reference view: each place at every step of the ladder.
#[must_use]
pub fn reference_views() -> Vec<View> {
    PLACES
        .iter()
        .flat_map(|p| LADDER.iter().map(move |&r| View::new(p, r)))
        .collect()
}

/// `1600`, `16`, `1.6` — the resolution as it appears in names and the v3 wire.
#[must_use]
pub fn fmt_res(res: f64) -> String {
    let s = format!("{res:.3}");
    s.trim_end_matches('0').trim_end_matches('.').to_string()
}

/// The viewer's request padding (a quarter of the viewport on every side).
pub const PAD: f64 = 0.25;
/// From this lod the viewer also asks for `points`.
pub const POINTS_MIN_LOD: u32 = 14;
/// The viewer's `points` cap.
pub const POINTS_MAX: u32 = 5000;
/// The coarsest and finest lod the viewer asks.
pub const LOD_MIN: u32 = 6;
pub const LOD_MAX: u32 = 20;

/// The viewer's lod for a camera zoom (`lod_from_world_px`, then the feed's clamp).
#[must_use]
pub fn lod_for_zoom(zoom: f64) -> u32 {
    let l = if zoom.is_finite() && zoom > 0.0 {
        zoom.round() as u32
    } else {
        0
    };
    l.clamp(LOD_MIN, LOD_MAX)
}

/// The viewer's per-kind row cap by lod (`FeedConfig::cap_for_lod`).
#[must_use]
pub const fn cap_for_lod(lod: u32) -> u32 {
    match lod {
        0..=9 => 200_000,
        10..=12 => 100_000,
        _ => 30_000,
    }
}

/// `Bbox::padded`: grown by `frac` of its size on every side, kept on the mercator world.
#[must_use]
pub fn padded(b: &[f64; 4], frac: f64) -> [f64; 4] {
    let (dx, dy) = ((b[2] - b[0]) * frac, (b[3] - b[1]) * frac);
    [
        (b[0] - dx).max(-180.0),
        (b[1] - dy).max(-85.0511),
        (b[2] + dx).min(180.0),
        (b[3] + dy).min(85.0511),
    ]
}

/// Two boxes' overlap, `None` when empty.
#[must_use]
pub fn intersect(a: &[f64; 4], b: &[f64; 4]) -> Option<[f64; 4]> {
    let r = [
        a[0].max(b[0]),
        a[1].max(b[1]),
        a[2].min(b[2]),
        a[3].min(b[3]),
    ];
    (r[0] < r[2] && r[1] < r[3]).then_some(r)
}

/// The wire's three kinds.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    Areas,
    Lines,
    Points,
}

impl Kind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Areas => "areas",
            Self::Lines => "lines",
            Self::Points => "points",
        }
    }
}

/// How a view becomes wire queries.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RequestStyle {
    /// Today: `lod=<int>`.
    Lod,
    /// v3: `res=<m/px>`.
    Res,
}

impl std::str::FromStr for RequestStyle {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, String> {
        match s {
            "lod" => Ok(Self::Lod),
            "res" => Ok(Self::Res),
            _ => Err(format!("request style is `lod` or `res`, not `{s}`")),
        }
    }
}

/// One wire query.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Request {
    pub kind: Kind,
    pub bbox: [f64; 4],
    /// `lod=N` or `res=R`.
    pub level: String,
    pub max: Option<u32>,
}

impl Request {
    /// The query's URL on `server` (no trailing slash) for `region`.
    #[must_use]
    pub fn url(&self, server: &str, region: &str) -> String {
        let b = self.bbox;
        let mut u = format!(
            "{}/v1/map/{}?region={}&bbox={:.6},{:.6},{:.6},{:.6}&{}",
            server.trim_end_matches('/'),
            self.kind.as_str(),
            region,
            b[0],
            b[1],
            b[2],
            b[3],
            self.level
        );
        if let Some(m) = self.max {
            u.push_str(&format!("&max={m}"));
        }
        u.push_str("&compress=zstd");
        u
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const SWEDEN: [f64; 4] = [10.59326171875, 55.13720703125, 24.177734375, 69.06005859375];

    #[test]
    fn the_set_is_six_places_by_seven_steps() {
        let v = reference_views();
        assert_eq!(v.len(), 42);
        assert!(v.iter().any(|v| v.name == "stockholm-1.6m"));
        assert!(v.iter().any(|v| v.name == "sweden-1600m"));
        let mut names: Vec<_> = v.iter().map(|v| v.name.clone()).collect();
        names.sort();
        names.dedup();
        assert_eq!(names.len(), 42, "names are unique");
    }

    #[test]
    fn sweden_fits_the_country_step() {
        let v = View::new(&PLACES[0], 1600.0);
        // The region's latitude span sits inside the canvas.
        assert!(
            v.bbox[1] < SWEDEN[1] && v.bbox[3] > SWEDEN[3],
            "{:?}",
            v.bbox
        );
        assert_eq!(v.lod, 6, "today's viewer clamps the country to lod 6");
    }

    #[test]
    fn todays_requests_mirror_the_viewer_feed() {
        let v = View::new(&PLACES[1], 1.6);
        let r = v.requests(RequestStyle::Lod, &SWEDEN);
        assert_eq!(
            r.iter().map(|q| q.kind).collect::<Vec<_>>(),
            [Kind::Areas, Kind::Lines, Kind::Points]
        );
        assert_eq!(v.lod, 16);
        let u = r[0].url("https://karta.gunnar.rs", "sweden");
        assert!(u.contains("/v1/map/areas?region=sweden&bbox="), "{u}");
        assert!(u.ends_with("&lod=16&max=30000&compress=zstd"), "{u}");
        assert!(r[2].url("x", "sweden").contains("&max=5000"));
        let coarse = View::new(&PLACES[1], 500.0).requests(RequestStyle::Lod, &SWEDEN);
        assert_eq!(coarse.len(), 2, "no points below lod 14");
        assert_eq!(coarse[0].max, Some(200_000));
    }

    #[test]
    fn v3_requests_carry_res_and_no_lod() {
        let v = View::new(&PLACES[3], 16.0);
        let r = v.requests(RequestStyle::Res, &SWEDEN);
        assert_eq!(r.len(), 3);
        let u = r[1].url("http://h:8765", "sweden");
        assert!(
            u.contains("&res=16&compress=zstd") && !u.contains("lod=") && !u.contains("max="),
            "{u}"
        );
        assert_eq!(fmt_res(1.6), "1.6");
        assert_eq!(fmt_res(1600.0), "1600");
    }

    #[test]
    fn the_padded_box_is_cut_to_the_region() {
        let v = View::new(&PLACES[0], 1600.0);
        let r = v.requests(RequestStyle::Lod, &SWEDEN);
        assert_eq!(r[0].bbox, SWEDEN);
    }
}