1#![warn(missing_docs)]
2
3pub mod cli;
17mod cli_error;
18pub mod config;
19
20pub use cli_error::CliError;
21pub use geolith::error;
22pub use geolith::output;
23pub use geolith::{conflation, progress, source};
24pub use geolith_dataset_builder as dataset;
25pub use geolith_search_builder as geocoding;
26pub use geolith_tiles_builder::{
27 geometry, layers, raster, reconstruct, sort, splat, terrain, tile, timing,
28};
29
30#[non_exhaustive]
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum PipelineAction {
34 Geocoding,
36 Routing(std::path::PathBuf),
38 Tiles,
40 UnsupportedFormat(String),
42}
43
44#[must_use]
50pub fn select_action(config: &config::Config) -> PipelineAction {
51 match config.output_format.as_str() {
52 "geocoding" => PipelineAction::Geocoding,
53 "routing" => {
54 let out = config
55 .routing_output
56 .clone()
57 .unwrap_or_else(|| std::path::PathBuf::from("planet-routing.glx"));
58 PipelineAction::Routing(out)
59 }
60 "tiles" => PipelineAction::Tiles,
61 other => PipelineAction::UnsupportedFormat(other.to_owned()),
62 }
63}
64
65fn init_tracing() {
70 timing::init();
71 tracing_subscriber::fmt()
75 .with_timer(timing::ElapsedTimer)
76 .with_env_filter(
77 tracing_subscriber::EnvFilter::try_from_default_env()
78 .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
79 )
80 .with_writer(std::io::stderr)
81 .init();
82}
83
84pub fn run() -> Result<(), CliError> {
90 let command = cli::parse_args();
91 init_tracing();
92 run_command(command)
93}
94
95pub fn run_command(command: cli::Command) -> Result<(), CliError> {
104 tracing::info!("geolith v{}", env!("CARGO_PKG_VERSION"));
105
106 match command {
107 cli::Command::Terrain(args) => run_terrain(&args),
108 cli::Command::SplatTiles(args) => run_splat_tiles(&args),
109 cli::Command::Raster(args) => run_raster(&args),
110 cli::Command::Reconstruct(args) => run_reconstruct(&args),
111 cli::Command::Dataset(args) => dataset::run(&args).map_err(CliError::from),
112 cli::Command::Notices => {
113 print!("{}", cli::NOTICE);
114 Ok(())
115 }
116 cli::Command::Tiles(config) => {
117 tracing::info!("config: {:?}", config);
118 run_with_config(&config)
119 }
120 }
121}
122
123#[must_use]
126pub fn exit_code(error: &CliError) -> i32 {
127 match error {
128 CliError::Dataset(error) => error.exit_code(),
129 _ => 1,
130 }
131}
132
133pub fn run_raster(args: &cli::RasterArgs) -> Result<(), CliError> {
140 let options = args.build_options()?;
141 raster::run(&options, &args.output).map_err(CliError::from)
142}
143
144pub fn run_terrain(args: &cli::TerrainArgs) -> Result<(), CliError> {
150 let options = args.tiler_options()?;
151 terrain::run(&args.dem, args.dem_crs, &args.output, &args.name, &options)
152 .map_err(CliError::from)
153}
154
155pub fn run_splat_tiles(args: &cli::SplatTilesArgs) -> Result<(), CliError> {
161 splat::run(&args.job()).map_err(CliError::from)
162}
163
164pub fn run_reconstruct(args: &cli::ReconstructArgs) -> Result<(), CliError> {
172 reconstruct::run_reconstruct(&args.video, &args.output, &args.options()).map_err(CliError::from)
173}
174
175pub fn run_with_config(config: &config::Config) -> Result<(), CliError> {
185 match select_action(config) {
186 PipelineAction::Geocoding => run_search(config),
187 PipelineAction::Routing(out) => run_routing(config, &out),
188 PipelineAction::UnsupportedFormat(format) => Err(CliError::UnsupportedFormat { format }),
189 PipelineAction::Tiles => {
190 geolith_tiles_builder::run(&config.tiles()?).map_err(CliError::from)
191 }
192 }
193}
194
195fn run_search(config: &config::Config) -> Result<(), CliError> {
201 let data = config.required_path(config::PathFlag::Data)?;
202 let output = match config.geocoding_output.clone() {
203 Some(path) => path,
204 None => geocoding::pipeline::default_geocoding_output(
205 config.required_path(config::PathFlag::Output)?,
206 &config.geocoding_format,
207 ),
208 };
209 let mut options = geolith_search_builder::SearchOptions::new(data, output);
210 options.format.clone_from(&config.geocoding_format);
211 options.osm_pbf.clone_from(&config.osm_pbf);
212 options.india_outline.clone_from(&config.india_outline);
213 options.bbox.clone_from(&config.bbox);
214 options.tmpdir.clone_from(&config.tmpdir);
215 options.node_store.clone_from(&config.node_store);
216 options.reuse_node_cache = config.reuse.node_cache;
217 options
218 .wikimedia_importance
219 .clone_from(&config.wikimedia_importance);
220 options.pg_index_flavor = config.pg_index_flavor;
221 geolith_search_builder::run(&options).map_err(CliError::from)
222}
223
224fn run_routing(config: &config::Config, out: &std::path::Path) -> Result<(), CliError> {
231 let Some(pbf) = config.osm_pbf.as_deref() else {
232 return Err(CliError::RoutingNeedsOsmPbf);
233 };
234 let mut options = geolith_routing_builder::RoutingOptions::new(pbf, out);
235 options.tmpdir.clone_from(&config.tmpdir);
236 options
237 .default_speeds
238 .clone_from(&config.routing_default_speeds);
239 options.admins.clone_from(&config.routing_admins);
240 options.timezones.clone_from(&config.routing_timezones);
241 options
242 .predicted_speeds
243 .clone_from(&config.routing_predicted_speeds);
244 options.metric_out.clone_from(&config.routing_metric_out);
245 options.cch.clone_from(&config.routing_cch);
246 if let (Some(_), Some(path)) = (
249 config.routing_admins.as_deref(),
250 config.india_outline.as_deref(),
251 ) {
252 options.india = Some(
253 geocoding::india::IndiaOutline::load(path)?
254 .polygons()
255 .clone(),
256 );
257 }
258 geolith_routing_builder::run(&options).map_err(CliError::from)
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264 use crate::config::Config;
265
266 fn make_config(output_format: &str) -> Config {
267 Config {
268 data: Some(std::path::PathBuf::from("/dev/null")),
269 osm_pbf: None,
270 natural_earth: Some(std::path::PathBuf::from("/dev/null")),
271 water_polygons: Some(std::path::PathBuf::from("/dev/null")),
272 land_polygons: Some(std::path::PathBuf::from("/dev/null")),
273 india_boundary: None,
274 india_outline: None,
275 output: Some(std::path::PathBuf::from("/dev/null")),
276 output_format: output_format.to_string(),
277 tile_format: "mvt".to_string(),
278 geocoding_format: "pg-copy".to_string(),
279 pg_index_flavor: crate::config::PgIndexFlavor::default(),
280 geocoding_output: None,
281 wikimedia_importance: None,
282 routing_output: None,
283 routing_predicted_speeds: None,
284 routing_metric_out: None,
285 routing_cch: Vec::new(),
286 routing_default_speeds: None,
287 routing_admins: None,
288 routing_timezones: None,
289 bbox: None,
290 max_zoom: 15,
291 threads: None,
292 chunk_size_mb: 0,
293 tmpdir: None,
294 node_store: None,
295 reuse: crate::config::RunReuse {
296 node_cache: false,
297 resume: false,
298 },
299 buildings_source: "both".to_string(),
300 places_source: "both".to_string(),
301 roads_source: "both".to_string(),
302 pois_source: "both".to_string(),
303 water_source: "both".to_string(),
304 landuse_source: "both".to_string(),
305 divisions_source: "overture".to_string(),
306 landcover_source: "overture".to_string(),
307 bathymetry_source: "overture".to_string(),
308 bridge_dir: None,
309 bridge_files: vec![],
310 no_conflate: false,
311 reclaim_source_after_read: false,
312 reclaim_chunks: false,
313 no_disk_check: false,
314 }
315 }
316
317 #[test]
318 fn select_action_geocoding() {
319 let cfg = make_config("geocoding");
320 assert_eq!(select_action(&cfg), PipelineAction::Geocoding);
321 }
322
323 #[test]
324 fn select_action_routing_default_path() {
325 let cfg = make_config("routing");
326 assert_eq!(
327 select_action(&cfg),
328 PipelineAction::Routing(std::path::PathBuf::from("planet-routing.glx"))
329 );
330 }
331
332 #[test]
333 fn select_action_routing_explicit_path() {
334 let mut cfg = make_config("routing");
335 cfg.routing_output = Some(std::path::PathBuf::from("/tmp/custom.glx"));
336 assert_eq!(
337 select_action(&cfg),
338 PipelineAction::Routing(std::path::PathBuf::from("/tmp/custom.glx"))
339 );
340 }
341
342 #[test]
343 fn select_action_tiles() {
344 let cfg = make_config("tiles");
345 assert_eq!(select_action(&cfg), PipelineAction::Tiles);
346 }
347
348 #[test]
349 fn select_action_unsupported_format() {
350 let cfg = make_config("osrm");
351 assert_eq!(
352 select_action(&cfg),
353 PipelineAction::UnsupportedFormat("osrm".to_string())
354 );
355 }
356
357 #[test]
358 fn run_with_config_rejects_an_unsupported_format() {
359 let cfg = make_config("unknown");
360 let err = run_with_config(&cfg).expect_err("a typo must not exit 0");
361 assert!(format!("{err}").contains("'unknown'"), "{err}");
362 }
363
364 #[test]
365 fn run_with_config_routing_needs_an_osm_pbf() {
366 let mut cfg = make_config("routing");
367 cfg.routing_output = Some(std::path::PathBuf::from("/tmp/graph.glx"));
368 let err = run_with_config(&cfg).expect_err("no graph without a PBF");
369 assert!(format!("{err}").contains("--osm-pbf"), "{err}");
370 }
371
372 #[test]
373 fn run_with_config_tiles_surfaces_an_unreadable_data_dir() {
374 let cfg = make_config("tiles");
375 let err = run_with_config(&cfg).expect_err("/dev/null is not a source directory");
376 assert!(
377 !format!("{err}").is_empty(),
378 "the failure is reported rather than panicking"
379 );
380 }
381
382 fn with_tracing<T>(body: impl FnOnce() -> T) -> T {
388 let subscriber = tracing_subscriber::fmt()
389 .with_test_writer()
390 .with_max_level(tracing::Level::TRACE)
391 .finish();
392 tracing::subscriber::with_default(subscriber, body)
393 }
394
395 fn write_dem(values: Vec<f32>, nodata: Option<&str>) -> tempfile::NamedTempFile {
401 use std::io::{Seek as _, Write as _};
402
403 use tiff::encoder::{TiffEncoder, colortype};
404 use tiff::tags::Tag;
405
406 let mut buffer = std::io::Cursor::new(Vec::new());
407 {
408 let mut encoder = TiffEncoder::new(&mut buffer).expect("tiff encoder");
409 let mut image = encoder
410 .new_image::<colortype::Gray32Float>(4, 4)
411 .expect("image encoder");
412 let directory = image.encoder();
413 directory
414 .write_tag(Tag::Unknown(33_550), &[10.0_f64, 10.0, 0.0][..])
415 .expect("pixel scale");
416 directory
417 .write_tag(
418 Tag::Unknown(33_922),
419 &[0.0_f64, 0.0, 0.0, 400_000.0, 5_100_000.0, 0.0][..],
420 )
421 .expect("tiepoint");
422 directory
423 .write_tag(
424 Tag::Unknown(34_735),
425 &[1_u32, 1, 0, 1, 3072, 0, 1, 32_632][..],
426 )
427 .expect("geokeys");
428 if let Some(sentinel) = nodata {
429 directory
430 .write_tag(Tag::Unknown(42_113), sentinel)
431 .expect("nodata");
432 }
433 image.write_data(&values).expect("write samples");
434 }
435 buffer.rewind().expect("rewind");
436
437 let mut file = tempfile::Builder::new()
438 .suffix(".tif")
439 .tempfile()
440 .expect("temp file");
441 file.write_all(&buffer.into_inner()).expect("write tiff");
442 file.flush().expect("flush");
443 file
444 }
445
446 fn write_ply(vertex_count: usize) -> tempfile::NamedTempFile {
447 use std::io::Write as _;
448
449 const PROPERTIES: [&str; 14] = [
450 "x", "y", "z", "f_dc_0", "f_dc_1", "f_dc_2", "opacity", "scale_0", "scale_1",
451 "scale_2", "rot_0", "rot_1", "rot_2", "rot_3",
452 ];
453
454 let mut file = tempfile::NamedTempFile::new().expect("temp file");
455 let mut header = String::from("ply\nformat binary_little_endian 1.0\n");
456 header.push_str(&format!("element vertex {vertex_count}\n"));
457 for property in PROPERTIES {
458 header.push_str(&format!("property float {property}\n"));
459 }
460 header.push_str("end_header\n");
461 file.write_all(header.as_bytes()).expect("header");
462
463 for index in 0..vertex_count {
464 let offset = index as f32;
465 for value in [
466 offset,
467 offset * 0.5,
468 offset * 0.25,
469 0.4,
470 0.5,
471 0.6,
472 1.1,
473 -2.0,
474 -2.1,
475 -2.2,
476 1.0,
477 0.0,
478 0.0,
479 0.0,
480 ] {
481 file.write_all(&value.to_le_bytes()).expect("vertex");
482 }
483 }
484 file.flush().expect("flush");
485 file
486 }
487
488 fn terrain_args(dem: &std::path::Path, output: &std::path::Path) -> cli::TerrainArgs {
489 cli::TerrainArgs {
490 dem: vec![dem.to_path_buf()],
491 clip: None,
492 output: output.to_path_buf(),
493 encoding: "mapbox".to_owned(),
494 min_zoom: 12,
495 max_zoom: 13,
496 tile_size: 256,
497 dem_crs: None,
498 name: "terrain".to_owned(),
499 }
500 }
501
502 fn splat_args(ply: &std::path::Path, output: &std::path::Path) -> cli::SplatTilesArgs {
503 cli::SplatTilesArgs {
504 ply: ply.to_path_buf(),
505 output: output.to_path_buf(),
506 longitude: 7.9797,
507 latitude: 45.9756,
508 altitude: 2250.0,
509 max_splats_per_tile: 4,
510 max_depth: 2,
511 root_geometric_error: 64.0,
512 antialiased: false,
513 emit_scene_spz: true,
514 crop_percentile: 0.0,
515 scale: 1.0,
516 coverage_boost_scale: 0.0,
517 }
518 }
519
520 #[test]
521 fn run_terrain_writes_an_archive() {
522 let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
523 let dem = write_dem(values, None);
524 let dir = tempfile::tempdir().expect("tempdir");
525 let output = dir.path().join("terrain.pmtiles");
526
527 with_tracing(|| run_terrain(&terrain_args(dem.path(), &output)))
528 .expect("terrain pipeline runs");
529
530 let bytes = std::fs::read(&output).expect("archive exists");
531 assert_eq!(&bytes[..7], b"PMTiles");
532 }
533
534 #[test]
535 fn run_terrain_writes_an_archive_for_valid_and_all_nodata_dems() {
536 let dir = tempfile::tempdir().expect("tempdir");
537
538 let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
539 let dem = write_dem(values, None);
540 let with_samples = dir.path().join("a.pmtiles");
541 with_tracing(|| run_terrain(&terrain_args(dem.path(), &with_samples)))
542 .expect("a DEM with valid samples must tile");
543
544 let dem = write_dem(vec![-9999.0; 16], Some("-9999"));
545 let all_nodata = dir.path().join("b.pmtiles");
546 with_tracing(|| run_terrain(&terrain_args(dem.path(), &all_nodata)))
547 .expect("an all-nodata DEM must still tile");
548
549 for path in [&with_samples, &all_nodata] {
550 let bytes = std::fs::read(path).expect("archive must exist on disk");
551 assert_eq!(
552 &bytes[..7],
553 b"PMTiles",
554 "{path:?} must be a PMTiles archive"
555 );
556 }
557 }
558
559 #[test]
560 fn run_terrain_propagates_failures() {
561 let dir = tempfile::tempdir().expect("tempdir");
562 let mut args = terrain_args(
563 std::path::Path::new("/nonexistent/dem.tif"),
564 &dir.path().join("out.pmtiles"),
565 );
566
567 args.encoding = "rainbow".to_owned();
568 assert!(
569 with_tracing(|| run_terrain(&args)).is_err(),
570 "the encoding is validated before the DEM is opened"
571 );
572
573 args.encoding = "mapbox".to_owned();
574 args.dem_crs = Some(27_700);
575 assert!(
576 with_tracing(|| run_terrain(&args)).is_err(),
577 "an unsupported EPSG fails before the DEM is read"
578 );
579
580 args.dem_crs = None;
581 assert!(
582 with_tracing(|| run_terrain(&args)).is_err(),
583 "a missing DEM surfaces as an error"
584 );
585 }
586
587 #[test]
588 fn run_splat_tiles_writes_a_tileset_and_scene() {
589 let ply = write_ply(32);
590 let dir = tempfile::tempdir().expect("tempdir");
591 let output = dir.path().join("tileset");
592
593 with_tracing(|| run_splat_tiles(&splat_args(ply.path(), &output)))
594 .expect("splat pipeline runs");
595
596 assert!(output.join("tileset.json").is_file());
597 assert!(output.join("tiles/0.glb").is_file());
598 assert!(
599 output.join("scene.spz").is_file(),
600 "--emit-scene-spz writes the standalone packet"
601 );
602 }
603
604 #[test]
605 fn run_splat_tiles_skips_the_scene_when_not_requested() {
606 let ply = write_ply(8);
607 let dir = tempfile::tempdir().expect("tempdir");
608 let output = dir.path().join("tileset");
609
610 let mut args = splat_args(ply.path(), &output);
611 args.emit_scene_spz = false;
612 with_tracing(|| run_splat_tiles(&args)).expect("splat pipeline runs");
613
614 assert!(output.join("tileset.json").is_file());
615 assert!(!output.join("scene.spz").exists());
616 }
617
618 #[test]
619 fn run_splat_tiles_propagates_failures() {
620 let dir = tempfile::tempdir().expect("tempdir");
621 assert!(
622 with_tracing(|| run_splat_tiles(&splat_args(
623 std::path::Path::new("/nonexistent/scene.ply"),
624 &dir.path().join("tileset"),
625 )))
626 .is_err(),
627 "a missing PLY surfaces as an error"
628 );
629
630 let empty = write_ply(0);
631 let err =
632 with_tracing(|| run_splat_tiles(&splat_args(empty.path(), &dir.path().join("empty"))))
633 .expect_err("an empty cloud cannot be tiled");
634 assert!(format!("{err}").contains("empty splat cloud"), "{err}");
635 }
636
637 #[test]
638 fn run_command_dispatches_every_verb() {
639 let dir = tempfile::tempdir().expect("tempdir");
640
641 let values: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect();
642 let dem = write_dem(values, None);
643 let terrain_out = dir.path().join("dispatched.pmtiles");
644 with_tracing(|| {
645 run_command(cli::Command::Terrain(Box::new(terrain_args(
646 dem.path(),
647 &terrain_out,
648 ))))
649 })
650 .expect("the terrain verb reaches run_terrain");
651 assert!(terrain_out.exists());
652
653 let ply = write_ply(8);
654 let splat_out = dir.path().join("dispatched-tileset");
655 with_tracing(|| {
656 run_command(cli::Command::SplatTiles(Box::new(splat_args(
657 ply.path(),
658 &splat_out,
659 ))))
660 })
661 .expect("the splat verb reaches run_splat_tiles");
662 assert!(splat_out.join("tileset.json").exists());
663
664 let config = make_config("not-a-real-format");
665 let err = with_tracing(|| run_command(cli::Command::Tiles(Box::new(config))))
666 .expect_err("the flat invocation reaches run_with_config, which rejects the format");
667 assert!(format!("{err}").contains("not-a-real-format"), "{err}");
668
669 let raster_args = cli::RasterArgs {
670 url_template: "http://127.0.0.1:1/{z}/{x}/{y}.jpg".into(),
671 output: dir.path().join("dispatched-raster.pmtiles"),
672 min_zoom: 0,
673 max_zoom: 0,
674 bbox: None,
675 bbox_min_zoom: 0,
676 format: "jpeg".into(),
677 concurrency: 1,
678 request_delay_ms: 0,
679 attempts: 1,
680 cache_dir: Some(dir.path().join("raster-cache")),
681 name: "dispatch-test".into(),
682 attribution: None,
683 };
684 let err = with_tracing(|| run_command(cli::Command::Raster(Box::new(raster_args))))
685 .expect_err("port 1 refuses connections, proving dispatch reached run_raster");
686 assert!(format!("{err}").contains("raster source error"));
687 }
688}