Skip to main content

utz_build/
lib.rs

1// docs.rs-only overrides of the sibling links; see utz/src/lib.rs.
2#![cfg_attr(
3    on_docsrs,
4    doc = "[custom]: https://docs.rs/utz/latest/utz/index.html#building-a-custom-asset"
5)]
6#![cfg_attr(
7    on_docsrs,
8    doc = "[cli]: https://docs.rs/utz_build_cli/latest/utz_build_cli/index.html"
9)]
10#![cfg_attr(on_docsrs, doc = "[reader]: https://docs.rs/utz/latest/utz/index.html")]
11#![cfg_attr(on_docsrs, doc = "")]
12//! The μTZ builder library generates custom `.utz` assets from a
13//! `build.rs`.
14//!
15//! Everything routes through the typed builder, [`Config`]. In a
16//! `build.rs` (with `utz_build` as a build-dependency):
17//!
18//! ```no_run
19//! utz_build::Config::new()
20//!     .dataset(utz_build::Dataset::Now)
21//!     .epsilon_meters(500.0)  // simplification tolerance ceiling
22//!     .quant_bits(24)     // 16 / 24 / 32
23//!     .codec(utz_build::Codec::Gzip)
24//!     .generate()?;       // writes $OUT_DIR/tz.utz (+ .guard.rs)
25//! # Ok::<(), utz_build::Error>(())
26//! ```
27//!
28//! The [utz crate's "Building a custom asset"][custom] section is the
29//! full walkthrough: embedding the asset, the guard file, and matching
30//! reader features. Every knob is a [`Config`] method; everything else
31//! this crate exposes (source loading, density weighting) is machinery
32//! those methods drive.
33//!
34//! # Source data
35//!
36//! Sources download on first use into a per-user cache directory
37//! (`$XDG_CACHE_HOME/utz_build`, overridable with `UTZ_CACHE_DIR` or
38//! [`Config::cache_dir()`]; see
39//! [`cache_dir()`]) and are revalidated with conditional GETs: the
40//! [timezone-boundary-builder] `GeoJSON` (tens of MB per dataset,
41//! [ODbL]), and for density-weighted recipes the [GHS-POP] population
42//! raster (~460 MB once, [CC BY 4.0]). Set `UTZ_TZBB_RELEASE` to pin a
43//! TZBB release for reproducible builds (see [`loader`]).
44//!
45//! [custom]: ../utz/index.html#building-a-custom-asset
46//! [ODbL]: https://opendatacommons.org/licenses/odbl/
47//! [GHS-POP]: https://human-settlement.emergency.copernicus.eu/ghs_pop2023.php
48//! [CC BY 4.0]: https://creativecommons.org/licenses/by/4.0/
49//!
50//! # Datasets
51//!
52//! The source data is OSM [timezone-boundary-builder]. The dataset
53//! picks which TZBB release an asset is generated from and is baked
54//! in at generation time. Its two knobs are the zone set and ocean
55//! coverage: `now` and `1970` merge zones whose rules are identical
56//! since that date, `all` keeps every distinct tzid, and a `land-`
57//! prefix selects the land-only releases (oceans are covered by
58//! default).
59//!
60//! | zone set | zones | `land-` zones | merge |
61//! |----------|------:|--------------:|-------|
62//! | `now`    |    64 |            63 | zones identical from today onward merged |
63//! | `1970`   |   304 |           301 | zones identical since 1970 merged |
64//! | `all`    |   444 |           419 | every distinct tzid kept |
65//!
66//! Dropping the oceans does not shrink an asset: the shared-arc
67//! geometry encodings make ocean coverage nearly free, and the
68//! `land-` variants actually measure slightly bigger (at the tiny
69//! recipe's knobs, uncompressed: `land-now` 89.7 KiB vs `now`
70//! 86.7 KiB). Their best use is coarse (grid-only) assets that will
71//! only ever be queried for land coordinates: a coarse asset answers
72//! at cell precision, and with oceans covered a land point near the
73//! coast resolves to the ocean timezone whenever most of its cell is
74//! ocean; without ocean zones the cell keeps the land answer.
75//!
76//! # Related crates
77//!
78//! The [`utz_build_cli`][cli] binary (`gen` and `gen-preset`, the CLI
79//! counterpart of a `build.rs`) lives in its own crate: it carries the
80//! runtime-reader dependency, so this library stays reader-free and
81//! build scripts are not rebuilt by reader-only changes. The generated
82//! assets are read by [`utz`][reader]; the repo-internal measurement
83//! and viewer tooling lives in the unpublished `utz_dev_cli` and
84//! `utz_viz` crates.
85//!
86//! [timezone-boundary-builder]: https://github.com/evansiroky/timezone-boundary-builder
87//! [`Config`]: ../utz_build/config/struct.Config.html
88//! [`Config::cache_dir()`]: ../utz_build/config/struct.Config.html#method.cache_dir
89//! [`cache_dir()`]: ../utz_build/fn.cache_dir.html
90//! [cli]: ../utz_build_cli/index.html
91//! [`loader`]: ../utz_build/loader/index.html
92//! [reader]: ../utz/index.html
93
94#![cfg_attr(docsrs, feature(doc_cfg))]
95
96// The consumer surface: Config plus the names its knobs and results
97// need. The encoder machinery itself stays in utz_encode; the internal
98// tooling (utz_dev_cli, utz_viz) depends on that crate directly.
99pub use utz_common::{Dataset, presets};
100pub use utz_encode::Feat;
101pub use utz_encode::encode::{Codec, GeomEncoding, SimplifyAlgorithm};
102
103pub mod error;
104pub use error::{Error, Result};
105
106pub mod config;
107pub mod density;
108pub mod download;
109pub mod loader;
110
111pub use config::Config;
112
113use std::path::PathBuf;
114
115/// Parses a dataset name (`[land-]now|1970|all`):
116/// [`Dataset::from_name()`] with this crate's error type.
117///
118/// # Errors
119/// Returns an error for an unrecognized dataset name.
120pub fn dataset(name: &str) -> crate::Result<Dataset> {
121    Dataset::from_name(name).ok_or_else(|| Error::UnknownDataset { ds: name.into() })
122}
123
124/// Loads a dataset via the download+`GeoJSON` pipeline (conditional-GET
125/// cached).
126///
127/// # Errors
128/// See [`load_with_release()`].
129pub fn load(dataset_name: &str) -> crate::Result<Vec<Feat>> {
130    Ok(load_with_release(dataset_name)?.0)
131}
132
133/// Runs [`load()`] and also returns the TZBB release tag the features
134/// came from, for stamping container headers (provenance). The tag is
135/// `"dev"` when the source isn't a pinned release (the offline fallback).
136///
137/// # Errors
138/// Returns an error for an invalid dataset name or a TZBB download/parse
139/// failure.
140pub fn load_with_release(dataset_name: &str) -> crate::Result<(Vec<Feat>, String)> {
141    load_with_release_in(dataset_name, &cache_dir())
142}
143
144/// Runs [`load_with_release()`] against an explicit cache directory
145/// instead of the [`cache_dir()`] chain.
146///
147/// # Errors
148/// Fails as [`load_with_release()`] does.
149pub fn load_with_release_in(
150    dataset_name: &str,
151    cache_dir: &std::path::Path,
152) -> crate::Result<(Vec<Feat>, String)> {
153    loader::load_tzbb(dataset(dataset_name)?, cache_dir)
154}
155
156/// Runs `encode::encode()` with population-density-weighted
157/// simplification. The per-edge ε multiplier is a simplification knob, so
158/// it lives here with the density code; `utz_encode` itself stays
159/// density-agnostic (see the `encode::encode()` docs).
160///
161/// # Errors
162/// Returns an error when payload encoding fails.
163pub fn encode_weighted(
164    features: &[Feat],
165    params: &utz_encode::encode::Params,
166    grid: &density::DensityGrid,
167    model: utz_simplify::DensityWeight,
168) -> crate::Result<Vec<u8>> {
169    let epsilon_deg = params.epsilon_m / utz_common::METERS_PER_DEG;
170    let algorithm = utz_encode::encode::to_simplify(params.simplify, epsilon_deg);
171    let topology = utz_encode::topo::build_topology_weighted(features, algorithm, &|a, b| {
172        model.weight(grid.max_along(a, b))
173    });
174    Ok(utz_encode::encode::finish(
175        &utz_encode::encode::payload_from_topology(
176            &topology,
177            &topology.arc_coords,
178            features,
179            params,
180        )?
181        .0,
182        params.codec,
183    )?)
184}
185
186/// Returns the source-data cache directory, resolved at call time as the
187/// first match in this chain:
188///
189/// 1. `$UTZ_CACHE_DIR` (the μTZ workspace pins this to its `cache/`
190///    via `.cargo/config.toml`, so in-repo builds share one cache).
191/// 2. `$XDG_CACHE_HOME/utz_build`.
192/// 3. `%LOCALAPPDATA%\utz_build` (Windows) or `$HOME/.cache/utz_build`.
193/// 4. `$OUT_DIR/utz_build-cache` (the build-script last resort), and
194///    otherwise `./utz_build-cache` relative to the current directory.
195///
196/// [`Config::cache_dir()`] overrides the
197/// chain per build. Everything inside is a re-fetchable download (TZBB
198/// zips keyed per release, the ~460 MB GHS-POP raster and its decoded
199/// sidecar), so the directory is safe to delete. Build scripts that
200/// depend on the chain should emit
201/// `cargo:rerun-if-env-changed=UTZ_CACHE_DIR`.
202#[must_use]
203pub fn cache_dir() -> PathBuf {
204    use std::path::Path;
205    if let Some(path) = std::env::var_os("UTZ_CACHE_DIR").filter(|path| !path.is_empty()) {
206        return path.into();
207    }
208    // the XDG spec says to ignore a relative XDG_CACHE_HOME
209    if let Some(path) =
210        std::env::var_os("XDG_CACHE_HOME").filter(|path| Path::new(path).is_absolute())
211    {
212        return Path::new(&path).join("utz_build");
213    }
214    #[cfg(windows)]
215    if let Some(path) = std::env::var_os("LOCALAPPDATA").filter(|path| !path.is_empty()) {
216        return Path::new(&path).join("utz_build");
217    }
218    if let Some(path) = std::env::var_os("HOME").filter(|path| !path.is_empty()) {
219        return Path::new(&path).join(".cache").join("utz_build");
220    }
221    if let Some(path) = std::env::var_os("OUT_DIR").filter(|path| !path.is_empty()) {
222        return Path::new(&path).join("utz_build-cache");
223    }
224    PathBuf::from("utz_build-cache")
225}