Skip to main content

utz_build_cli/cmd/
generate.rs

1#![cfg_attr(
2    on_docsrs,
3    doc = "[`utz_build::Config`]: https://docs.rs/utz_build/latest/utz_build/config/struct.Config.html"
4)]
5#![cfg_attr(on_docsrs, doc = "")]
6//! Encodes an asset to disk from explicit knobs. The asset is the input
7//! for `utz_bench_cli`, the embedded bench firmware (which embeds an
8//! *uncompressed* asset and borrows it zero-copy from flash via
9//! `Finder::from_static()`), and any flash-partition/OTA image.
10//! Every flag maps to one [`utz_build::Config`] knob.
11//!
12//! ```text
13//! utz_build_cli gen [ds] [epsilon_m] [--codec none|gzip|zstd|brotli|xz]
14//!     [--qbits 24] [--grid-deg 2] [--algorithm rdp|vw|ii|none]
15//!     [--geom varint-arcs|fixed-width-arcs|full-rings|coarse]
16//!     [--w-min <mult>] [-o out.utz]
17//! ```
18//!
19//! [`utz_build::Config`]: ../../utz_build/config/struct.Config.html
20
21use std::path::PathBuf;
22
23use utz_build::{Codec, Config, Error, GeomEncoding, SimplifyAlgorithm};
24
25#[derive(clap::Args)]
26pub struct Args {
27    /// The dataset, one of [land-]now|1970|all.
28    #[arg(default_value = "now")]
29    ds: String,
30    /// The simplification tolerance ceiling in meters.
31    #[arg(default_value_t = 500.0)]
32    epsilon_m: f64,
33    /// The payload codec, one of none|gzip|zstd|brotli|xz (firmware wants
34    /// none).
35    #[arg(long, default_value = "zstd")]
36    codec: String,
37    /// The quantization width, one of 16/24/32.
38    #[arg(long, default_value_t = 24)]
39    qbits: u32,
40    /// The grid cell size in degrees (fractional values are allowed, e.g.
41    /// 4/3 as 1.333…).
42    #[arg(long, default_value_t = 2.0)]
43    grid_deg: f64,
44    /// The simplification algorithm, one of none|rdp|vw|ii.
45    #[arg(long, default_value = "rdp")]
46    algorithm: String,
47    /// The geometry encoding, one of
48    /// varint-arcs|fixed-width-arcs|full-rings|coarse (see `GeomEncoding`
49    /// for the size/speed ladder).
50    #[arg(long, default_value = "varint-arcs")]
51    geom: String,
52    /// Enables population weighting with this floor multiplier, strictly
53    /// between 0 and 1 (the presets use 0.001-0.10).
54    #[arg(long)]
55    w_min: Option<f64>,
56    /// The output path (the default is `<ds>-<epsilon>m[-w<min>]-<codec>.utz`).
57    #[arg(long, short)]
58    out: Option<PathBuf>,
59}
60
61/// # Errors
62/// The command fails on an unknown codec/algorithm/geom name, a dataset
63/// load/parse or encode failure, the verify lookup coming back empty, or
64/// an I/O error writing the asset and its guard file.
65pub fn run(args: Args) -> utz_build::Result<()> {
66    let codec = Codec::from_name(&args.codec).ok_or_else(|| {
67        Error::Msg(format!(
68            "unknown codec {:?}: use none|gzip|zstd|brotli|xz",
69            args.codec
70        ))
71    })?;
72    let simplify = SimplifyAlgorithm::from_name(&args.algorithm).ok_or_else(|| {
73        Error::Msg(format!(
74            "unknown algorithm {:?}: use none|rdp|vw|ii",
75            args.algorithm
76        ))
77    })?;
78    let geom = GeomEncoding::from_name(&args.geom).ok_or_else(|| {
79        Error::Msg(format!(
80            "unknown geom {:?}: use varint-arcs|fixed-width-arcs|full-rings|coarse",
81            args.geom
82        ))
83    })?;
84    let out = args.out.unwrap_or_else(|| {
85        let weight_suffix = args
86            .w_min
87            .map(|floor| format!("-w{floor}"))
88            .unwrap_or_default();
89        PathBuf::from(format!(
90            "{}-{}m{}-{}.utz",
91            args.ds, args.epsilon_m, weight_suffix, args.codec
92        ))
93    });
94
95    let mut config = Config::new()
96        .dataset(utz_build::dataset(&args.ds)?)
97        .epsilon_meters(args.epsilon_m)
98        .quant_bits(args.qbits)
99        .grid_deg(args.grid_deg)
100        .codec(codec)
101        .simplify_algorithm(simplify)
102        .geom(geom)
103        .out_path(&out);
104    if let Some(floor) = args.w_min {
105        config = config.density_weight_floor(floor);
106    }
107    let path = config.generate()?;
108
109    // sanity: the runtime must accept what we just wrote
110    let container = std::fs::read(&path)?;
111    let size = container.len();
112    let finder = utz::Finder::from_vec(container)?;
113    let release = finder.tzbb_release().to_string();
114    if finder
115        .lookup(utz::Position {
116            lon: -0.1276,
117            lat: 51.5072,
118        })?
119        .is_none()
120    {
121        // don't leave a bad asset (or its guard) where a good one may
122        // have been
123        let _ = std::fs::remove_file(&path);
124        let _ = std::fs::remove_file(path.with_extension("utz.guard.rs"));
125        return Err(Error::Msg("verify lookup failed".into()));
126    }
127    #[expect(clippy::cast_precision_loss, reason = "asset size ≪ 2^53; KiB display")]
128    let kib = size as f64 / 1024.0;
129    println!(
130        "wrote {} ({kib:.1} KiB, {codec:?}, TZBB {release})",
131        path.display()
132    );
133    Ok(())
134}