use std::borrow::Cow;
use serde::Serialize;
use crate::{EARTH_CIRCUMFERENCE, EARTH_CIRCUMFERENCE_DEGREES, MAX_ZOOM, TileRect, wgs84_to_webmercator};
pub const WEB_MERCATOR_QUAD_ID: &str = "WebMercatorQuad";
pub const WORLD_CRS84_QUAD_ID: &str = "WorldCRS84Quad";
pub const SIMPLE_CRS: &str = "simple";
pub const WEB_MERCATOR_QUAD: TileGrid = TileGrid {
id: Cow::Borrowed(WEB_MERCATOR_QUAD_ID),
crs: Cow::Borrowed("EPSG:3857"),
origin: [-EARTH_CIRCUMFERENCE / 2.0, EARTH_CIRCUMFERENCE / 2.0],
extent_at_zoom0: EARTH_CIRCUMFERENCE,
matrix_at_zoom0: [1, 1],
wraps: true,
in_ogc_registry: true,
};
pub const WORLD_CRS84_QUAD: TileGrid = TileGrid {
id: Cow::Borrowed(WORLD_CRS84_QUAD_ID),
crs: Cow::Borrowed("EPSG:4326"),
origin: [-180.0, 90.0],
extent_at_zoom0: 180.0,
matrix_at_zoom0: [2, 1],
wraps: true,
in_ogc_registry: true,
};
pub const WGS1984_QUAD_ID: &str = "WGS1984Quad";
pub const WORLD_MERCATOR_WGS84_QUAD: TileGrid = TileGrid {
id: Cow::Borrowed("WorldMercatorWGS84Quad"),
crs: Cow::Borrowed("EPSG:3395"),
origin: [-EARTH_CIRCUMFERENCE / 2.0, EARTH_CIRCUMFERENCE / 2.0],
extent_at_zoom0: EARTH_CIRCUMFERENCE,
matrix_at_zoom0: [1, 1],
wraps: true,
in_ogc_registry: true,
};
pub const EUROPEAN_ETRS89_LAEA_QUAD: TileGrid = TileGrid {
id: Cow::Borrowed("EuropeanETRS89_LAEAQuad"),
crs: Cow::Borrowed("EPSG:3035"),
origin: [2_000_000.0, 5_500_000.0],
extent_at_zoom0: 4_500_000.0,
matrix_at_zoom0: [1, 1],
wraps: false,
in_ogc_registry: true,
};
pub const NZTM2000_QUAD: TileGrid = TileGrid {
id: Cow::Borrowed("NZTM2000Quad"),
crs: Cow::Borrowed("EPSG:2193"),
origin: [-3_260_586.728_4, 10_438_190.165_2],
extent_at_zoom0: EARTH_CIRCUMFERENCE / 4.0,
matrix_at_zoom0: [1, 1],
wraps: false,
in_ogc_registry: false,
};
pub const UPS_ARCTIC_WGS84_QUAD: TileGrid = TileGrid {
id: Cow::Borrowed("UPSArcticWGS84Quad"),
crs: Cow::Borrowed("EPSG:5041"),
origin: [-14_440_759.350_252, 18_440_759.350_252],
extent_at_zoom0: 32_881_518.694_4,
matrix_at_zoom0: [1, 1],
wraps: false,
in_ogc_registry: true,
};
pub const UPS_ANTARCTIC_WGS84_QUAD: TileGrid = TileGrid {
id: Cow::Borrowed("UPSAntarcticWGS84Quad"),
crs: Cow::Borrowed("EPSG:5042"),
origin: [-14_440_759.350_252, 18_440_759.350_252],
extent_at_zoom0: 32_881_518.694_4,
matrix_at_zoom0: [1, 1],
wraps: false,
in_ogc_registry: true,
};
pub const BUILT_IN_GRIDS: [TileGrid; 7] = [
WEB_MERCATOR_QUAD,
WORLD_CRS84_QUAD,
WORLD_MERCATOR_WGS84_QUAD,
EUROPEAN_ETRS89_LAEA_QUAD,
NZTM2000_QUAD,
UPS_ARCTIC_WGS84_QUAD,
UPS_ANTARCTIC_WGS84_QUAD,
];
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TileGrid {
id: Cow<'static, str>,
crs: Cow<'static, str>,
origin: [f64; 2],
extent_at_zoom0: f64,
#[serde(skip_serializing_if = "is_single_tile")]
matrix_at_zoom0: [u32; 2],
#[serde(skip)]
wraps: bool,
#[serde(skip)]
in_ogc_registry: bool,
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde hands skip_serializing_if a reference"
)]
fn is_single_tile(matrix: &[u32; 2]) -> bool {
*matrix == [1, 1]
}
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum TileGridError {
#[error("tile grid id must not be empty")]
EmptyId,
#[error("tile grid {0}: crs must be an authority-prefixed identifier such as EPSG:3857, got {1:?}")]
InvalidCrs(String, String),
#[error("tile grid {0}: extent_at_zoom0 must be a positive finite number, got {1}")]
InvalidExtent(String, f64),
#[error("tile grid {0}: origin must be finite, got [{1}, {2}]")]
InvalidOrigin(String, f64, f64),
#[error(
"tile grid {0}: matrix_at_zoom0 must be [1, 1], [2, 1] or [1, 2], got [{1}, {2}]. A grid that is two by two at zoom 0 is one by one at zoom 1"
)]
InvalidMatrix(String, u32, u32),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CrsAxes {
pub metres_per_unit: f64,
pub ordered_axes: [&'static str; 2],
pub northing_first: bool,
}
impl TileGrid {
pub fn new(
id: impl Into<String>,
crs: impl Into<String>,
origin: [f64; 2],
extent_at_zoom0: f64,
) -> Result<Self, TileGridError> {
let id = id.into();
if id.is_empty() {
return Err(TileGridError::EmptyId);
}
let crs = crs.into();
if crs != SIMPLE_CRS
&& !crs
.split_once(':')
.is_some_and(|(authority, code)| !authority.is_empty() && !code.is_empty())
{
return Err(TileGridError::InvalidCrs(id, crs));
}
if !(extent_at_zoom0.is_finite() && extent_at_zoom0 > 0.0) {
return Err(TileGridError::InvalidExtent(id, extent_at_zoom0));
}
if !(origin[0].is_finite() && origin[1].is_finite()) {
return Err(TileGridError::InvalidOrigin(id, origin[0], origin[1]));
}
Ok(Self {
id: Cow::Owned(id),
crs: Cow::Owned(crs),
origin,
extent_at_zoom0,
matrix_at_zoom0: [1, 1],
wraps: false,
in_ogc_registry: false,
})
}
pub fn with_matrix_at_zoom0(mut self, matrix: [u32; 2]) -> Result<Self, TileGridError> {
if !matches!(matrix, [1, 1 | 2] | [2, 1]) {
return Err(TileGridError::InvalidMatrix(self.id.into_owned(), matrix[0], matrix[1]));
}
self.matrix_at_zoom0 = matrix;
Ok(self)
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
#[must_use]
pub fn crs(&self) -> &str {
&self.crs
}
#[must_use]
pub fn crs_authority(&self) -> &str {
self.crs.split_once(':').map_or(&*self.crs, |(a, _)| a)
}
#[must_use]
pub fn crs_code(&self) -> &str {
self.crs.split_once(':').map_or("", |(_, c)| c)
}
#[must_use]
pub fn crs_axes(&self) -> Option<CrsAxes> {
let metres = |ordered_axes, northing_first| CrsAxes {
metres_per_unit: 1.0,
ordered_axes,
northing_first,
};
match (self.crs_authority(), self.crs_code()) {
("EPSG", "4326") | ("OGC", "CRS84") => Some(CrsAxes {
metres_per_unit: EARTH_CIRCUMFERENCE / f64::from(EARTH_CIRCUMFERENCE_DEGREES),
ordered_axes: ["Lon", "Lat"],
northing_first: false,
}),
("EPSG", "3857") => Some(metres(["X", "Y"], false)),
("EPSG", "3395" | "5041" | "5042") => Some(metres(["E", "N"], false)),
("EPSG", "3035" | "2193") => Some(metres(["Y", "X"], true)),
_ => None,
}
}
#[must_use]
pub fn crs_bounds(&self, [left, bottom, right, top]: [f64; 4]) -> Option<[f64; 4]> {
match (self.crs_authority(), self.crs_code()) {
("EPSG", "3857") => {
let (left, bottom) = wgs84_to_webmercator(left, bottom);
let (right, top) = wgs84_to_webmercator(right, top);
Some([left, bottom, right, top])
}
("EPSG", "4326") | ("OGC", "CRS84") => Some([left, bottom, right, top]),
_ => None,
}
}
#[must_use]
pub fn origin(&self) -> [f64; 2] {
self.origin
}
#[must_use]
pub fn extent_at_zoom0(&self) -> f64 {
self.extent_at_zoom0
}
#[must_use]
pub fn matrix_at_zoom0(&self) -> [u32; 2] {
self.matrix_at_zoom0
}
#[must_use]
pub fn is_simple(&self) -> bool {
self.crs == SIMPLE_CRS
}
#[must_use]
pub fn tile_side(&self, zoom: u8) -> f64 {
assert!(zoom <= MAX_ZOOM, "zoom {zoom} must be <= {MAX_ZOOM}");
self.extent_at_zoom0 / f64::from(1_u32 << zoom)
}
#[must_use]
pub fn bounds(&self) -> [f64; 4] {
let [x, y] = self.origin;
let [columns, rows] = self.matrix_at_zoom0;
[
x,
f64::from(rows).mul_add(-self.extent_at_zoom0, y),
f64::from(columns).mul_add(self.extent_at_zoom0, x),
y,
]
}
#[must_use]
pub fn is_valid(&self, z: u8, x: u32, y: u32) -> bool {
if z > MAX_ZOOM {
return false;
}
let [columns, rows] = self.matrix_at_zoom0;
u64::from(x) < u64::from(columns) << z && u64::from(y) < u64::from(rows) << z
}
#[must_use]
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
pub fn tile_range(&self, bounds: [f64; 4], zoom: u8) -> TileRect {
let side = self.tile_side(zoom);
let [columns, rows] = self.matrix_at_zoom0;
let (max_col, max_row) = ((columns << zoom) - 1, (rows << zoom) - 1);
let col = |x: f64| (((x - self.origin[0]) / side).floor().max(0.0) as u32).min(max_col);
let row = |y: f64| (((self.origin[1] - y) / side).floor().max(0.0) as u32).min(max_row);
let [min_x, min_y, max_x, max_y] = bounds;
TileRect::new(zoom, col(min_x), row(max_y), col(max_x), row(min_y))
}
#[must_use]
pub fn wraps(&self) -> bool {
self.wraps
}
#[must_use]
pub fn is_web_mercator(&self) -> bool {
self.id == WEB_MERCATOR_QUAD_ID
}
#[must_use]
pub fn is_in_ogc_registry(&self) -> bool {
self.in_ogc_registry
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
#[test]
fn only_the_cylindrical_world_grids_wrap() {
let wrapping: Vec<&str> = BUILT_IN_GRIDS
.iter()
.filter(|grid| grid.wraps())
.map(TileGrid::id)
.collect();
assert_eq!(
wrapping,
["WebMercatorQuad", "WorldCRS84Quad", "WorldMercatorWGS84Quad"]
);
let mercator: Vec<&str> = BUILT_IN_GRIDS
.iter()
.filter(|grid| grid.is_web_mercator())
.map(TileGrid::id)
.collect();
assert_eq!(mercator, ["WebMercatorQuad"]);
let plan = TileGrid::new("floor", SIMPLE_CRS, [0.0, 1000.0], 1000.0).unwrap();
assert!(!plan.wraps());
}
#[rstest]
#[case::mercator_root(&WEB_MERCATOR_QUAD, 0, 0, 0, true)]
#[case::mercator_beyond(&WEB_MERCATOR_QUAD, 0, 1, 0, false)]
#[case::mercator_deep(&WEB_MERCATOR_QUAD, 3, 7, 7, true)]
#[case::mercator_deep_beyond(&WEB_MERCATOR_QUAD, 3, 8, 0, false)]
#[case::crs84_second_column(&WORLD_CRS84_QUAD, 0, 1, 0, true)]
#[case::crs84_third_column(&WORLD_CRS84_QUAD, 0, 2, 0, false)]
#[case::crs84_second_row(&WORLD_CRS84_QUAD, 0, 0, 1, false)]
#[case::crs84_zoom_one(&WORLD_CRS84_QUAD, 1, 3, 1, true)]
#[case::absurd_zoom(&WEB_MERCATOR_QUAD, 200, 0, 0, false)]
fn tiles_beyond_the_matrix_are_not_valid(
#[case] grid: &TileGrid,
#[case] z: u8,
#[case] x: u32,
#[case] y: u32,
#[case] valid: bool,
) {
assert_eq!(grid.is_valid(z, x, y), valid);
}
#[test]
fn a_two_by_one_grid_covers_the_world_in_two_tiles() {
assert_eq!(
WORLD_CRS84_QUAD.bounds().map(f64::to_bits),
[-180.0_f64, -90.0, 180.0, 90.0].map(f64::to_bits)
);
assert_eq!(WORLD_CRS84_QUAD.tile_side(1).to_bits(), 90.0_f64.to_bits());
assert_eq!(
WORLD_CRS84_QUAD.tile_range([-180.0, -90.0, 180.0, 90.0], 1),
TileRect::new(1, 0, 0, 3, 1)
);
assert_eq!(
WORLD_CRS84_QUAD.tile_range([100.0, -400.0, 400.0, 10.0], 0),
TileRect::new(0, 1, 0, 1, 0)
);
}
#[test]
fn a_tile_range_follows_the_mercator_helper() {
let (min_x, min_y, max_x, max_y) = crate::bbox_to_xyz(-10.0, -10.0, 10.0, 10.0, 4);
let bounds = wgs84_to_webmercator(-10.0, -10.0);
let upper = wgs84_to_webmercator(10.0, 10.0);
assert_eq!(
WEB_MERCATOR_QUAD.tile_range([bounds.0, bounds.1, upper.0, upper.1], 4),
TileRect::new(4, min_x, min_y, max_x, max_y)
);
}
#[rstest]
#[case([2, 2])]
#[case([3, 1])]
#[case([0, 1])]
fn only_one_by_one_two_by_one_and_one_by_two_matrices_exist(#[case] matrix: [u32; 2]) {
let err = NZTM2000_QUAD.with_matrix_at_zoom0(matrix).unwrap_err();
assert!(matches!(err, TileGridError::InvalidMatrix(id, c, r) if id == "NZTM2000Quad" && [c, r] == matrix));
}
#[test]
fn a_simple_grid_has_no_authority() {
let plan = TileGrid::new("floor", SIMPLE_CRS, [0.0, 1000.0], 1000.0).unwrap();
assert!(plan.is_simple());
assert_eq!(plan.crs_authority(), SIMPLE_CRS);
assert_eq!(plan.crs_code(), "");
assert!(!WEB_MERCATOR_QUAD.is_simple());
}
#[test]
fn crs_splits_into_authority_and_code() {
let mars = TileGrid::new("mars", "IAU_2015:49900", [-180.0, 90.0], 360.0).unwrap();
assert_eq!(mars.crs_authority(), "IAU_2015");
assert_eq!(mars.crs_code(), "49900");
assert_eq!(WEB_MERCATOR_QUAD.crs_authority(), "EPSG");
assert_eq!(WEB_MERCATOR_QUAD.crs_code(), "3857");
}
#[rstest]
#[case("", "EPSG:4326", [0.0, 0.0], 1.0, TileGridError::EmptyId)]
#[case("g", "4326", [0.0, 0.0], 1.0, TileGridError::InvalidCrs("g".into(), "4326".into()))]
#[case("g", "EPSG:", [0.0, 0.0], 1.0, TileGridError::InvalidCrs("g".into(), "EPSG:".into()))]
#[case("g", "EPSG:4326", [0.0, 0.0], 0.0, TileGridError::InvalidExtent("g".into(), 0.0))]
#[case("g", "EPSG:4326", [0.0, 0.0], -1.0, TileGridError::InvalidExtent("g".into(), -1.0))]
#[case("g", "EPSG:4326", [0.0, 0.0], f64::NAN, TileGridError::InvalidExtent("g".into(), f64::NAN))]
#[case("g", "EPSG:4326", [f64::INFINITY, 0.0], 1.0, TileGridError::InvalidOrigin("g".into(), f64::INFINITY, 0.0))]
fn rejects_malformed_grids(
#[case] id: &str,
#[case] crs: &str,
#[case] origin: [f64; 2],
#[case] extent: f64,
#[case] expected: TileGridError,
) {
let err = TileGrid::new(id, crs, origin, extent).unwrap_err();
assert_eq!(err.to_string(), expected.to_string());
}
#[test]
fn serializes_like_the_maplibre_tile_matrix() {
let json = serde_json::to_value(NZTM2000_QUAD).unwrap();
assert_eq!(
json,
serde_json::json!({
"id": "NZTM2000Quad",
"crs": "EPSG:2193",
"origin": [-3_260_586.728_4, 10_438_190.165_2],
"extentAtZoom0": EARTH_CIRCUMFERENCE / 4.0,
})
);
let json = serde_json::to_value(WORLD_CRS84_QUAD).unwrap();
assert_eq!(json["matrixAtZoom0"], serde_json::json!([2, 1]));
}
}