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

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

buildings.rs497 lines · 20.7 KiBRaw
1//! `buildings`: the densest layer in the schema, and the simplest to classify.
2//!
3//! Two kinds and almost no judgement — `building=*` is a building unless it says `no`. What makes it
4//! the expensive layer is volume: a city tile holds thousands, and California holds millions. So the
5//! style keeps it off below z14 and the schema does not carry it at all above that floor, which is
6//! the same decision made twice for two different reasons — the style's is a draw-call cost, this
7//! one is archive bytes.
8//!
9//! `building:part` is a separate kind because a 3D model tags the parts of a building separately
10//! from its footprint, and drawing both means drawing the courtyard of a building twice.
11
12use tilecodec::mamaps::body::{
13 BuildingAttrs, ROOF_DOME, ROOF_FLAT, ROOF_GABLED, ROOF_HIPPED, ROOF_ORIENT_ACROSS,
14 ROOF_ORIENT_ALONG, ROOF_PYRAMIDAL, ROOF_SKILLION,
15};
16use tilecodec::mamaps::dict::LAYER_BUILDINGS;
17
18use super::{kind, Class, TagSource};
19
20/// The pre-screen.
21///
22/// A superset of the keys the rules and [`attrs`] read: `building`/`building:part` decide the
23/// classification, and the rest carry the S3DB attributes [`attrs`] parses. Listing the attribute
24/// keys keeps a building's height and roof tags through the `osmium tags-filter` extract step, so
25/// they are still present when [`attrs`] runs — a building that passed the screen on `building`
26/// alone would otherwise arrive stripped of everything the 3D extrusion needs.
27pub const FILTERS: &[&str] = &[
28 "building",
29 "building:part",
30 "height",
31 "building:levels",
32 "building:min_level",
33 "min_height",
34 "roof:shape",
35 "roof:height",
36 "roof:levels",
37 "roof:direction",
38 "roof:orientation",
39 "building:colour",
40 "roof:colour",
41 "building:material",
42 "roof:material",
43];
44
45/// Every `kind` this module can emit.
46#[cfg_attr(not(test), allow(dead_code))]
47pub const KINDS: &[&str] = &["building", "building_part"];
48
49/// The shallowest zoom a building is worth carrying at.
50///
51/// Matches the style's own floor for the `buildings` layer, so the archive holds nothing the
52/// renderer would not draw. The two are independent decisions that happen to agree, and
53/// `the_schema_floor_matches_the_styles` in the crate root is what keeps them agreeing.
54pub const MIN_ZOOM: u8 = 14;
55
56/// The smallest drawn building footprint worth carrying, in square pixels of a 256-unit tile.
57///
58/// `2.0`: a footprint smaller than two display pixels at z14 (Phase C floors — sub-2px
59/// sheds/garages). Converted by [`super::landtype::min_area_units`] to 512 square extent units
60/// at extent 4096 (a ~23x23-unit square, ~13.5 m at z14) — a speck rather than detail, and more
61/// aggressive than the floor the schema applies to the smallest z14 `landtype` kinds (`pitch`,
62/// `playground`, `platform`). Whole-number because [`crate::store`] packs this field as a `u8`
63/// and refuses anything fractional rather than rounding a threshold silently. Carried through
64/// the existing `min_area_px` plumbing so [`crate::tiler`] needs no building branch for the
65/// drop itself.
66///
67/// The prototype at `analysis/mamaps_building_savings.py` estimates dropping the smallest ~15%
68/// of footprints; this floor is at least that aggressive, on the same z14-only layer (9.76M
69/// features, ~20% of the archive).
70pub const MIN_AREA_PX: f64 = 2.0;
71
72pub fn classify(tags: &(impl TagSource + ?Sized)) -> Option<Class> {
73 // A part first: a way carrying both is a part of a larger footprint, and drawing it as a
74 // footprint too would double-paint the courtyard.
75 if tags.truthy("building:part") {
76 return Some(Class {
77 min_area_px: MIN_AREA_PX,
78 ..Class::area(LAYER_BUILDINGS, kind("building_part"), MIN_ZOOM)
79 });
80 }
81 if tags.truthy("building") {
82 return Some(Class {
83 min_area_px: MIN_AREA_PX,
84 ..Class::area(LAYER_BUILDINGS, kind("building"), MIN_ZOOM)
85 });
86 }
87 None
88}
89
90/// Roughly the height of one storey, in metres. OSM's own default for `building:levels` when a
91/// building carries no explicit `height`, and what the S3DB wiki suggests. Rooms are ~2.5 m but a
92/// storey includes floor and ceiling, so 3 m is the conventional figure the renderer expects back.
93const METRES_PER_LEVEL: f64 = 3.0;
94
95/// The S3DB attributes of a building, parsed from its tags — the build half of the 3D extrusion.
96///
97/// Called by [`crate::extract`] on any feature the classifier put in [`LAYER_BUILDINGS`], for both
98/// `building` footprints and `building:part` parts. Every field falls back gracefully: a building
99/// with no S3DB tags at all yields [`BuildingAttrs::default`], which the renderer extrudes as a
100/// flat box at its own default height. Heights are stored in decimetres (0.1 m); directions are
101/// quantised to a byte; colours resolve a CSS/named colour or, failing that, a `*:material`.
102pub fn attrs(tags: &(impl TagSource + ?Sized)) -> BuildingAttrs {
103 // `height` wins over `building:levels`; a building with neither leaves 0 for the renderer's
104 // own default rather than guessing a storey count.
105 let height =
106 metres_dm(tags, "height").or_else(|| levels_dm(tags, "building:levels")).unwrap_or(0);
107 let min_height = metres_dm(tags, "min_height")
108 .or_else(|| levels_dm(tags, "building:min_level"))
109 .unwrap_or(0);
110 let roof_height =
111 metres_dm(tags, "roof:height").or_else(|| levels_dm(tags, "roof:levels")).unwrap_or(0);
112 let building_colour = tags
113 .get("building:colour")
114 .and_then(parse_colour)
115 .or_else(|| tags.get("building:material").and_then(material_colour))
116 .unwrap_or(0);
117 let roof_colour = tags
118 .get("roof:colour")
119 .and_then(parse_colour)
120 .or_else(|| tags.get("roof:material").and_then(material_colour))
121 .unwrap_or(0);
122 BuildingAttrs {
123 height,
124 min_height,
125 roof_height,
126 roof_shape: roof_shape(tags.get("roof:shape")),
127 roof_direction: roof_direction(tags.get("roof:direction")),
128 roof_orientation: match tags.get("roof:orientation") {
129 Some("across") => ROOF_ORIENT_ACROSS,
130 _ => ROOF_ORIENT_ALONG,
131 },
132 building_colour,
133 roof_colour,
134 }
135}
136
137/// A metre value (`12`, `12.5`, `12 m`) as decimetres, clamped to what a `u16` holds (6553.5 m,
138/// past the tallest building on earth). `None` when the tag is absent or not a number.
139fn metres_dm(tags: &(impl TagSource + ?Sized), key: &str) -> Option<u16> {
140 let raw = tags.get(key)?;
141 let metres = parse_leading_f64(raw)?;
142 super::buildings_extra::dm_of(metres)
143}
144
145/// A level count (`building:levels=3`) as a height in decimetres, at [`METRES_PER_LEVEL`] each.
146fn levels_dm(tags: &(impl TagSource + ?Sized), key: &str) -> Option<u16> {
147 let levels = parse_leading_f64(tags.get(key)?)?;
148 super::buildings_extra::dm_of(levels * METRES_PER_LEVEL)
149}
150
151/// The leading number of a value, ignoring a trailing unit like ` m`. OSM height tags are metres
152/// by convention; a stray `ft` is rare enough to accept the bare number rather than convert.
153fn parse_leading_f64(raw: &str) -> Option<f64> {
154 let trimmed = raw.trim();
155 let end = trimmed
156 .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+'))
157 .unwrap_or(trimmed.len());
158 trimmed[..end].parse::<f64>().ok()
159}
160
161/// An OSM `roof:shape` mapped to one of the six the renderer models. Anything else — round,
162/// gambrel, mansard, sawtooth — falls back to flat, which is the plan's stated behaviour: a shape
163/// the extruder cannot build is drawn as a flat cap rather than guessed at.
164fn roof_shape(value: Option<&str>) -> u8 {
165 match value {
166 Some("gabled") => ROOF_GABLED,
167 Some("hipped") => ROOF_HIPPED,
168 Some("pyramidal") => ROOF_PYRAMIDAL,
169 Some("skillion") => ROOF_SKILLION,
170 Some("dome") => ROOF_DOME,
171 _ => ROOF_FLAT,
172 }
173}
174
175/// A `roof:direction` (degrees, or a compass point like `NE`) quantised to a byte: `deg * 256 /
176/// 360`, which the renderer decodes as `v * 360 / 256`. Zero (north) for an absent or unparseable
177/// value, which is the same default a flat roof carries anyway.
178fn roof_direction(value: Option<&str>) -> u8 {
179 let Some(raw) = value else { return 0 };
180 let degrees = compass_degrees(raw.trim()).or_else(|| parse_leading_f64(raw)).unwrap_or(0.0);
181 // Wrap into 0..360 before quantising, so 720 and -90 land where a compass would put them.
182 let wrapped = degrees.rem_euclid(360.0);
183 ((wrapped / 360.0 * 256.0).round() as i64).rem_euclid(256) as u8
184}
185
186/// The eight- and sixteen-point compass abbreviations OSM allows in a direction tag, in degrees.
187fn compass_degrees(raw: &str) -> Option<f64> {
188 let d = match raw.to_ascii_uppercase().as_str() {
189 "N" => 0.0,
190 "NNE" => 22.5,
191 "NE" => 45.0,
192 "ENE" => 67.5,
193 "E" => 90.0,
194 "ESE" => 112.5,
195 "SE" => 135.0,
196 "SSE" => 157.5,
197 "S" => 180.0,
198 "SSW" => 202.5,
199 "SW" => 225.0,
200 "WSW" => 247.5,
201 "W" => 270.0,
202 "WNW" => 292.5,
203 "NW" => 315.0,
204 "NNW" => 337.5,
205 _ => return None,
206 };
207 Some(d)
208}
209
210/// A CSS/OSM colour — `#rgb`, `#rrggbb`, or a common colour name — as opaque `0xAARRGGBB`.
211/// `None` for anything unrecognised, so the caller can fall back to a material.
212fn parse_colour(raw: &str) -> Option<u32> {
213 let s = raw.trim();
214 if let Some(hex) = s.strip_prefix('#') {
215 let rgb = match hex.len() {
216 3 => {
217 let mut v = 0u32;
218 for c in hex.chars() {
219 let n = c.to_digit(16)?;
220 // Each nibble is doubled: #abc is #aabbcc.
221 v = (v << 8) | (n * 17);
222 }
223 v
224 }
225 6 => u32::from_str_radix(hex, 16).ok()?,
226 _ => return None,
227 };
228 return Some(0xFF00_0000 | rgb);
229 }
230 named_colour(&s.to_ascii_lowercase()).map(|rgb| 0xFF00_0000 | rgb)
231}
232
233/// The common CSS/OSM colour names that actually appear on buildings, as `0xRRGGBB`.
234///
235/// Not the full 147-name CSS set: the long tail never appears on a `building:colour`, and a name
236/// this misses falls through to the material palette or to "no colour", both of which are fine.
237fn named_colour(name: &str) -> Option<u32> {
238 let rgb = match name {
239 "white" => 0xFFFFFF,
240 "black" => 0x000000,
241 "gray" | "grey" => 0x808080,
242 "silver" => 0xC0C0C0,
243 "lightgray" | "lightgrey" => 0xD3D3D3,
244 "darkgray" | "darkgrey" => 0xA9A9A9,
245 "red" => 0xFF0000,
246 "darkred" => 0x8B0000,
247 "maroon" => 0x800000,
248 "brown" => 0xA52A2A,
249 "sienna" => 0xA0522D,
250 "orange" => 0xFFA500,
251 "yellow" => 0xFFFF00,
252 "gold" => 0xFFD700,
253 "beige" => 0xF5F5DC,
254 "cream" => 0xFFFDD0,
255 "tan" => 0xD2B48C,
256 "green" => 0x008000,
257 "darkgreen" => 0x006400,
258 "olive" => 0x808000,
259 "lightgreen" => 0x90EE90,
260 "blue" => 0x0000FF,
261 "lightblue" => 0xADD8E6,
262 "navy" => 0x000080,
263 "cyan" => 0x00FFFF,
264 "teal" => 0x008080,
265 "purple" => 0x800080,
266 "pink" => 0xFFC0CB,
267 "terracotta" => 0xE2725B,
268 _ => return None,
269 };
270 Some(rgb)
271}
272
273/// A `building:material` or `roof:material` mapped to a representative colour, as opaque
274/// `0xAARRGGBB`. The palette a renderer falls back to when a building states its material but not
275/// its colour, which is the common case on 3D-mapped cities.
276fn material_colour(material: &str) -> Option<u32> {
277 let rgb = match material.trim().to_ascii_lowercase().as_str() {
278 "brick" | "brick_wall" => 0xB0_4A_39,
279 "concrete" | "cement_block" => 0xB0_B0_B0,
280 "glass" | "mirror" => 0xB8_D0_E0,
281 "wood" | "timber_framing" => 0x9B_6B_43,
282 "stone" | "sandstone" | "limestone" => 0xC8_BE_A8,
283 "marble" => 0xF0_EE_E6,
284 "metal" | "metal_sheet" | "steel" => 0xB4_B8_BC,
285 "copper" => 0x7A_9E_8E,
286 "plaster" | "stucco" | "render" => 0xE8_E0_D0,
287 "roof_tiles" | "tile" | "tiles" | "clay" => 0xB5_6A_4A,
288 "slate" => 0x50_54_5A,
289 "tar_paper" | "asphalt" | "bitumen" => 0x3A_3A_3E,
290 "grass" | "green_roof" => 0x6E_8B_3D,
291 "gravel" => 0x9A_94_88,
292 _ => return None,
293 };
294 Some(0xFF00_0000 | rgb)
295}
296
297#[cfg(test)]
298mod tests {
299 use super::*;
300 use tilecodec::mamaps::dict;
301
302 fn classify_tags(pairs: &[(&str, &str)]) -> Option<Class> {
303 super::classify(pairs)
304 }
305
306 fn kind_name(class: &Class) -> &'static str {
307 dict::KINDS[class.kind as usize - 1]
308 }
309
310 #[test]
311 fn any_building_value_but_no_is_a_building() {
312 // OSM tags a building's *type* in the same key, so the value is not a yes/no in practice:
313 // `building=house`, `building=church`, `building=yes` are all buildings.
314 for value in ["yes", "house", "church", "industrial", "retail", "1", "true"] {
315 let class = classify_tags(&[("building", value)]).expect(value);
316 assert_eq!(class.layer, dict::LAYER_BUILDINGS);
317 assert_eq!(kind_name(&class), "building");
318 assert!(class.area, "a building is an area");
319 assert_eq!(class.min_zoom, MIN_ZOOM);
320 }
321 }
322
323 #[test]
324 fn building_no_is_not_a_building() {
325 // A real tag: `building=no` marks a way that looks like a building and is not.
326 assert!(classify_tags(&[("building", "no")]).is_none());
327 assert!(classify_tags(&[("building", "false")]).is_none());
328 assert!(classify_tags(&[("building", "0")]).is_none());
329 }
330
331 /// A 3D model tags parts separately from the footprint. Both are drawn, so they need different
332 /// kinds — otherwise a building with parts paints its courtyard twice.
333 #[test]
334 fn a_part_is_its_own_kind_and_wins_over_the_footprint() {
335 let part = classify_tags(&[("building:part", "yes")]).expect("part");
336 assert_eq!(kind_name(&part), "building_part");
337 let both = classify_tags(&[("building", "yes"), ("building:part", "yes")]).expect("both");
338 assert_eq!(kind_name(&both), "building_part", "the part rule is asked first");
339 }
340
341 #[test]
342 fn nothing_else_is_a_building() {
343 for tags in [
344 vec![("natural", "water")],
345 vec![("highway", "residential")],
346 vec![("building:levels", "3")],
347 vec![],
348 ] {
349 assert!(classify_tags(&tags).is_none(), "{tags:?} should not be a building");
350 }
351 }
352
353 /// The densest layer in the schema stays off the mid zooms. Without a floor, a z10 tile of a
354 /// city is megabytes of footprints nothing draws.
355 #[test]
356 fn buildings_are_not_carried_below_street_zoom() {
357 assert_eq!(MIN_ZOOM, 14);
358 let class = classify_tags(&[("building", "yes")]).expect("building");
359 assert_eq!(class.min_zoom, 14);
360 }
361
362 /// The densest z14 layer drops what no screen can show: below two display pixels a
363 /// footprint is a speck (a sub-2px shed or garage), not detail. Both kinds carry it — a part
364 /// is still a footprint — and it is a whole number because the store packs this field as a
365 /// `u8` and refuses fractions rather than rounding a threshold silently.
366 #[test]
367 fn buildings_carry_a_two_pixel_minimum_area() {
368 assert_eq!(MIN_AREA_PX, 2.0);
369 for tags in [vec![("building", "yes")], vec![("building:part", "yes")]] {
370 let class = classify_tags(&tags).expect("building");
371 assert_eq!(class.min_area_px, MIN_AREA_PX, "{tags:?}");
372 }
373 // Two display pixels, expressed in a 4096-unit tile: a ~23x23-unit square.
374 assert_eq!(crate::schema::landtype::min_area_units(MIN_AREA_PX, 4096), 512.0);
375 }
376
377 fn attrs_of(pairs: &[(&str, &str)]) -> BuildingAttrs {
378 super::attrs(pairs)
379 }
380
381 #[test]
382 fn a_plain_building_has_default_attrs() {
383 // No S3DB tags at all: a flat box at the renderer's own default height, no colours.
384 let a = attrs_of(&[("building", "yes")]);
385 assert_eq!(a, BuildingAttrs::default());
386 assert_eq!(a.height, 0, "0 means the renderer picks a default");
387 assert_eq!(a.roof_shape, ROOF_FLAT);
388 }
389
390 #[test]
391 fn height_is_metres_in_decimetres_and_levels_are_the_fallback() {
392 // An explicit height wins and carries its fraction, stored as decimetres.
393 assert_eq!(attrs_of(&[("building", "yes"), ("height", "12.5")]).height, 125);
394 // A trailing unit is ignored — the number is metres by convention.
395 assert_eq!(attrs_of(&[("building", "yes"), ("height", "20 m")]).height, 200);
396 // Levels are the fallback at 3 m each, only when there is no explicit height.
397 assert_eq!(attrs_of(&[("building", "yes"), ("building:levels", "4")]).height, 120);
398 let both = attrs_of(&[("building", "yes"), ("height", "9"), ("building:levels", "4")]);
399 assert_eq!(both.height, 90, "an explicit height wins over the level count");
400 }
401
402 #[test]
403 fn min_height_and_roof_height_parse_with_their_level_fallbacks() {
404 let a = attrs_of(&[("building:part", "yes"), ("min_height", "8"), ("roof:height", "3.5")]);
405 assert_eq!(a.min_height, 80);
406 assert_eq!(a.roof_height, 35);
407 let levels = attrs_of(&[
408 ("building:part", "yes"),
409 ("building:min_level", "2"),
410 ("roof:levels", "1"),
411 ]);
412 assert_eq!(levels.min_height, 60, "two levels up at 3 m each");
413 assert_eq!(levels.roof_height, 30);
414 }
415
416 #[test]
417 fn roof_shapes_map_and_unknown_falls_back_to_flat() {
418 for (tag, want) in [
419 ("flat", ROOF_FLAT),
420 ("gabled", ROOF_GABLED),
421 ("hipped", ROOF_HIPPED),
422 ("pyramidal", ROOF_PYRAMIDAL),
423 ("skillion", ROOF_SKILLION),
424 ("dome", ROOF_DOME),
425 // Shapes the extruder does not model fall back to flat rather than guessing.
426 ("gambrel", ROOF_FLAT),
427 ("mansard", ROOF_FLAT),
428 ("round", ROOF_FLAT),
429 ] {
430 assert_eq!(
431 attrs_of(&[("building", "yes"), ("roof:shape", tag)]).roof_shape,
432 want,
433 "roof:shape={tag}",
434 );
435 }
436 }
437
438 #[test]
439 fn roof_direction_takes_degrees_and_compass_points() {
440 // 90° east quantises to a quarter of 256.
441 assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "90")]).roof_direction, 64);
442 assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "E")]).roof_direction, 64);
443 assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "N")]).roof_direction, 0);
444 // A value past 360 wraps like a compass rather than clamping.
445 assert_eq!(attrs_of(&[("building", "yes"), ("roof:direction", "450")]).roof_direction, 64);
446 assert_eq!(
447 attrs_of(&[("building", "yes"), ("roof:orientation", "across")]).roof_orientation,
448 ROOF_ORIENT_ACROSS,
449 );
450 assert_eq!(
451 attrs_of(&[("building", "yes")]).roof_orientation,
452 ROOF_ORIENT_ALONG,
453 "the default orientation is along",
454 );
455 }
456
457 #[test]
458 fn colours_parse_hex_and_names_with_a_material_fallback() {
459 // Hex, short and long, opaque.
460 assert_eq!(
461 attrs_of(&[("building", "yes"), ("building:colour", "#ffcc00")]).building_colour,
462 0xFF_FF_CC_00,
463 );
464 assert_eq!(
465 attrs_of(&[("building", "yes"), ("building:colour", "#fc0")]).building_colour,
466 0xFF_FF_CC_00,
467 "a three-digit hex doubles each nibble",
468 );
469 // A named colour.
470 assert_eq!(
471 attrs_of(&[("building", "yes"), ("roof:colour", "red")]).roof_colour,
472 0xFF_FF_00_00,
473 );
474 // No colour, but a material: the palette fills in.
475 let brick = attrs_of(&[("building", "yes"), ("building:material", "brick")]);
476 assert_ne!(brick.building_colour, 0, "a material resolves to a palette colour");
477 assert_eq!(brick.building_colour >> 24, 0xFF, "and it is opaque");
478 // An explicit colour beats the material.
479 let both = attrs_of(&[
480 ("building", "yes"),
481 ("building:colour", "white"),
482 ("building:material", "brick"),
483 ]);
484 assert_eq!(both.building_colour, 0xFF_FF_FF_FF, "the colour wins over the material");
485 // No colour and no material: absent, so the style default is used.
486 assert_eq!(attrs_of(&[("building", "yes")]).building_colour, 0);
487 }
488
489 #[test]
490 fn a_giant_height_is_clamped_rather_than_wrapping() {
491 // A vandalised height must not wrap a u16 into a short building.
492 let a = attrs_of(&[("building", "yes"), ("height", "999999")]);
493 assert_eq!(a.height, u16::MAX);
494 // A negative height is nonsense and drops to the default rather than a huge unsigned value.
495 assert_eq!(attrs_of(&[("building", "yes"), ("height", "-5")]).height, 0);
496 }
497}