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

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

places.rs277 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.get("name:en")
84 .or_else(|| tags.get("name"))
85 .map(str::trim)
86 .filter(|name| !name.is_empty())
87 .map(str::to_string)
88}
89
90/// A city's zoom from its weight: capitals and million-strong cities at z2–z4, the rest at z5.
91///
92/// Population is the signal when present (`population=*`); `capital=*` promotes one step,
93/// because a capital of 200 k outranks a town of 500 k on every basemap.
94fn city_zoom(tags: &(impl TagSource + ?Sized)) -> u8 {
95 let population = population_of(tags);
96 let capital = tags.get("capital") == Some("yes");
97 let zoom: u8 = if population >= 5_000_000 {
98 2
99 } else if population >= 1_000_000 {
100 3
101 } else if population >= 100_000 {
102 4
103 } else {
104 5
105 };
106 if capital {
107 zoom.saturating_sub(1)
108 } else {
109 zoom
110 }
111}
112
113/// A 0-15 population rank for `kind_detail`: millions at the top, unknown at zero.
114///
115/// The buckets are the reference basemap's `population_rank`, because the authored style
116/// sizes and gates place labels by comparing against it: a locality is drawn large above
117/// rank 13 at z2, above 12 at z6, above 9 at z10. A coarser scale cannot express that.
118/// This was three buckets (5 M, 500 k, any) and the style had to approximate the whole
119/// curve with one ramp and a fixed multiplier, which drew small towns at city size and
120/// let them win collisions against the cities they should have lost to.
121///
122/// Each step is an order-of-magnitude-ish threshold, which is what matters: a city of
123/// 8 M outranks one of 800 k, and both outrank an unpopulated hamlet nobody counted.
124fn rank_of(tags: &(impl TagSource + ?Sized)) -> u16 {
125 const BUCKETS: &[(u64, u16)] = &[
126 (10_000_000, 15),
127 (5_000_000, 14),
128 (1_000_000, 13),
129 (500_000, 12),
130 (200_000, 11),
131 (100_000, 10),
132 (50_000, 9),
133 (20_000, 8),
134 (10_000, 7),
135 (5_000, 6),
136 (2_000, 5),
137 (1_000, 4),
138 (500, 3),
139 (200, 2),
140 (1, 1),
141 ];
142 let population = population_of(tags);
143 BUCKETS
144 .iter()
145 .find(|(floor, _)| population >= *floor)
146 .map(|(_, rank)| *rank)
147 // Zero is "nobody counted", which is not the same as a village of two hundred:
148 // it sorts and sizes below every known population rather than beside the
149 // smallest one.
150 .unwrap_or(0)
151}
152
153/// A `population` tag as a headcount: commas and spaces stripped, unparseable or
154/// absent as zero (nobody counted — Antarctica's case, not an error).
155///
156/// `pub` for pass 1, which reads it off place relations while the tags are in hand
157/// (country label zoom scoring); the spill record never carries tags.
158pub fn population_of(tags: &(impl TagSource + ?Sized)) -> u64 {
159 tags.get("population")
160 .map(str::trim)
161 .and_then(|raw| raw.replace([' ', ','], "").parse::<u64>().ok())
162 .unwrap_or(0)
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168 use tilecodec::mamaps::dict;
169
170 fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {
171 super::classify(pairs)
172 }
173
174 #[test]
175 fn a_country_is_labelled_from_world_zoom() {
176 let class = classify_tags(&[("place", "country"), ("name", "France")]).expect("country");
177 assert_eq!(class.layer, dict::LAYER_PLACES);
178 assert_eq!(dict::KINDS[class.kind as usize - 1], "country");
179 assert_eq!(class.min_zoom, 0, "a country label carries a world tile");
180 assert!(!class.area, "a label is a point even for an area-mapped place");
181 }
182
183 #[test]
184 fn a_city_zoom_follows_its_weight() {
185 let at = |tags: &[(&str, &str)]| classify_tags(tags).expect("city").min_zoom;
186 assert_eq!(at(&[("place", "city"), ("population", "8000000")]), 2, "a megacity");
187 assert_eq!(at(&[("place", "city"), ("population", "2000000")]), 3);
188 assert_eq!(at(&[("place", "city")]), 5, "an uncounted city");
189 assert_eq!(at(&[("place", "city"), ("capital", "yes")]), 4, "a capital promotes one step");
190 assert_eq!(
191 at(&[("place", "city"), ("population", "8000000"), ("capital", "yes")]),
192 1,
193 "but never past z1 for a city",
194 );
195 }
196
197 #[test]
198 fn towns_villages_and_suburbs_layer_by_size() {
199 assert_eq!(classify_tags(&[("place", "town")]).expect("town").min_zoom, 6);
200 assert_eq!(classify_tags(&[("place", "village")]).expect("village").min_zoom, 9);
201 let suburb = classify_tags(&[("place", "suburb")]).expect("suburb");
202 assert_eq!(dict::KINDS[suburb.kind as usize - 1], "neighbourhood");
203 assert_eq!(suburb.min_zoom, 10);
204 }
205
206 #[test]
207 fn the_name_prefers_english_and_falls_back() {
208 let name_of = |pairs: &[(&str, &str)]| display_name(pairs);
209 assert_eq!(
210 name_of(&[("name:en", "Munich"), ("name", "München")]),
211 Some("Munich".to_string()),
212 );
213 assert_eq!(name_of(&[("name", "München")]), Some("München".to_string()));
214 assert_eq!(name_of(&[("place", "city")]), None, "unnamed");
215 assert_eq!(name_of(&[("name", " ")]), None, "blank");
216 }
217
218 #[test]
219 fn only_named_kinds_of_place_count() {
220 for tags in [
221 vec![("place", "island")],
222 vec![("place", "islet")],
223 vec![("place", "sea")],
224 vec![("amenity", "cafe")],
225 vec![],
226 ] {
227 assert!(classify_tags(&tags).is_none(), "{tags:?} should not be a place label");
228 }
229 // Islands are `earth`, not `places`: the island label comes from the earth kind.
230 assert!(classify_tags(&[("place", "islet")]).is_none());
231 }
232
233 #[test]
234 fn the_rank_is_numeric_and_sorts_by_weight() {
235 let rank = |tags: &[(&str, &str)]| classify_tags(tags).expect("place").kind_detail;
236 assert!(
237 rank(&[("place", "city"), ("population", "8000000")])
238 > rank(&[("place", "city"), ("population", "100000")])
239 );
240 assert_eq!(rank(&[("place", "city")]), 0, "unknown sorts last");
241 let class = classify_tags(&[("place", "city"), ("population", "8000000")]).expect("city");
242 // Numeric, like boundaries' admin level: the renderer compares, not matches.
243 assert_eq!(class.flags, FLAG_DETAIL_NUMERIC);
244 assert_eq!(class.kind_detail, 14, "8 M lands in the 5 M bucket");
245 }
246
247 /// The style compares this against thresholds of 8, 9, 11, 12 and 13, so those
248 /// boundaries have to fall where the reference basemap puts them or a locality is
249 /// sized and gated against the wrong arm.
250 #[test]
251 fn the_rank_matches_the_reference_population_buckets() {
252 let rank = |population: &str| {
253 classify_tags(&[("place", "city"), ("population", population)])
254 .expect("place")
255 .kind_detail
256 };
257 for (population, want) in [
258 ("12000000", 15),
259 ("6000000", 14),
260 ("1200000", 13),
261 ("600000", 12),
262 ("250000", 11),
263 ("120000", 10),
264 ("60000", 9),
265 ("25000", 8),
266 ("12000", 7),
267 ("1", 1),
268 ] {
269 assert_eq!(rank(population), want, "population {population}");
270 }
271 // The thresholds are inclusive floors, which is what the `>=` comparisons expect.
272 assert_eq!(rank("1000000"), 13);
273 assert_eq!(rank("999999"), 12);
274 assert_eq!(rank("50000"), 9);
275 assert_eq!(rank("49999"), 8);
276 }
277}