Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / scripts / maps / mamaps_build / src / schema / places.rs

places.rs273 lines · 11.4 KiBRaw
1//! `places`: labels — the one layer that is points with names.
2//!
3//! A place is a node (or exceptionally a way/relation centroid) tagged `place=*`, carrying a
4//! coalesced display name (`name:en` preferred, falling back to `name`, as the reference style
5//! does with its `coalesce(get(name:en), get(name), ...)` text fields) and a `kind` mirroring
6//! the reference style's `places` filters: `country`, `region` (a named state/province),
7//! `locality` (a city or town) and `neighbourhood`/`macrohood` (a subplace).
8//!
9//! # Why points
10//!
11//! Upstream's `places` is points: a label is anchored at one coordinate, not drawn from an area.
12//! The tiler therefore emits one point feature per place, and the body's [`GEOM_POINT`] carries
13//! it. A place mapped as a way or relation is labelled at its centroid (computed in extract),
14//! which is what MapLibre does with area labels.
15//!
16//! [`GEOM_POINT`]: tilecodec::mamaps::body::GEOM_POINT
17//!
18//! # Rank and zoom
19//!
20//! The style draws a place when `zoom >= min_zoom`, where the important places surface early: a
21//! country at z0, a region at z3, a city by population, a suburb late. `min_zoom` here mirrors
22//! that: capitals and millions-strong cities at z2–z4, towns at z6–z8, suburbs at z10+. The
23//! numeric `kind_detail` carries the population rank the style's symbol-sort uses, so a later
24//! renderer can order labels without re-reading OSM.
25//!
26//! Country labels are deliberately NOT gated by area here: `classify` sees tags only, and a
27//! country's ground area is known only after its boundary relation is stitched (see
28//! `extract_fallback::Boundary::area`). Per-country zoom gating by size would ride a
29//! place-id → min_zoom side map (same shape as `region_links`) computed from those areas
30//! and consulted at tile-chunk time — not a change to this function.
31
32use tilecodec::mamaps::body::FLAG_DETAIL_NUMERIC;
33use tilecodec::mamaps::dict::LAYER_PLACES;
34
35use super::{kind, Class, TagSource};
36
37pub const FILTERS: &[&str] = &["place", "name", "name:en", "population", "capital"];
38
39/// Every `kind` this module can emit, mirroring the reference style's `places` filters.
40#[cfg_attr(not(test), allow(dead_code))]
41pub const KINDS: &[&str] = &["country", "region", "locality", "neighbourhood", "macrohood"];
42
43/// A country's label carries the world tile, like its border.
44const Z_COUNTRY: u8 = 0;
45/// A named state/province surfaces with the region borders.
46const Z_REGION: u8 = 3;
47
48/// Classify a `place=*` element. `name` is coalesced `name:en` → `name` by the caller (extract),
49/// because the spill carries one string per feature; this function decides kind and zoom.
50pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {
51 let place = tags.get("place")?;
52 let (kind_name, min_zoom) = match place {
53 "country" => ("country", Z_COUNTRY),
54 "state" | "province" => ("region", Z_REGION),
55 "city" => ("locality", city_zoom(tags)),
56 "town" => ("locality", 6),
57 "village" | "hamlet" => ("locality", 9),
58 "suburb" | "borough" => ("neighbourhood", 10),
59 "neighbourhood" | "quarter" => ("neighbourhood", 11),
60 // A macrohood is an upstream grouping above neighbourhoods; rare in OSM, drawn late.
61 "macrohood" => ("macrohood", 10),
62 _ => return None,
63 };
64 Some(Class {
65 layer: LAYER_PLACES,
66 kind: kind(kind_name),
67 // The population rank the style sorts by, when known. Zero (unknown) sorts last;
68 // carrying it numerically is what lets a later renderer order labels.
69 kind_detail: rank_of(tags),
70 flags: FLAG_DETAIL_NUMERIC,
71 // A label is a point even when the place was mapped as an area: extract centroids it.
72 area: false,
73 min_zoom,
74 min_area_px: 0.0,
75 })
76}
77
78/// The display name for a place: `name:en` preferred, `name` as fallback.
79///
80/// Mirrors the reference style's `coalesce(get(name:en), get(name), ...)`. The `pgf:name`
81/// fallback is upstream's own preprocessing and has no OSM source, so it is not read here.
82pub fn display_name(tags: &(impl TagSource + ?Sized)) -> Option<String> {
83 tags
84 .get("name:en")
85 .or_else(|| tags.get("name"))
86 .map(str::trim)
87 .filter(|name| !name.is_empty())
88 .map(str::to_string)
89}
90
91/// A city's zoom from its weight: capitals and million-strong cities at z2–z4, the rest at z5.
92///
93/// Population is the signal when present (`population=*`); `capital=*` promotes one step,
94/// because a capital of 200 k outranks a town of 500 k on every basemap.
95fn city_zoom(tags: &(impl TagSource + ?Sized)) -> u8 {
96 let population = population_of(tags);
97 let capital = tags.get("capital") == Some("yes");
98 let zoom: u8 = if population >= 5_000_000 {
99 2
100 } else if population >= 1_000_000 {
101 3
102 } else if population >= 100_000 {
103 4
104 } else {
105 5
106 };
107 if capital { zoom.saturating_sub(1) } else { zoom }
108}
109
110/// A 0-15 population rank for `kind_detail`: millions at the top, unknown at zero.
111///
112/// The buckets are the reference basemap's `population_rank`, because the authored style
113/// sizes and gates place labels by comparing against it: a locality is drawn large above
114/// rank 13 at z2, above 12 at z6, above 9 at z10. A coarser scale cannot express that.
115/// This was three buckets (5 M, 500 k, any) and the style had to approximate the whole
116/// curve with one ramp and a fixed multiplier, which drew small towns at city size and
117/// let them win collisions against the cities they should have lost to.
118///
119/// Each step is an order-of-magnitude-ish threshold, which is what matters: a city of
120/// 8 M outranks one of 800 k, and both outrank an unpopulated hamlet nobody counted.
121fn rank_of(tags: &(impl TagSource + ?Sized)) -> u16 {
122 const BUCKETS: &[(u64, u16)] = &[
123 (10_000_000, 15),
124 (5_000_000, 14),
125 (1_000_000, 13),
126 (500_000, 12),
127 (200_000, 11),
128 (100_000, 10),
129 (50_000, 9),
130 (20_000, 8),
131 (10_000, 7),
132 (5_000, 6),
133 (2_000, 5),
134 (1_000, 4),
135 (500, 3),
136 (200, 2),
137 (1, 1),
138 ];
139 let population = population_of(tags);
140 BUCKETS
141 .iter()
142 .find(|(floor, _)| population >= *floor)
143 .map(|(_, rank)| *rank)
144 // Zero is "nobody counted", which is not the same as a village of two hundred:
145 // it sorts and sizes below every known population rather than beside the
146 // smallest one.
147 .unwrap_or(0)
148}
149
150/// A `population` tag as a headcount: commas and spaces stripped, unparseable or
151/// absent as zero (nobody counted — Antarctica's case, not an error).
152///
153/// `pub` for pass 1, which reads it off place relations while the tags are in hand
154/// (country label zoom scoring); the spill record never carries tags.
155pub fn population_of(tags: &(impl TagSource + ?Sized)) -> u64 {
156 tags
157 .get("population")
158 .map(str::trim)
159 .and_then(|raw| raw.replace([' ', ','], "").parse::<u64>().ok())
160 .unwrap_or(0)
161}
162
163#[cfg(test)]
164mod tests {
165 use super::*;
166 use tilecodec::mamaps::dict;
167
168 fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {
169 super::classify(pairs)
170 }
171
172 #[test]
173 fn a_country_is_labelled_from_world_zoom() {
174 let class = classify_tags(&[("place", "country"), ("name", "France")]).expect("country");
175 assert_eq!(class.layer, dict::LAYER_PLACES);
176 assert_eq!(dict::KINDS[class.kind as usize - 1], "country");
177 assert_eq!(class.min_zoom, 0, "a country label carries a world tile");
178 assert!(!class.area, "a label is a point even for an area-mapped place");
179 }
180
181 #[test]
182 fn a_city_zoom_follows_its_weight() {
183 let at = |tags: &[(&str, &str)]| classify_tags(tags).expect("city").min_zoom;
184 assert_eq!(at(&[("place", "city"), ("population", "8000000")]), 2, "a megacity");
185 assert_eq!(at(&[("place", "city"), ("population", "2000000")]), 3);
186 assert_eq!(at(&[("place", "city")]), 5, "an uncounted city");
187 assert_eq!(at(&[("place", "city"), ("capital", "yes")]), 4, "a capital promotes one step");
188 assert_eq!(
189 at(&[("place", "city"), ("population", "8000000"), ("capital", "yes")]),
190 1,
191 "but never past z1 for a city",
192 );
193 }
194
195 #[test]
196 fn towns_villages_and_suburbs_layer_by_size() {
197 assert_eq!(classify_tags(&[("place", "town")]).expect("town").min_zoom, 6);
198 assert_eq!(classify_tags(&[("place", "village")]).expect("village").min_zoom, 9);
199 let suburb = classify_tags(&[("place", "suburb")]).expect("suburb");
200 assert_eq!(dict::KINDS[suburb.kind as usize - 1], "neighbourhood");
201 assert_eq!(suburb.min_zoom, 10);
202 }
203
204 #[test]
205 fn the_name_prefers_english_and_falls_back() {
206 let name_of = |pairs: &[(&str, &str)]| display_name(pairs);
207 assert_eq!(
208 name_of(&[("name:en", "Munich"), ("name", "München")]),
209 Some("Munich".to_string()),
210 );
211 assert_eq!(name_of(&[("name", "München")]), Some("München".to_string()));
212 assert_eq!(name_of(&[("place", "city")]), None, "unnamed");
213 assert_eq!(name_of(&[("name", " ")]), None, "blank");
214 }
215
216 #[test]
217 fn only_named_kinds_of_place_count() {
218 for tags in [
219 vec![("place", "island")],
220 vec![("place", "islet")],
221 vec![("place", "sea")],
222 vec![("amenity", "cafe")],
223 vec![],
224 ] {
225 assert!(classify_tags(&tags).is_none(), "{tags:?} should not be a place label");
226 }
227 // Islands are `earth`, not `places`: the island label comes from the earth kind.
228 assert!(classify_tags(&[("place", "islet")]).is_none());
229 }
230
231 #[test]
232 fn the_rank_is_numeric_and_sorts_by_weight() {
233 let rank = |tags: &[(&str, &str)]| classify_tags(tags).expect("place").kind_detail;
234 assert!(rank(&[("place", "city"), ("population", "8000000")])
235 > rank(&[("place", "city"), ("population", "100000")]));
236 assert_eq!(rank(&[("place", "city")]), 0, "unknown sorts last");
237 let class = classify_tags(&[("place", "city"), ("population", "8000000")]).expect("city");
238 // Numeric, like boundaries' admin level: the renderer compares, not matches.
239 assert_eq!(class.flags, FLAG_DETAIL_NUMERIC);
240 assert_eq!(class.kind_detail, 14, "8 M lands in the 5 M bucket");
241 }
242
243 /// The style compares this against thresholds of 8, 9, 11, 12 and 13, so those
244 /// boundaries have to fall where the reference basemap puts them or a locality is
245 /// sized and gated against the wrong arm.
246 #[test]
247 fn the_rank_matches_the_reference_population_buckets() {
248 let rank = |population: &str| {
249 classify_tags(&[("place", "city"), ("population", population)])
250 .expect("place")
251 .kind_detail
252 };
253 for (population, want) in [
254 ("12000000", 15),
255 ("6000000", 14),
256 ("1200000", 13),
257 ("600000", 12),
258 ("250000", 11),
259 ("120000", 10),
260 ("60000", 9),
261 ("25000", 8),
262 ("12000", 7),
263 ("1", 1),
264 ] {
265 assert_eq!(rank(population), want, "population {population}");
266 }
267 // The thresholds are inclusive floors, which is what the `>=` comparisons expect.
268 assert_eq!(rank("1000000"), 13);
269 assert_eq!(rank("999999"), 12);
270 assert_eq!(rank("50000"), 9);
271 assert_eq!(rank("49999"), 8);
272 }
273}