#![allow(clippy::unwrap_used)]
use std::collections::HashMap;
use std::io::Read;
use std::path::Path;
use std::sync::Arc;
use arrow::array::{
Array, ArrayRef, BinaryArray, Float32Array, Float64Builder, ListArray, ListBuilder,
StringArray, StringBuilder, StructArray,
};
use arrow::buffer::OffsetBuffer;
use arrow::datatypes::{DataType, Field, Fields, Schema};
use arrow::record_batch::RecordBatch;
use clap::Parser;
use geolith_cli::tile::mvt::proto;
use parquet::arrow::ArrowWriter;
use prost::Message;
struct Segment {
id: &'static str,
subtype: &'static str,
class: &'static str,
line: [(f64, f64); 2],
flags: Vec<(&'static str, Option<(f64, f64)>)>,
}
fn wkb_line(line: &[(f64, f64)]) -> Vec<u8> {
let mut b = vec![1u8];
b.extend_from_slice(&2u32.to_le_bytes());
b.extend_from_slice(&(line.len() as u32).to_le_bytes());
for (x, y) in line {
b.extend_from_slice(&x.to_le_bytes());
b.extend_from_slice(&y.to_le_bytes());
}
b
}
fn road_flags(rows: &[Segment]) -> ListArray {
let mut values = ListBuilder::new(StringBuilder::new());
let mut between = ListBuilder::new(Float64Builder::new());
let mut lengths = Vec::with_capacity(rows.len());
for row in rows {
lengths.push(row.flags.len());
for (flag, range) in &row.flags {
values.values().append_value(flag);
values.append(true);
match range {
Some((a, b)) => {
between.values().append_value(*a);
between.values().append_value(*b);
between.append(true);
}
None => between.append(false),
}
}
}
let values = values.finish();
let between = between.finish();
let fields = Fields::from(vec![
Field::new("values", values.data_type().clone(), true),
Field::new("between", between.data_type().clone(), true),
]);
let rules = StructArray::new(
fields.clone(),
vec![Arc::new(values) as ArrayRef, Arc::new(between)],
None,
);
ListArray::new(
Arc::new(Field::new("item", DataType::Struct(fields), true)),
OffsetBuffer::from_lengths(lengths),
Arc::new(rules),
None,
)
}
fn write_segments(dir: &Path, rows: &[Segment]) {
write_segment_file(dir, "part-00000.parquet", rows);
}
fn write_segment_file(dir: &Path, file: &str, rows: &[Segment]) {
let part = dir.join("theme=transportation/type=segment");
std::fs::create_dir_all(&part).expect("partition dir");
let bbox_fields = Fields::from(vec![
Field::new("xmin", DataType::Float32, false),
Field::new("ymin", DataType::Float32, false),
Field::new("xmax", DataType::Float32, false),
Field::new("ymax", DataType::Float32, false),
]);
let coord = |f: fn(f64, f64) -> f64, i: usize| -> Float32Array {
rows.iter()
.map(|r| {
let [(x0, y0), (x1, y1)] = r.line;
let pair = if i == 0 { (x0, x1) } else { (y0, y1) };
f(pair.0, pair.1) as f32
})
.collect()
};
let bbox = StructArray::new(
bbox_fields.clone(),
vec![
Arc::new(coord(f64::min, 0)) as ArrayRef,
Arc::new(coord(f64::min, 1)),
Arc::new(coord(f64::max, 0)),
Arc::new(coord(f64::max, 1)),
],
None,
);
let flags = road_flags(rows);
let wkb: Vec<Vec<u8>> = rows.iter().map(|r| wkb_line(&r.line)).collect();
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Utf8, false),
Field::new("geometry", DataType::Binary, false),
Field::new("bbox", DataType::Struct(bbox_fields), false),
Field::new("subtype", DataType::Utf8, true),
Field::new("class", DataType::Utf8, true),
Field::new("road_flags", flags.data_type().clone(), true),
]));
let batch = RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.id))) as ArrayRef,
Arc::new(BinaryArray::from_iter_values(wkb.iter())),
Arc::new(bbox),
Arc::new(StringArray::from_iter_values(
rows.iter().map(|r| r.subtype),
)),
Arc::new(StringArray::from_iter_values(rows.iter().map(|r| r.class))),
Arc::new(flags),
],
)
.expect("record batch");
let file = std::fs::File::create(part.join(file)).expect("parquet file");
let mut writer = ArrowWriter::try_new(file, schema, None).expect("writer");
writer.write(&batch).expect("write");
writer.close().expect("close");
}
fn write_square_shapefile(dir: &Path, name: &str, min: f64, max: f64) {
use shapefile::dbase::{Record, TableWriterBuilder};
use shapefile::record::polygon::{Polygon, PolygonRing};
use shapefile::{Point, Writer};
std::fs::create_dir_all(dir).expect("shapefile dir");
let mut writer = Writer::from_path(dir.join(format!("{name}.shp")), TableWriterBuilder::new())
.expect("shapefile writer");
let ring = vec![
Point::new(min, min),
Point::new(min, max),
Point::new(max, max),
Point::new(max, min),
Point::new(min, min),
];
writer
.write_shape_and_record(
&Polygon::with_rings(vec![PolygonRing::Outer(ring)]),
&Record::default(),
)
.expect("write polygon");
}
fn read_varint(buf: &[u8], pos: &mut usize) -> u64 {
let mut value = 0u64;
let mut shift = 0;
loop {
let byte = buf[*pos];
*pos += 1;
value |= u64::from(byte & 0x7f) << shift;
if byte & 0x80 == 0 {
return value;
}
shift += 7;
}
}
fn decompress(bytes: &[u8], compression: u8) -> Vec<u8> {
match compression {
1 => bytes.to_vec(),
2 => {
let mut out = Vec::new();
flate2::read::GzDecoder::new(bytes)
.read_to_end(&mut out)
.expect("gzip");
out
}
other => panic!("unexpected PMTiles compression {other}"),
}
}
fn u64_at(buf: &[u8], at: usize) -> u64 {
u64::from_le_bytes(buf[at..at + 8].try_into().expect("8 bytes"))
}
fn read_all_tiles(archive: &[u8]) -> HashMap<u64, Vec<u8>> {
assert_eq!(&archive[..7], b"PMTiles");
assert_eq!(archive[7], 3);
let (root_off, root_len) = (u64_at(archive, 8), u64_at(archive, 16));
let leaf_off = u64_at(archive, 40);
let data_off = u64_at(archive, 56);
let (internal, tile_comp) = (archive[97], archive[98]);
let mut tiles = HashMap::new();
let mut stack = vec![(root_off, root_len)];
while let Some((off, len)) = stack.pop() {
let dir = decompress(&archive[off as usize..(off + len) as usize], internal);
let mut p = 0;
let n = read_varint(&dir, &mut p) as usize;
let mut ids = Vec::with_capacity(n);
let mut last = 0;
for _ in 0..n {
last += read_varint(&dir, &mut p);
ids.push(last);
}
let runs: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
let lens: Vec<u64> = (0..n).map(|_| read_varint(&dir, &mut p)).collect();
let mut offs = Vec::with_capacity(n);
for i in 0..n {
let raw = read_varint(&dir, &mut p);
offs.push(if raw == 0 && i > 0 {
offs[i - 1] + lens[i - 1]
} else {
raw - 1
});
}
for i in 0..n {
if runs[i] == 0 {
stack.push((leaf_off + offs[i], lens[i]));
continue;
}
let start = (data_off + offs[i]) as usize;
let payload = decompress(&archive[start..start + lens[i] as usize], tile_comp);
for k in 0..runs[i] {
tiles.insert(ids[i] + k, payload.clone());
}
}
}
tiles
}
fn zoom_of(tile_id: u64) -> u8 {
let (mut z, mut base) = (0u8, 0u64);
while tile_id >= base + 4u64.pow(u32::from(z)) {
base += 4u64.pow(u32::from(z));
z += 1;
}
z
}
#[derive(Debug)]
struct Road {
zoom: u8,
kind: String,
detail: Option<String>,
bridge: bool,
reference: Option<String>,
network: Option<String>,
shield: Option<String>,
}
fn roads_in(tiles: &HashMap<u64, Vec<u8>>) -> Vec<Road> {
let mut out = Vec::new();
for (&id, bytes) in tiles {
let tile = proto::Tile::decode(bytes.as_slice()).expect("valid MVT");
for layer in tile.layers.iter().filter(|l| l.name == "roads") {
for f in &layer.features {
let mut props: HashMap<&str, &proto::tile::Value> = HashMap::new();
for pair in f.tags.chunks(2) {
props.insert(
layer.keys[pair[0] as usize].as_str(),
&layer.values[pair[1] as usize],
);
}
let text = |k: &str| props.get(k).and_then(|v| v.string_value.clone());
out.push(Road {
zoom: zoom_of(id),
kind: text("kind").unwrap_or_default(),
detail: text("kind_detail"),
bridge: props.get("is_bridge").and_then(|v| v.bool_value) == Some(true),
reference: text("ref"),
network: text("network"),
shield: text("shield_text"),
});
}
}
}
out
}
fn build(rows: &[Segment]) -> Vec<Road> {
build_with(rows, "overture", "-0.3,51.4,0.3,51.6", None)
}
fn build_with(rows: &[Segment], source: &str, bbox: &str, osm_pbf: Option<&Path>) -> Vec<Road> {
let mut extra = vec!["--roads-source".to_string(), source.into()];
if let Some(pbf) = osm_pbf {
extra.extend(["--osm-pbf".into(), pbf.to_string_lossy().into_owned()]);
}
roads_in(&read_all_tiles(&run_fixture(rows, bbox, 12, &extra)))
}
fn run_fixture(rows: &[Segment], bbox: &str, max_zoom: u8, extra: &[String]) -> Vec<u8> {
run_fixture_on(rows, bbox, max_zoom, extra, None)
}
fn run_fixture_on(
rows: &[Segment],
bbox: &str,
max_zoom: u8,
extra: &[String],
threads: Option<usize>,
) -> Vec<u8> {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
write_segments(&root.join("overture"), rows);
rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
let out = root.join("out.pmtiles");
let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
let mut args = vec![
"geolith".to_string(),
"--data".into(),
arg("overture"),
"--natural-earth".into(),
arg("ne.sqlite"),
"--land-polygons".into(),
arg("land"),
"--water-polygons".into(),
arg("water"),
"--output".into(),
out.to_string_lossy().into_owned(),
"--tmpdir".into(),
arg("tmp"),
"--node-store".into(),
arg("nodes.bin"),
"--no-conflate".into(),
"--bbox".into(),
bbox.into(),
"--max-zoom".into(),
max_zoom.to_string(),
];
args.extend_from_slice(extra);
let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
match threads {
Some(n) => rayon::ThreadPoolBuilder::new()
.num_threads(n)
.build()
.expect("thread pool")
.install(|| geolith_cli::run_with_config(&config)),
None => geolith_cli::run_with_config(&config),
}
.expect("pipeline runs");
std::fs::read(&out).expect("archive")
}
fn layer_counts_at(tiles: &HashMap<u64, Vec<u8>>, zoom: u8) -> HashMap<String, usize> {
let at_zoom: Vec<&Vec<u8>> = tiles
.iter()
.filter(|(id, _)| zoom_of(**id) == zoom)
.map(|(_, bytes)| bytes)
.collect();
assert_eq!(at_zoom.len(), 1, "expected one tile at z{zoom}");
let tile = proto::Tile::decode(at_zoom[0].as_slice()).expect("valid MVT");
tile.layers
.iter()
.map(|l| (l.name.clone(), l.features.len()))
.collect()
}
#[test]
fn a_build_larger_than_one_encode_batch_writes_every_tile() {
for format in ["mvt", "mlt"] {
let args = ["--tile-format".to_string(), format.into()];
let tiles = read_all_tiles(&run_fixture(&[], "-0.3,-0.3,0.3,0.3", 14, &args));
let z14 = tiles.keys().filter(|id| zoom_of(**id) == 14).count();
assert_eq!(z14, 28 * 28, "{format}");
}
}
#[test]
fn a_bbox_build_records_the_bbox_in_the_header() {
let archive = run_fixture(&touching_motorways(), "-0.06,51.49,-0.02,51.51", 12, &[]);
let e7 = |at: usize| i32::from_le_bytes(archive[at..at + 4].try_into().expect("four bytes"));
assert_eq!(
[e7(102), e7(106), e7(110), e7(114)],
[-600_000, 514_900_000, -200_000, 515_100_000]
);
}
fn touching_motorways() -> Vec<Segment> {
[
("west", [(-0.05, 51.5), (-0.04, 51.5)]),
("east", [(-0.04, 51.5), (-0.03, 51.5)]),
]
.into_iter()
.map(|(id, line)| Segment {
id,
subtype: "road",
class: "motorway",
line,
flags: Vec::new(),
})
.collect()
}
#[test]
fn same_attribute_roads_merge_into_one_tile_feature() {
let bbox = "-0.06,51.49,-0.02,51.51";
let tiles = read_all_tiles(&run_fixture(&touching_motorways(), bbox, 12, &[]));
assert_eq!(layer_counts_at(&tiles, 12).get("roads"), Some(&1));
}
#[test]
fn a_bus_route_gives_an_osm_road_no_ref_or_shield() {
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/relations.osm.pbf");
let roads = build_with(&[], "osm", "73.8,18.5,73.9,18.6", Some(&pbf));
let primary: Vec<&Road> = roads
.iter()
.filter(|r| r.detail.as_deref() == Some("primary"))
.collect();
assert!(!primary.is_empty(), "no primary road: {roads:?}");
assert!(
primary
.iter()
.all(|r| r.reference.is_none() && r.network.is_none() && r.shield.is_none()),
"{primary:?}"
);
}
#[test]
fn the_avus_shield_is_its_autobahn_number_on_any_thread_count() {
let pbf = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/berlin-a115.osm.pbf");
let extra = [
"--roads-source".to_string(),
"osm".into(),
"--osm-pbf".into(),
pbf.to_string_lossy().into_owned(),
];
let bbox = "13.19,52.40,13.20,52.42";
let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
let roads = roads_in(&read_all_tiles(&serial));
assert!(!roads.is_empty(), "no roads");
assert!(
roads.iter().all(|r| r.reference.as_deref() == Some("A 115")
&& r.network.as_deref() == Some("BAB")
&& r.shield.as_deref() == Some("A115")),
"{roads:?}"
);
for threads in [2, 4, 8] {
let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
assert!(
parallel == serial,
"{threads} threads: archive bytes differ"
);
}
}
#[test]
fn osm_route_attributes_and_merged_roads_are_identical_on_any_thread_count() {
let pbf = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/route-relations-many-blobs.osm.pbf");
let extra = [
"--roads-source".to_string(),
"osm".into(),
"--osm-pbf".into(),
pbf.to_string_lossy().into_owned(),
];
let bbox = "-0.06,51.49,-0.02,51.51";
let serial = run_fixture_on(&[], bbox, 12, &extra, Some(1));
let tiles = read_all_tiles(&serial);
let roads = roads_in(&tiles);
assert!(
!roads.is_empty()
&& roads
.iter()
.all(|r| r.shield.as_deref() == Some("A1") && r.network.as_deref() == Some("BAB")),
"{roads:?}"
);
assert_eq!(
layer_counts_at(&tiles, 12).get("roads"),
Some(&1),
"the two ways merge"
);
for (run, threads) in [8, 4, 8, 2, 8].into_iter().enumerate() {
let parallel = run_fixture_on(&[], bbox, 12, &extra, Some(threads));
assert!(
parallel == serial,
"run {run} on {threads} threads: archive bytes differ: {:?}",
roads_in(&read_all_tiles(¶llel))
);
}
}
#[test]
fn partially_bridged_overture_road_is_split_in_the_archive() {
let roads = build(&[Segment {
id: "road",
subtype: "road",
class: "motorway",
line: [(-0.2, 51.5), (0.2, 51.5)],
flags: vec![("is_bridge", Some((0.2, 0.5)))],
}]);
let z12: Vec<_> = roads.iter().filter(|r| r.zoom == 12).collect();
assert!(z12.iter().all(|r| r.kind == "highway"), "{z12:?}");
assert!(z12.iter().any(|r| r.bridge), "no bridge piece: {z12:?}");
assert!(
z12.iter().any(|r| !r.bridge),
"whole road marked bridge: {z12:?}"
);
assert!(roads.iter().any(|r| r.zoom == 3 && r.kind == "highway"));
assert!(!roads.iter().any(|r| r.zoom < 3));
}
#[test]
fn overture_rail_is_rail_in_the_archive() {
let roads = build(&[Segment {
id: "rail",
subtype: "rail",
class: "standard_gauge",
line: [(-0.2, 51.45), (0.2, 51.55)],
flags: vec![("is_bridge", None)],
}]);
assert!(!roads.is_empty());
assert!(
roads.iter().all(|r| r.kind == "rail" && r.zoom >= 11),
"{roads:?}"
);
assert!(
roads
.iter()
.all(|r| r.detail.as_deref() == Some("standard_gauge") && r.bridge),
"{roads:?}"
);
assert!(roads.iter().any(|r| r.zoom == 11));
}
fn build_archive(files: &[Vec<Segment>], threads: usize) -> Vec<u8> {
let dir = tempfile::tempdir().expect("tempdir");
let root = dir.path();
for (i, rows) in files.iter().enumerate() {
write_segment_file(
&root.join("overture"),
&format!("part-{i:05}.parquet"),
rows,
);
}
rusqlite::Connection::open(root.join("ne.sqlite")).expect("empty natural earth db");
write_square_shapefile(&root.join("land"), "land", -40_000.0, 40_000.0);
write_square_shapefile(&root.join("water"), "water", 100_000.0, 140_000.0);
let out = root.join("out.pmtiles");
let arg = |p: &str| root.join(p).to_string_lossy().into_owned();
let args = vec![
"geolith".to_string(),
"--data".into(),
arg("overture"),
"--natural-earth".into(),
arg("ne.sqlite"),
"--land-polygons".into(),
arg("land"),
"--water-polygons".into(),
arg("water"),
"--output".into(),
out.to_string_lossy().into_owned(),
"--tmpdir".into(),
arg("tmp"),
"--roads-source".into(),
"overture".into(),
"--no-conflate".into(),
"--bbox".into(),
"-0.3,51.4,0.3,51.6".into(),
"--max-zoom".into(),
"10".into(),
];
let config = geolith_cli::config::Config::try_parse_from(args).expect("config parses");
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build()
.expect("thread pool")
.install(|| geolith_cli::run_with_config(&config))
.expect("pipeline runs");
std::fs::read(&out).expect("archive")
}
fn tied_motorway_files() -> Vec<Vec<Segment>> {
let motorway = |file: usize, k: usize| {
let y = 51.45 + 0.1 * (file * 64 + k) as f64 / 1024.0;
Segment {
id: Box::leak(format!("motorway-{file}-{k}").into_boxed_str()),
subtype: "road",
class: "motorway",
line: [(-0.25, y), (0.25, y + 0.001)],
flags: Vec::new(),
}
};
(0..8)
.map(|file| {
let rows = if file == 0 { 2_000 } else { 1 };
(0..rows).map(|k| motorway(file, k)).collect()
})
.collect()
}
#[test]
fn tile_archive_is_byte_identical_across_runs_and_thread_counts() {
let files = tied_motorway_files();
let serial = build_archive(&files, 1);
let tiles = read_all_tiles(&serial);
assert!(
!roads_in(&tiles).is_empty(),
"fixture produced no roads to order"
);
for (run, threads) in [4, 8, 4, 8].into_iter().enumerate() {
let parallel = build_archive(&files, threads);
let other = read_all_tiles(¶llel);
let differing = tiles
.iter()
.filter(|(id, bytes)| other.get(id) != Some(bytes))
.count();
assert_eq!(
differing,
0,
"run {run} on {threads} threads: {differing} of {} tiles differ",
tiles.len()
);
assert!(
parallel == serial,
"run {run} on {threads} threads: archive bytes differ"
);
}
}