use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::Path;
use anyhow::Context as _;
use flate2::write::GzEncoder;
use geo::{BoundingRect as _, Coord, Polygon};
use geolith::geometry::mercator::TileCoord;
use geolith::output::hilbert::tile_to_pmtiles_id;
use geolith::output::writer::{Compression, PmtilesWriter, TileType};
use geolith::tile::feature::TILE_EXTENT;
use geolith::tile::mvt::{encode_polygon, proto};
use i_overlay::core::fill_rule::FillRule;
use i_overlay::core::overlay::{IntOverlayOptions, Overlay};
use i_overlay::core::overlay_rule::OverlayRule;
use i_overlay::core::solver::Solver;
use i_overlay::i_float::int::point::IntPoint;
use prost::Message as _;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::json;
use crate::areas::{Area, GAP_LABEL, GapPiece};
use crate::topology::{Coverage, FeatureRings, MAX_ZOOM};
const BOUNDARIES_CONFIG: &str = include_str!("../data/datasets/boundaries.json");
pub fn tiles_revision() -> anyhow::Result<u64> {
let config: serde_json::Value =
serde_json::from_str(BOUNDARIES_CONFIG).context("bad boundaries.json")?;
config
.get("tiles_revision")
.and_then(serde_json::Value::as_u64)
.filter(|r| *r >= 1)
.context("boundaries.json has no positive tiles_revision")
}
const LAYER: &str = "areas";
const AREA_KEYS: [&str; 2] = ["id", "kind"];
const GAPS_LAYER: &str = "gaps";
const GAP_KEYS: [&str; 4] = ["id", "region_code", "region_name", "label"];
const DISTRICT: &str = "district";
const GAP: &str = "gap";
struct Item<'a> {
values: Vec<Option<&'a str>>,
polygons: Vec<&'a Polygon<f64>>,
}
fn item_id<'a>(item: &Item<'a>) -> &'a str {
item.values.first().copied().flatten().unwrap_or_default()
}
fn items<'a>(areas: &'a [Area], gaps: &'a [GapPiece]) -> Vec<Item<'a>> {
let mut items: Vec<Item<'a>> = Vec::with_capacity(areas.len() + gaps.len());
items.extend(areas.iter().map(|a| Item {
values: vec![Some(a.id.as_str()), Some(DISTRICT)],
polygons: a.shape.0.iter().collect(),
}));
items.extend(gaps.iter().map(|g| Item {
values: vec![Some(g.id.as_str()), Some(GAP)],
polygons: g.shape.0.iter().collect(),
}));
items.sort_by(|a, b| item_id(a).cmp(item_id(b)));
items
}
fn gap_items(gaps: &[GapPiece]) -> Vec<Item<'_>> {
let mut items: Vec<Item<'_>> = gaps
.iter()
.map(|g| Item {
values: vec![
Some(g.id.as_str()),
g.region_code.as_deref(),
g.region_name.as_deref(),
Some(GAP_LABEL),
],
polygons: g.shape.0.iter().collect(),
})
.collect();
items.sort_by(|a, b| item_id(a).cmp(item_id(b)));
items
}
const BUFFER: i32 = 64;
const EXTENT: i64 = TILE_EXTENT as i64;
const CLIP_OPTIONS: IntOverlayOptions = IntOverlayOptions {
preserve_input_collinear: true,
output_direction: i_overlay::core::overlay::ContourDirection::CounterClockwise,
preserve_output_collinear: true,
min_output_area: 0,
ogc: true,
};
fn signed_area_2x(ring: &[(i32, i32)]) -> i64 {
let n = ring.len();
(0..n)
.map(|i| {
let (x1, y1) = ring[i];
let (x2, y2) = ring[(i + 1) % n];
(i64::from(x2) - i64::from(x1)) * (i64::from(y2) + i64::from(y1))
})
.sum()
}
fn wind(mut ring: Vec<(i32, i32)>, exterior: bool) -> Vec<(i32, i32)> {
let area = signed_area_2x(&ring);
if (exterior && area > 0) || (!exterior && area < 0) {
ring.reverse();
}
ring
}
type TileRings = BTreeMap<(u32, u32), Vec<Vec<(i32, i32)>>>;
fn tile_rings(feature: &FeatureRings, z: u8) -> TileRings {
let last = (1_i64 << z) - 1;
let (b, e) = (BUFFER, TILE_EXTENT as i32);
let rect = vec![
IntPoint::new(-b, -b),
IntPoint::new(e + b, -b),
IntPoint::new(e + b, e + b),
IntPoint::new(-b, e + b),
];
let mut out = TileRings::new();
for polygon in feature {
let Some(exterior) = polygon.first() else {
continue;
};
let (mut x0, mut y0, mut x1, mut y1) = (i64::MAX, i64::MAX, i64::MIN, i64::MIN);
for &(x, y) in exterior {
(x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x), y1.max(y));
}
let tiles = |lo: i64, hi: i64| {
let from = (lo - i64::from(b)).div_euclid(EXTENT).max(0);
let to = (hi + i64::from(b)).div_euclid(EXTENT).min(last);
from..=to
};
for tx in tiles(x0, x1) {
for ty in tiles(y0, y1) {
let (ox, oy) = (tx * EXTENT, ty * EXTENT);
let contours: Vec<Vec<IntPoint>> = polygon
.iter()
.map(|ring| {
ring.iter()
.map(|&(x, y)| IntPoint::new((x - ox) as i32, (y - oy) as i32))
.collect()
})
.collect();
let shapes = Overlay::with_contours_custom(
&contours,
std::slice::from_ref(&rect),
CLIP_OPTIONS,
Solver::default(),
)
.overlay(OverlayRule::Intersect, FillRule::Positive);
if shapes.is_empty() {
continue;
}
let group = out.entry((tx as u32, ty as u32)).or_default();
for shape in shapes {
for (k, contour) in shape.into_iter().enumerate() {
let ring: Vec<(i32, i32)> = contour.iter().map(|p| (p.x, p.y)).collect();
group.push(wind(ring, k == 0));
}
}
}
}
}
out
}
struct LayerBuilder {
name: &'static str,
keys: &'static [&'static str],
values: Vec<proto::tile::Value>,
value_index: BTreeMap<String, u32>,
features: Vec<proto::tile::Feature>,
}
impl LayerBuilder {
const fn new(name: &'static str, keys: &'static [&'static str]) -> Self {
Self {
name,
keys,
values: Vec::new(),
value_index: BTreeMap::new(),
features: Vec::new(),
}
}
fn value(&mut self, text: &str) -> u32 {
if let Some(&i) = self.value_index.get(text) {
return i;
}
let i = self.values.len() as u32;
self.values.push(proto::tile::Value {
string_value: Some(text.to_string()),
..Default::default()
});
self.value_index.insert(text.to_string(), i);
i
}
fn push(&mut self, mvt_id: u64, item: &Item<'_>, geometry: Vec<u32>) {
let mut tags = Vec::with_capacity(2 * item.values.len());
for (key, value) in (0_u32..).zip(&item.values) {
if let Some(text) = value {
let value = self.value(text);
tags.extend([key, value]);
}
}
self.features.push(proto::tile::Feature {
id: Some(mvt_id),
tags,
r#type: Some(proto::tile::GeomType::Polygon as i32),
geometry,
});
}
fn into_layer(self) -> proto::tile::Layer {
proto::tile::Layer {
version: 2,
name: self.name.to_string(),
features: self.features,
keys: self.keys.iter().map(|k| (*k).to_string()).collect(),
values: self.values,
extent: Some(TILE_EXTENT),
}
}
}
type LayerFeatures<'a, 'r> = (
&'static str,
&'static [&'static str],
Vec<(&'r Item<'a>, &'r TileRings)>,
);
type TileLayers = [Option<LayerBuilder>; 2];
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TileStats {
pub tiles_written: u64,
pub unique_tiles: u64,
pub bytes: u64,
}
#[must_use]
pub fn render_area_tiles(
areas: &[Area],
gaps: &[GapPiece],
max_zoom: u8,
) -> Vec<(TileCoord, Vec<u8>)> {
let max_zoom = max_zoom.min(MAX_ZOOM);
let area_items = items(areas, gaps);
let gap_list = gap_items(gaps);
let polygons: Vec<Vec<&Polygon<f64>>> = area_items.iter().map(|i| i.polygons.clone()).collect();
let coverage = Coverage::build(&polygons);
let s = coverage.stats;
tracing::info!(
shared_before = s.shared_before / s.total_before.max(1.0),
shared_after = s.shared_after / s.total_after.max(1.0),
merged = s.merged,
inserted = s.inserted,
arcs = s.arcs,
nodes = s.nodes,
"area borders built"
);
let position: BTreeMap<&str, usize> = area_items
.iter()
.enumerate()
.map(|(i, item)| (item_id(item), i))
.collect();
let gap_of: Vec<Option<usize>> = gap_list
.iter()
.map(|g| position.get(item_id(g)).copied())
.collect();
let mut tiles: Vec<(TileCoord, Vec<u8>)> = Vec::new();
for z in 0..=max_zoom {
let (rings, stats) = coverage.rings_at_zoom(z);
tracing::info!(
z,
vertices = stats.vertices,
repaired = stats.repaired,
crossing = stats.crossing,
dropped_rings = stats.dropped_rings,
"area borders simplified"
);
let per_feature: Vec<TileRings> = rings.par_iter().map(|f| tile_rings(f, z)).collect();
let empty = TileRings::new();
let mut by_tile: BTreeMap<(u32, u32), TileLayers> = BTreeMap::new();
let layers: [LayerFeatures<'_, '_>; 2] = [
(
LAYER,
&AREA_KEYS,
area_items.iter().zip(&per_feature).collect(),
),
(
GAPS_LAYER,
&GAP_KEYS,
gap_list
.iter()
.zip(&gap_of)
.map(|(g, at)| (g, at.and_then(|i| per_feature.get(i)).unwrap_or(&empty)))
.collect(),
),
];
for (slot, (name, keys, features)) in layers.iter().enumerate() {
for (mvt_id, (item, per_tile)) in (0_u64..).zip(features) {
for (xy, rings) in per_tile.iter() {
let geometry = encode_polygon(rings);
if geometry.is_empty() {
continue;
}
let tile = by_tile.entry(*xy).or_default();
if let Some(layer) = tile.get_mut(slot) {
layer
.get_or_insert_with(|| LayerBuilder::new(name, keys))
.push(mvt_id, item, geometry);
}
}
}
}
tiles.reserve(by_tile.len());
tiles.extend(by_tile.into_iter().map(|((x, y), layers)| {
let tile = proto::Tile {
layers: layers
.into_iter()
.flatten()
.map(LayerBuilder::into_layer)
.collect(),
};
(TileCoord::new(z, x, y), tile.encode_to_vec())
}));
}
tiles
}
pub fn write_areas_pmtiles(
path: &Path,
areas: &[Area],
gaps: &[GapPiece],
max_zoom: u8,
attribution: &str,
bounds: Option<[f64; 4]>,
) -> anyhow::Result<TileStats> {
if max_zoom > MAX_ZOOM {
anyhow::bail!("areas tiles reach zoom {MAX_ZOOM} at most, not {max_zoom}");
}
let revision = tiles_revision()?;
let mut tiles: Vec<(u64, Vec<u8>)> = render_area_tiles(areas, gaps, max_zoom)
.into_iter()
.map(|(coord, mvt)| (tile_to_pmtiles_id(coord), mvt))
.collect();
tiles.sort_unstable_by_key(|(id, _)| *id);
let mut writer = PmtilesWriter::create(path, Compression::Gzip, TileType::Mvt, 0, max_zoom)
.with_context(|| format!("failed to create {}", path.display()))?;
let header_bounds = match bounds {
Some([min_lon, min_lat, max_lon, max_lat]) => Some((min_lon, min_lat, max_lon, max_lat)),
None => {
let rects = areas
.iter()
.filter_map(|a| a.shape.bounding_rect())
.chain(gaps.iter().filter_map(|g| g.shape.bounding_rect()));
rects
.reduce(|a, b| {
geo::Rect::new(
Coord {
x: a.min().x.min(b.min().x),
y: a.min().y.min(b.min().y),
},
Coord {
x: a.max().x.max(b.max().x),
y: a.max().y.max(b.max().y),
},
)
})
.map(|r| (r.min().x, r.min().y, r.max().x, r.max().y))
}
};
if let Some((min_lon, min_lat, max_lon, max_lat)) = header_bounds {
writer.set_bounds(min_lon, min_lat, max_lon, max_lat);
}
for (id, mvt) in &tiles {
let mut gz = GzEncoder::new(
Vec::with_capacity(mvt.len()),
flate2::Compression::default(),
);
gz.write_all(mvt).context("failed to gzip a tile")?;
let compressed = gz.finish().context("failed to gzip a tile")?;
writer
.write_tile(*id, &compressed)
.with_context(|| format!("failed to write {}", path.display()))?;
}
let tiles_written = writer.tiles_written();
let unique_tiles = writer.unique_tiles() as u64;
let metadata = json!({
"vector_layers": [{
"id": LAYER,
"fields": { "id": "String", "kind": "String" },
"minzoom": 0,
"maxzoom": max_zoom,
}, {
"id": GAPS_LAYER,
"fields": {
"id": "String",
"region_code": "String",
"region_name": "String",
"label": "String",
},
"minzoom": 0,
"maxzoom": max_zoom,
}],
"attribution": attribution,
"tiles_revision": revision,
"generator": concat!("geolith ", env!("CARGO_PKG_VERSION")),
});
writer
.finalize(serde_json::to_string(&metadata)?.as_bytes())
.with_context(|| format!("failed to write {}", path.display()))?;
let bytes = std::fs::metadata(path)
.with_context(|| format!("failed to stat {}", path.display()))?
.len();
Ok(TileStats {
tiles_written,
unique_tiles,
bytes,
})
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::io::Read as _;
use super::*;
use geo::{LineString, MultiPolygon, Polygon};
use geolith::geometry::mercator::{wgs84_to_world, world_to_tile};
use std::collections::BTreeMap;
fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> LineString<f64> {
LineString::from(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)])
}
fn area(id: &str, polygon: Polygon<f64>) -> Area {
Area {
code: None,
id: id.to_string(),
name: id.to_string(),
country: "IN".to_string(),
level: "county".to_string(),
parent_id: None,
parent_name: None,
region_code: None,
shape: MultiPolygon(vec![polygon]),
}
}
fn decode(bytes: &[u8]) -> proto::Tile {
proto::Tile::decode(bytes).expect("tile decodes")
}
fn props(
layer: &proto::tile::Layer,
feature: &proto::tile::Feature,
) -> HashMap<String, String> {
feature
.tags
.chunks(2)
.map(|kv| {
let key = layer.keys[kv[0] as usize].clone();
let value = layer.values[kv[1] as usize]
.string_value
.clone()
.expect("string value");
(key, value)
})
.collect()
}
fn features(
tiles: &[(TileCoord, Vec<u8>)],
) -> Vec<(TileCoord, proto::tile::Feature, HashMap<String, String>)> {
tiles
.iter()
.flat_map(|(coord, bytes)| {
let tile = decode(bytes);
tile.layers
.iter()
.flat_map(|layer| {
layer
.features
.iter()
.map(|f| (*coord, f.clone(), props(layer, f)))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()
})
.collect()
}
fn close_paths(geometry: &[u32]) -> usize {
let (mut i, mut closes) = (0, 0);
while i < geometry.len() {
let (id, count) = (geometry[i] & 7, (geometry[i] >> 3) as usize);
i += 1;
match id {
1 | 2 => i += 2 * count,
7 => closes += count,
_ => panic!("bad command {id}"),
}
}
closes
}
#[test]
fn tiles_carry_one_areas_layer() {
let areas = [area(
"div-x",
Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![]),
)];
let tiles = render_area_tiles(&areas, &[], 4);
assert!(!tiles.is_empty(), "no tiles rendered");
for (coord, bytes) in &tiles {
let tile = decode(bytes);
assert_eq!(tile.layers.len(), 1, "layers of {coord:?}");
let layer = tile.layers.first().expect("one layer");
assert_eq!(layer.name, "areas");
assert_eq!(layer.extent, Some(4096));
}
}
#[test]
fn the_tile_under_a_centroid_holds_that_area() {
let areas = [
area("div-x", Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![])),
area("div-y", Polygon::new(rect(10.0, 10.0, 11.0, 11.0), vec![])),
];
let tiles = render_area_tiles(&areas, &[], 5);
let (wx, wy) = wgs84_to_world(72.5, 25.5);
let under = world_to_tile(wx, wy, 5);
let ids: Vec<String> = features(&tiles)
.into_iter()
.filter(|(coord, _, _)| *coord == under)
.filter_map(|(_, _, p)| p.get("id").cloned())
.collect();
assert!(
ids.iter().any(|id| id == "div-x"),
"ids under {under:?}: {ids:?}"
);
assert!(
!ids.iter().any(|id| id == "div-y"),
"div-y is far away: {ids:?}"
);
}
#[test]
fn holes_survive_clipping() {
let holed = Polygon::new(
rect(60.0, 10.0, 90.0, 40.0),
vec![rect(70.0, 20.0, 80.0, 30.0)],
);
let tiles = render_area_tiles(&[area("div-h", holed)], &[], 3);
let (wx, wy) = wgs84_to_world(75.0, 25.0);
let under = world_to_tile(wx, wy, 3);
let (_, feature, _) = features(&tiles)
.into_iter()
.find(|(coord, _, p)| *coord == under && p.get("id").is_some_and(|id| id == "div-h"))
.expect("div-h in the tile under the hole");
assert_eq!(close_paths(&feature.geometry), 2, "exterior and hole");
}
#[test]
fn gaps_are_tagged() {
let areas = [area(
"div-x",
Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![]),
)];
let gap = GapPiece {
id: "gap-1".to_string(),
area_sq_deg: 1.0,
centroid: (74.5, 25.5),
region_id: None,
region_name: None,
region_code: None,
shape: MultiPolygon(vec![Polygon::new(rect(74.0, 25.0, 75.0, 26.0), vec![])]),
};
let tiles = render_area_tiles(&areas, &[gap], 4);
let all = features(&tiles);
let (_, _, p) = all
.iter()
.find(|(_, _, p)| p.get("kind").is_some_and(|k| k == "gap"))
.expect("a gap feature");
assert_eq!(p.get("id").map(String::as_str), Some("gap-1"));
let (_, _, d) = all
.iter()
.find(|(_, _, p)| p.get("id").is_some_and(|id| id == "div-x"))
.expect("the district feature");
assert_eq!(d.get("kind").map(String::as_str), Some("district"));
}
#[test]
fn the_gaps_layer_carries_region_and_label() {
let gap = GapPiece {
id: "gap-1".to_string(),
area_sq_deg: 1.0,
centroid: (74.5, 25.5),
region_id: Some("div-jk".to_string()),
region_name: Some("JK name".to_string()),
region_code: Some("IN-JK".to_string()),
shape: MultiPolygon(vec![Polygon::new(rect(74.0, 25.0, 75.0, 26.0), vec![])]),
};
let tiles = render_area_tiles(&[], &[gap], 4);
let (wx, wy) = wgs84_to_world(74.5, 25.5);
let under = world_to_tile(wx, wy, 4);
let (_, bytes) = tiles
.iter()
.find(|(coord, _)| *coord == under)
.expect("the tile under the gap");
let tile = decode(bytes);
let layer = tile
.layers
.iter()
.find(|l| l.name == "gaps")
.expect("a gaps layer");
assert_eq!(layer.extent, Some(4096));
let feature = layer.features.first().expect("a gap feature");
let p = props(layer, feature);
assert_eq!(p.get("id").map(String::as_str), Some("gap-1"));
assert_eq!(p.get("region_code").map(String::as_str), Some("IN-JK"));
assert_eq!(p.get("region_name").map(String::as_str), Some("JK name"));
assert_eq!(
p.get("label").map(String::as_str),
Some("District data not available")
);
}
#[test]
fn a_gap_without_a_region_has_no_region_tags() {
let gap = GapPiece {
id: "gap-1".to_string(),
area_sq_deg: 1.0,
centroid: (74.5, 25.5),
region_id: None,
region_name: None,
region_code: None,
shape: MultiPolygon(vec![Polygon::new(rect(74.0, 25.0, 75.0, 26.0), vec![])]),
};
let tiles = render_area_tiles(&[], &[gap], 2);
let tagged: Vec<HashMap<String, String>> = tiles
.iter()
.flat_map(|(_, bytes)| {
let tile = decode(bytes);
tile.layers
.iter()
.filter(|l| l.name == "gaps")
.flat_map(|l| l.features.iter().map(|f| props(l, f)).collect::<Vec<_>>())
.collect::<Vec<_>>()
})
.collect();
assert!(!tagged.is_empty(), "gap features rendered");
for p in &tagged {
assert!(!p.contains_key("region_code"), "{p:?}");
assert!(!p.contains_key("region_name"), "{p:?}");
assert!(p.get("label").is_some_and(|l| !l.is_empty()), "{p:?}");
}
}
#[test]
fn the_archive_records_attribution() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("areas.pmtiles");
let areas = [area(
"div-x",
Polygon::new(rect(72.0, 25.0, 73.0, 26.0), vec![]),
)];
let attribution = "Boundaries: test attribution ©";
let stats = write_areas_pmtiles(&path, &areas, &[], 3, attribution, None).expect("write");
let bytes = std::fs::read(&path).expect("archive bytes");
assert_eq!(&bytes[0..7], b"PMTiles");
assert_eq!(bytes[7], 3, "PMTiles v3");
assert_eq!(stats.bytes, bytes.len() as u64);
let field =
|at: usize| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("8 bytes")) as usize;
let (offset, length) = (field(24), field(32));
let mut metadata = String::new();
flate2::read::GzDecoder::new(&bytes[offset..offset + length])
.read_to_string(&mut metadata)
.expect("gunzip metadata");
let json: serde_json::Value = serde_json::from_str(&metadata).expect("metadata json");
assert_eq!(json["attribution"], attribution);
let layer = json["vector_layers"]
.as_array()
.expect("vector_layers")
.iter()
.find(|l| l["id"] == "areas")
.expect("areas layer");
assert_eq!(layer["maxzoom"], 3);
assert_eq!(layer["fields"]["kind"], "String");
let gaps = json["vector_layers"]
.as_array()
.expect("vector_layers")
.iter()
.find(|l| l["id"] == "gaps")
.expect("gaps layer");
assert_eq!(gaps["fields"]["region_code"], "String");
assert_eq!(gaps["fields"]["label"], "String");
}
fn border(a: (f64, f64), b: (f64, f64), seed: f64, straight: bool) -> Vec<(f64, f64)> {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let len = dx.hypot(dy);
let (nx, ny) = (-dy / len, dx / len);
(0..=200)
.map(|k| {
let t = f64::from(k) / 200.0;
let w = if straight || k == 0 || k == 200 {
0.0
} else {
(std::f64::consts::PI * t).sin()
* (0.004 * (37.0 * t + seed).sin() + 0.002 * (91.0 * t + 2.0 * seed).sin())
};
(a.0 + t * dx + w * nx, a.1 + t * dy + w * ny)
})
.collect()
}
fn block() -> (Vec<Area>, Vec<GapPiece>) {
let node = |i: usize, j: usize| (77.0 + 0.1 * i as f64, 28.0 + 0.1 * j as f64);
let h = |i: usize, j: usize| {
border(
node(i, j),
node(i + 1, j),
(i * 7 + j) as f64,
j == 0 || j == 3,
)
};
let v = |i: usize, j: usize| {
border(
node(i, j),
node(i, j + 1),
(i * 11 + j + 50) as f64,
i == 0 || i == 3,
)
};
let enclave: Vec<(f64, f64)> = (0..=60)
.map(|k| {
let a = f64::from(k) / 60.0 * std::f64::consts::TAU;
let r = 0.02 + 0.004 * (5.0 * a).sin();
(77.15 + r * a.cos(), 28.15 + r * a.sin())
})
.collect();
let mut areas = Vec::new();
let mut gaps = Vec::new();
for i in 0..3 {
for j in 0..3 {
let mut ring: Vec<(f64, f64)> = h(i, j);
ring.extend(v(i + 1, j).into_iter().skip(1));
ring.extend(h(i, j + 1).into_iter().rev().skip(1));
ring.extend(v(i, j).into_iter().rev().skip(1));
let holes = if (i, j) == (1, 1) {
vec![LineString::from(
enclave.iter().rev().copied().collect::<Vec<_>>(),
)]
} else {
vec![]
};
let polygon = Polygon::new(LineString::from(ring), holes);
if (i, j) == (2, 2) {
gaps.push(GapPiece {
id: "gap-1".to_string(),
area_sq_deg: 0.01,
centroid: (77.25, 28.25),
region_id: None,
region_name: None,
region_code: None,
shape: MultiPolygon(vec![polygon]),
});
} else {
areas.push(area(&format!("div-{i}{j}"), polygon));
}
}
}
areas.push(area(
"div-enclave",
Polygon::new(LineString::from(enclave), vec![]),
));
let island: Vec<(f64, f64)> = (0..=80)
.map(|k| {
let a = f64::from(k) / 80.0 * std::f64::consts::TAU;
let r = 0.05 + 0.01 * (7.0 * a).sin();
(78.0 + r * a.cos(), 27.5 + r * a.sin())
})
.collect();
areas.push(area(
"div-island",
Polygon::new(
LineString::from(island),
vec![rect(77.99, 27.49, 78.01, 27.51)],
),
));
(areas, gaps)
}
type Decoded = (String, Vec<Vec<(i64, i64)>>);
type EdgeOwners<'a> = BTreeMap<((i64, i64), (i64, i64)), Vec<&'a str>>;
fn layer_rings(bytes: &[u8], name: &str) -> Vec<Decoded> {
let tile = decode(bytes);
let Some(layer) = tile.layers.iter().find(|l| l.name == name) else {
return Vec::new();
};
layer
.features
.iter()
.map(|f| {
let id = props(layer, f).remove("id").expect("id");
let mut rings: Vec<Vec<(i64, i64)>> = Vec::new();
let (mut x, mut y, mut i) = (0_i64, 0_i64, 0);
let zz = |v: u32| i64::from((v >> 1) as i32 ^ -((v & 1) as i32));
let g = &f.geometry;
while i < g.len() {
let (cmd, count) = (g[i] & 7, (g[i] >> 3) as usize);
i += 1;
if cmd == 7 {
continue;
}
for _ in 0..count {
x += zz(g[i]);
y += zz(g[i + 1]);
i += 2;
if cmd == 1 {
rings.push(Vec::new());
}
if let Some(r) = rings.last_mut() {
r.push((x, y));
}
}
}
(id, rings)
})
.collect()
}
fn self_intersects(ring: &[(i64, i64)]) -> bool {
use crate::topology::{Contact, contact};
let n = ring.len();
for i in 0..n {
for j in i + 1..n {
let c = contact(ring[i], ring[(i + 1) % n], ring[j], ring[(j + 1) % n]);
let adjacent = j == i + 1 || (i == 0 && j == n - 1);
match c {
Contact::None => {}
Contact::SharedEnd if adjacent => {}
_ => return true,
}
}
}
false
}
fn overlap_and_gap(features: &[Decoded], region: (i64, i64, i64, i64)) -> (usize, usize) {
let (x0, y0, x1, y1) = (
region.0.max(0),
region.1.max(0),
region.2.min(4096),
region.3.min(4096),
);
if x0 >= x1 || y0 >= y1 {
return (0, 0);
}
let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);
let mut count = vec![0_u8; w * h];
for (_, rings) in features {
for row in 0..h {
let yc = (y0 + row as i64) as f64 + 0.5;
let mut xs: Vec<f64> = Vec::new();
for ring in rings {
for k in 0..ring.len() {
let (mut a, mut b) = (ring[k], ring[(k + 1) % ring.len()]);
if a.1 == b.1 {
continue;
}
if a.1 > b.1 {
std::mem::swap(&mut a, &mut b);
}
let (ay, by) = (a.1 as f64, b.1 as f64);
if ay <= yc && yc < by {
xs.push(a.0 as f64 + (yc - ay) * (b.0 - a.0) as f64 / (by - ay));
}
}
}
xs.sort_by(f64::total_cmp);
for pair in xs.chunks(2) {
if let [l, r] = pair {
let from = ((l - 0.5).ceil() as i64).max(x0);
let to = ((r - 0.5).ceil() as i64).min(x1);
for x in from..to {
let i = row * w + (x - x0) as usize;
count[i] = count[i].saturating_add(1);
}
}
}
}
}
let overlap = count.iter().filter(|&&c| c >= 2).count();
let mut outside = vec![false; w * h];
let mut stack: Vec<usize> = (0..w)
.flat_map(|x| [x, (h - 1) * w + x])
.chain((0..h).flat_map(|y| [y * w, y * w + w - 1]))
.collect();
while let Some(i) = stack.pop() {
if outside[i] || count[i] != 0 {
continue;
}
outside[i] = true;
let (x, y) = (i % w, i / w);
if x > 0 {
stack.push(i - 1);
}
if x + 1 < w {
stack.push(i + 1);
}
if y > 0 {
stack.push(i - w);
}
if y + 1 < h {
stack.push(i + w);
}
}
let gap = (0..w * h).filter(|&i| count[i] == 0 && !outside[i]).count();
(overlap, gap)
}
#[test]
fn every_ring_of_a_coverage_is_simple_at_every_zoom() {
let (areas, gaps) = block();
for (coord, bytes) in render_area_tiles(&areas, &gaps, 10) {
for name in ["areas", "gaps"] {
for (id, rings) in layer_rings(&bytes, name) {
for ring in &rings {
assert!(
ring.len() >= 3,
"{coord:?} {id}: ring of {} points",
ring.len()
);
assert!(
!self_intersects(ring),
"{coord:?} {id}: ring crosses itself"
);
}
}
}
}
}
#[test]
fn neighbours_share_every_inner_border_at_every_zoom() {
let (areas, gaps) = block();
let mut total_shared = 0.0;
for (coord, bytes) in render_area_tiles(&areas, &gaps, 10)
.into_iter()
.filter(|(c, _)| c.z >= 4)
{
let features = layer_rings(&bytes, "areas");
let mut owners: EdgeOwners<'_> = BTreeMap::new();
for (id, rings) in &features {
for ring in rings {
for k in 0..ring.len() {
let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
owners
.entry(if a < b { (a, b) } else { (b, a) })
.or_default()
.push(id);
}
}
}
let n = f64::from(1_u32 << coord.z);
let to_tile = |lon: f64, lat: f64| {
let (wx, wy) = wgs84_to_world(lon, lat);
(
((wx * n - f64::from(coord.x)) * 4096.0).round() as i64,
((wy * n - f64::from(coord.y)) * 4096.0).round() as i64,
)
};
let (left, top) = to_tile(77.0, 28.3);
let (right, bottom) = to_tile(77.3, 28.0);
let inside = |p: (i64, i64)| (0..=4096).contains(&p.0) && (0..=4096).contains(&p.1);
let outer = |a: (i64, i64), b: (i64, i64)| {
(a.0 == b.0 && (a.0 == left || a.0 == right))
|| (a.1 == b.1 && (a.1 == top || a.1 == bottom))
};
let (overlap, gap) = overlap_and_gap(&features, (left, top, right, bottom));
assert_eq!((overlap, gap), (0, 0), "{coord:?}: overlap and gap, units²");
let (mut shared, mut alone) = (0.0, 0.0);
for ((a, b), ids) in &owners {
let island = ids.iter().all(|id| *id == "div-island");
if !inside(*a) || !inside(*b) || outer(*a, *b) || island {
continue;
}
let len = ((b.0 - a.0) as f64).hypot((b.1 - a.1) as f64);
assert!(
ids.len() <= 2,
"{coord:?}: edge {a:?}-{b:?} drawn by {ids:?}"
);
if ids.len() == 2 {
shared += len;
} else {
alone += len;
}
}
total_shared += shared;
assert!(
alone == 0.0,
"{coord:?}: {alone:.0} units of inner border drawn by one side, {shared:.0} by both"
);
}
assert!(total_shared > 0.0, "no shared border drawn");
}
#[test]
fn the_gaps_layer_draws_the_gap_pieces_as_the_areas_layer() {
let (areas, gaps) = block();
for (coord, bytes) in render_area_tiles(&areas, &gaps, 8) {
let gap_rings = layer_rings(&bytes, "gaps");
let in_areas: Vec<_> = layer_rings(&bytes, "areas")
.into_iter()
.filter(|(id, _)| id.starts_with("gap-"))
.collect();
assert_eq!(gap_rings, in_areas, "{coord:?}");
}
}
#[test]
fn small_areas_keep_a_shape_while_they_span_two_pixels() {
let (areas, gaps) = block();
for z in 5..=10_u8 {
let present = render_area_tiles(&areas, &gaps, z)
.iter()
.filter(|(c, _)| c.z == z)
.any(|(_, bytes)| {
layer_rings(bytes, "areas")
.iter()
.any(|(id, rings)| id == "div-enclave" && !rings.is_empty())
});
assert!(present, "z{z}: the enclave vanished");
}
}
#[test]
fn two_renders_are_byte_identical() {
let (areas, gaps) = block();
assert_eq!(
render_area_tiles(&areas, &gaps, 8),
render_area_tiles(&areas, &gaps, 8)
);
}
const FINGERPRINTS: &[(u64, u64)] = &[(2, 0xf9db_9a2a_1b4a_6fde)];
#[test]
fn a_change_of_the_tiles_bumps_the_tiles_revision() {
let (areas, gaps) = block();
let mut bytes = Vec::new();
for (coord, tile) in render_area_tiles(&areas, &gaps, 8) {
bytes.extend_from_slice(&[coord.z]);
bytes.extend_from_slice(&coord.x.to_le_bytes());
bytes.extend_from_slice(&coord.y.to_le_bytes());
bytes.extend_from_slice(&(tile.len() as u64).to_le_bytes());
bytes.extend_from_slice(&tile);
}
let fingerprint = xxhash_rust::xxh3::xxh3_64(&bytes);
let revision = tiles_revision().expect("tiles revision");
let recorded = FINGERPRINTS
.iter()
.find(|(r, _)| *r == revision)
.map(|(_, f)| *f);
assert_eq!(
recorded,
Some(fingerprint),
"the areas tiles changed (fingerprint {fingerprint:#x}) under tiles_revision \
{revision}: bump tiles_revision in packages/dataset-builder/data/datasets/boundaries.json and \
record ({}, {fingerprint:#x}) in FINGERPRINTS",
revision + 1
);
assert!(
FINGERPRINTS.iter().all(|(r, _)| *r <= revision),
"a fingerprint is recorded for a revision above {revision}"
);
}
#[test]
fn the_tiles_revision_is_at_least_two() {
assert!(tiles_revision().expect("tiles revision") >= 2);
}
}