Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / map / src / main / rust / src / tile / placement.rs
placement.rs401 lines · 16.5 KiBRaw
| 1 | //! Screen-space label placement: greedy, rank-ordered, per-frame. |
| 2 | //! |
| 3 | //! M1 places _point_ labels only (country/region/locality/subplace). Each tile |
| 4 | //! shapes its candidates once ([`crate::tile::symbol`]); this module decides, per |
| 5 | //! frame, which candidates draw: sort by rank (country first), greedily accept |
| 6 | //! while the screen box collides with nothing accepted yet. |
| 7 | //! |
| 8 | //! # Coordinates |
| 9 | //! |
| 10 | //! Collision runs in _screen px_: the caller passes each candidate's screen box |
| 11 | //! (computed from the anchor's clip position + the frame's text size). This keeps |
| 12 | //! the module free of camera math and testable with literal boxes. |
| 13 | //! |
| 14 | //! Projection is pitch-aware ([`project_to_screen`]): at pitch 0 it is the linear |
| 15 | //! map, and under tilt it carries the perspective divide the billboard shader |
| 16 | //! applies — so a box sits where its label draws, and distant POIs compress onto |
| 17 | //! overlapping boxes the rank-ordered placer thins by importance. |
| 18 | //! |
| 19 | //! # Rank |
| 20 | //! |
| 21 | //! Lower is more important: country (0) > region (1) > locality (2) > subplace |
| 22 | //! (3) > POI (4), 255 for an id the renderer did not recognise (sinks last). Ties break |
| 23 | //! by population weight (higher first — a big city beats a town), then by |
| 24 | //! larger box (more informative), then by id order — deterministic, so frames |
| 25 | //! don't shimmer. |
| 26 | //! |
| 27 | //! # Variable anchors |
| 28 | //! |
| 29 | //! A POI label may be drawn to the left or the right of its icon |
| 30 | //! (`text-variable-anchor: ["left", "right"]`), so a candidate carries two boxes and |
| 31 | //! [`place`] reports which one it accepted. The renderer then emits at that anchor, which |
| 32 | //! is what makes a label near the edge of a crowd flip to its other side instead of |
| 33 | //! disappearing. |
| 34 | |
| 35 | use crate::style::Anchor; |
| 36 | |
| 37 | /// A label candidate's screen box plus its rank. |
| 38 | pub struct Candidate { |
| 39 | /// Stable id for the accept-set. |
| 40 | pub id: u64, |
| 41 | /// Rank: 0 country … 4 POI, 255 unknown (sorts last). |
| 42 | pub rank: u8, |
| 43 | /// Population weight within the rank, higher first. |
| 44 | pub pop: u16, |
| 45 | /// Screen box in device px, with collision padding baked in. |
| 46 | pub rect: (f32, f32, f32, f32), |
| 47 | /// The box to try when [`rect`](Self::rect) collides — the label drawn at its second |
| 48 | /// variable anchor. `None` for a label that cannot move, which is every place label. |
| 49 | pub alternate: Option<(f32, f32, f32, f32)>, |
| 50 | } |
| 51 | |
| 52 | /// An accepted candidate: its id, and whether it took its |
| 53 | /// [`alternate`](Candidate::alternate) box. |
| 54 | pub type Placed = (u64, bool); |
| 55 | |
| 56 | /// Minimum population rank for a locality to draw at a camera zoom. |
| 57 | /// |
| 58 | /// Country/region always draw (few, important); subplace is layer-gated. Rank gating |
| 59 | /// happens before collision because collision alone cannot thin hundreds of towns down |
| 60 | /// to the major-city set - the small ones simply arrive first in some tiles. |
| 61 | /// |
| 62 | /// The ranks are the reference basemap's `population_rank` (see the tiler's |
| 63 | /// `schema::places::rank_of`): 12 is 500k, 1 is any counted population at all. So z6 and |
| 64 | /// below hold the half-million-plus cities, z7..z9 add anywhere with a population, and |
| 65 | /// z10 draws everything the tile shaped. |
| 66 | pub fn locality_min_pop(zoom: f64) -> u16 { |
| 67 | if zoom < 7.0 { |
| 68 | 12 |
| 69 | } else if zoom < 10.0 { |
| 70 | 1 |
| 71 | } else { |
| 72 | 0 |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// Greedily place candidates: rank order, first-come keeps its box. |
| 77 | /// Rank 0 (country) always draws: it never collides, so capitals and country |
| 78 | /// names survive any crowd. All other ranks collide normally. |
| 79 | /// |
| 80 | /// A candidate whose primary box collides gets one more try at its |
| 81 | /// [`alternate`](Candidate::alternate), and is reported as having taken it. That is |
| 82 | /// MapLibre's variable-anchor behaviour reduced to the two anchors the reference |
| 83 | /// declares. |
| 84 | /// |
| 85 | /// Returns the accepted candidates in acceptance order. |
| 86 | pub fn place(candidates: &[Candidate]) -> Vec<Placed> { |
| 87 | let mut ordered: Vec<&Candidate> = candidates.iter().collect(); |
| 88 | ordered.sort_by(|a, b| { |
| 89 | a.rank |
| 90 | .cmp(&b.rank) |
| 91 | .then_with(|| b.pop.cmp(&a.pop)) |
| 92 | .then_with(|| { |
| 93 | let (aw, ah) = (a.rect.2 - a.rect.0, a.rect.3 - a.rect.1); |
| 94 | let (bw, bh) = (b.rect.2 - b.rect.0, b.rect.3 - b.rect.1); |
| 95 | (bw * bh) |
| 96 | .partial_cmp(&(aw * ah)) |
| 97 | .unwrap_or(std::cmp::Ordering::Equal) |
| 98 | }) |
| 99 | .then_with(|| a.id.cmp(&b.id)) |
| 100 | }); |
| 101 | let mut accepted: Vec<(f32, f32, f32, f32)> = Vec::new(); |
| 102 | let mut out = Vec::new(); |
| 103 | for c in ordered { |
| 104 | // Rank 0 never collides: country labels are few and must always draw. |
| 105 | let free = |rect: (f32, f32, f32, f32), accepted: &[(f32, f32, f32, f32)]| { |
| 106 | c.rank == 0 || !accepted.iter().any(|a| overlaps(*a, rect)) |
| 107 | }; |
| 108 | let taken = if free(c.rect, &accepted) { |
| 109 | (c.rect, false) |
| 110 | } else if let Some(alternate) = c.alternate.filter(|a| free(*a, &accepted)) { |
| 111 | (alternate, true) |
| 112 | } else { |
| 113 | continue; |
| 114 | }; |
| 115 | accepted.push(taken.0); |
| 116 | out.push((c.id, taken.1)); |
| 117 | } |
| 118 | out |
| 119 | } |
| 120 | |
| 121 | fn overlaps(a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)) -> bool { |
| 122 | a.0 < b.2 && b.0 < a.2 && a.1 < b.3 && b.1 < a.3 |
| 123 | } |
| 124 | |
| 125 | /// Stable id for one label of one tile in one frame, so the accept-set the |
| 126 | /// renderer computes in its pre-pass names the same labels `record_symbol` |
| 127 | /// later filters by. |
| 128 | /// |
| 129 | /// A cheap deterministic integer mix over (tile z/x/y, layer index, position in |
| 130 | /// the tile's shaped label list) — the label list is shaped once in feature |
| 131 | /// order, so the inputs are frame-stable and collisions across tiles are |
| 132 | /// impossible in practice. Pure integer arithmetic, so ids are stable across |
| 133 | /// frames and runs (no hasher keys, no per-process randomness). |
| 134 | pub fn candidate_id(z: u8, x: u32, y: u32, layer_index: usize, label_idx: usize) -> u64 { |
| 135 | // FxHash-style multiply mix + splitmix64 final avalanche. |
| 136 | const K: u64 = 0xbf58476d1ce4e5b9; |
| 137 | let mut h: u64 = 0x9e3779b97f4a7c15; |
| 138 | h ^= z as u64; |
| 139 | h = h.wrapping_mul(K); |
| 140 | h ^= x as u64; |
| 141 | h = h.wrapping_mul(K); |
| 142 | h ^= y as u64; |
| 143 | h = h.wrapping_mul(K); |
| 144 | h ^= layer_index as u64; |
| 145 | h = h.wrapping_mul(K); |
| 146 | h ^= label_idx as u64; |
| 147 | h = h.wrapping_mul(K); |
| 148 | // Final avalanche so neighbouring inputs land far apart. |
| 149 | h ^= h >> 30; |
| 150 | h = h.wrapping_mul(K); |
| 151 | h ^= h >> 27; |
| 152 | h = h.wrapping_mul(0x94d049bb133111eb); |
| 153 | h ^= h >> 31; |
| 154 | h |
| 155 | } |
| 156 | |
| 157 | /// One label's screen collision box in device px, from the same inputs the |
| 158 | /// tessellator uses — so the box the placer sees is the box the GPU draws, |
| 159 | /// plus MapLibre-style padding. |
| 160 | /// |
| 161 | /// `anchor` is tile-local 0..1, `tile_clip` the camera's column-major matrix |
| 162 | /// for the tile, `extent_wh` the viewport in device px. Width is the label's |
| 163 | /// advance at the frame's `text_px` (`total_advance` is in font units over |
| 164 | /// [`UP_EM`](crate::tile::glyph::UP_EM)); height is one `text_px`, centred on |
| 165 | /// the anchor like the emitted em box. `pad_px` inflates the box on every |
| 166 | /// side, standing in for the icon + text padding MapLibre applies around |
| 167 | /// every label: without it tight advance boxes let hundreds of villages |
| 168 | /// survive at z6 where MapLibre shows ~10 cities. |
| 169 | pub fn screen_rect( |
| 170 | anchor: (f32, f32), |
| 171 | tile_clip: [f32; 16], |
| 172 | extent_wh: (u32, u32), |
| 173 | text_px: f32, |
| 174 | total_advance: f32, |
| 175 | pad_px: f32, |
| 176 | ) -> Option<(f32, f32, f32, f32)> { |
| 177 | anchored_rect( |
| 178 | anchor, |
| 179 | tile_clip, |
| 180 | extent_wh, |
| 181 | &BoxInputs { |
| 182 | text_px, |
| 183 | advance: total_advance, |
| 184 | line_count: 1, |
| 185 | offset_em: (0.0, 0.0), |
| 186 | icon_px: None, |
| 187 | pad_px, |
| 188 | }, |
| 189 | Anchor::Center, |
| 190 | ) |
| 191 | } |
| 192 | |
| 193 | /// Everything a label's collision box depends on besides where it is anchored. |
| 194 | /// |
| 195 | /// A struct rather than eight parameters because the renderer builds one of these per |
| 196 | /// label and then asks for a box at each candidate anchor — the inputs are shared and only |
| 197 | /// the anchor varies. |
| 198 | pub struct BoxInputs { |
| 199 | /// The frame's text size in device px. |
| 200 | pub text_px: f32, |
| 201 | /// The widest line's advance, in font units. |
| 202 | pub advance: f32, |
| 203 | /// How many lines the label wrapped to, at least 1. |
| 204 | pub line_count: usize, |
| 205 | /// `text-offset` in ems. |
| 206 | pub offset_em: (f32, f32), |
| 207 | /// The icon's drawn size in device px, when the label has one. |
| 208 | pub icon_px: Option<(f32, f32)>, |
| 209 | /// Collision padding added on every side. |
| 210 | pub pad_px: f32, |
| 211 | } |
| 212 | |
| 213 | /// Project a tile-local 0..1 point to screen px through the tile's clip matrix, **with** |
| 214 | /// the perspective divide — the one derivation collision shares with the GPU billboard path. |
| 215 | /// |
| 216 | /// [`anchored_rect`] and [`curved_boxes`] used to apply only the matrix's linear part, which |
| 217 | /// is the whole transform at pitch 0 (`w == 1`) but drops the foreshortening under tilt: boxes |
| 218 | /// were built around a pre-divide position while `symbol_billboard.vert` draws each anchor |
| 219 | /// post-divide, so collision tested boxes that sat nowhere near the drawn labels. A tilted view |
| 220 | /// additionally compresses distant ground toward the horizon, which is exactly the declutter |
| 221 | /// case — with the divide, far POIs land close together on screen, their screen-constant boxes |
| 222 | /// overlap, and the rank-ordered placer culls them, so declutter follows the projected density |
| 223 | /// rather than the zoom alone. |
| 224 | /// |
| 225 | /// Returns `None` when the point is on or behind the eye (`w <= 0`): there is no screen position |
| 226 | /// to collide at, so the label cannot be a candidate. Callers skip the label (point path) or the |
| 227 | /// glyph (curved path) — a box for an unprojectable label is unrepresentable rather than garbage. |
| 228 | /// The `!(w > 0.0)` form also catches NaN, which would otherwise build a box that collides with |
| 229 | /// nothing and always draws. |
| 230 | pub fn project_to_screen( |
| 231 | tile_clip: [f32; 16], |
| 232 | point: (f32, f32), |
| 233 | extent_wh: (u32, u32), |
| 234 | ) -> Option<(f32, f32)> { |
| 235 | let cx = tile_clip[0] * point.0 + tile_clip[4] * point.1 + tile_clip[12]; |
| 236 | let cy = tile_clip[1] * point.0 + tile_clip[5] * point.1 + tile_clip[13]; |
| 237 | let w = tile_clip[3] * point.0 + tile_clip[7] * point.1 + tile_clip[15]; |
| 238 | if !(w > 0.0) { |
| 239 | return None; |
| 240 | } |
| 241 | Some(( |
| 242 | (cx / w * 0.5 + 0.5) * extent_wh.0 as f32, |
| 243 | (cy / w * 0.5 + 0.5) * extent_wh.1 as f32, |
| 244 | )) |
| 245 | } |
| 246 | |
| 247 | /// The screen box a label would occupy if drawn at `anchor`. |
| 248 | /// |
| 249 | /// The union of the text block and the icon, which is where this departs from MapLibre: |
| 250 | /// it keeps two linked boxes and tests both. The two are equivalent while `icon-optional` |
| 251 | /// and `text-optional` are both false — as they are here, since neither is set — because |
| 252 | /// then a collision on either box rejects the pair anyway. A union is looser only in the |
| 253 | /// gap the `text-offset` opens between icon and text, which is 1.1 em of empty space that |
| 254 | /// nothing would have been placed in. |
| 255 | /// |
| 256 | /// The box is centred on [`project_to_screen`]'s pitch-aware projection of `point`, so under |
| 257 | /// tilt it sits where the billboarded label draws; its width and height are screen-constant |
| 258 | /// (text advance at `text_px`, icon size in device px), matching the screen-constant size the |
| 259 | /// billboard path draws at. Returns `None` when the anchor is on or behind the eye — such a |
| 260 | /// label cannot be a candidate, so no box exists for it. |
| 261 | pub fn anchored_rect( |
| 262 | point: (f32, f32), |
| 263 | tile_clip: [f32; 16], |
| 264 | extent_wh: (u32, u32), |
| 265 | inputs: &BoxInputs, |
| 266 | anchor: Anchor, |
| 267 | ) -> Option<(f32, f32, f32, f32)> { |
| 268 | let (sx, sy) = project_to_screen(tile_clip, point, extent_wh)?; |
| 269 | |
| 270 | let w = inputs.text_px * inputs.advance / crate::tile::glyph::UP_EM as f32; |
| 271 | // Lines stack at 1.2 em, so a two-line block is 2.2 em tall, not 2.4: the first line |
| 272 | // contributes its own height and each further one a line's worth of leading. |
| 273 | let lines = inputs.line_count.max(1) as f32; |
| 274 | let h = inputs.text_px * (1.0 + (lines - 1.0) * crate::tess::text::LINE_HEIGHT_EM); |
| 275 | // The same placement `tess::text::emit` uses: the offset's magnitude, its direction |
| 276 | // taken from the anchor, and no vertical component on a horizontal anchor. |
| 277 | let offset = inputs.offset_em.0.abs() * inputs.text_px; |
| 278 | let (mut x0, mut x1) = match anchor { |
| 279 | Anchor::Center => (sx - w * 0.5, sx + w * 0.5), |
| 280 | Anchor::Left => (sx + offset, sx + offset + w), |
| 281 | Anchor::Right => (sx - offset - w, sx - offset), |
| 282 | }; |
| 283 | let (mut y0, mut y1) = (sy - h * 0.5, sy + h * 0.5); |
| 284 | if let Some((icon_w, icon_h)) = inputs.icon_px { |
| 285 | x0 = x0.min(sx - icon_w * 0.5); |
| 286 | x1 = x1.max(sx + icon_w * 0.5); |
| 287 | y0 = y0.min(sy - icon_h * 0.5); |
| 288 | y1 = y1.max(sy + icon_h * 0.5); |
| 289 | } |
| 290 | Some(( |
| 291 | x0 - inputs.pad_px, |
| 292 | y0 - inputs.pad_px, |
| 293 | x1 + inputs.pad_px, |
| 294 | y1 + inputs.pad_px, |
| 295 | )) |
| 296 | } |
| 297 | |
| 298 | // --- oriented / segmented collision (curved labels) ------------------------- |
| 299 | |
| 300 | /// An oriented bounding box in screen px: a centre, half-extents along its own axes, and the |
| 301 | /// unit orientation `(cos, sin)` of its local x-axis. |
| 302 | /// |
| 303 | /// A point label's box is one of these with `sin == 0` (axis-aligned), so a single collision |
| 304 | /// primitive serves both the straight point labels and the per-glyph boxes of a curved one — a |
| 305 | /// curved street name is a *row* of these, each rotated to its glyph's tangent, which is what |
| 306 | /// lets it collide tightly instead of as one loose AABB across the whole bend. |
| 307 | #[derive(Clone, Copy, Debug)] |
| 308 | pub struct Obb { |
| 309 | pub cx: f32, |
| 310 | pub cy: f32, |
| 311 | pub hx: f32, |
| 312 | pub hy: f32, |
| 313 | pub cos: f32, |
| 314 | pub sin: f32, |
| 315 | } |
| 316 | |
| 317 | impl Obb { |
| 318 | /// An axis-aligned box from a screen rect — how a point label enters the segmented placer. |
| 319 | pub fn from_rect(rect: (f32, f32, f32, f32)) -> Obb { |
| 320 | Obb { |
| 321 | cx: (rect.0 + rect.2) * 0.5, |
| 322 | cy: (rect.1 + rect.3) * 0.5, |
| 323 | hx: (rect.2 - rect.0).abs() * 0.5, |
| 324 | hy: (rect.3 - rect.1).abs() * 0.5, |
| 325 | cos: 1.0, |
| 326 | sin: 0.0, |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | /// The box's two unit axes. |
| 331 | fn axes(&self) -> [(f32, f32); 2] { |
| 332 | [(self.cos, self.sin), (-self.sin, self.cos)] |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | /// Whether two oriented boxes overlap, by the separating-axis theorem. |
| 337 | /// |
| 338 | /// Four candidate axes (each box's two), which is all a 2D OBB pair needs: if the boxes' shadows |
| 339 | /// are disjoint on any one axis they cannot intersect. Touching exactly (a gap of zero) counts as |
| 340 | /// separated, matching the half-open [`overlaps`] the axis-aligned path uses so a label may sit |
| 341 | /// flush against its neighbour. |
| 342 | /// |
| 343 | /// Fast path: when both boxes are axis-aligned (`sin == 0`, which is how every point label enters |
| 344 | /// via [`Obb::from_rect`]), this is exactly the 4-float AABB test — same half-open rule, no SAT. |
| 345 | pub fn obb_overlap(a: &Obb, b: &Obb) -> bool { |
| 346 | if a.sin == 0.0 && b.sin == 0.0 { |
| 347 | // |dx| < hx sum AND |dy| < hy sum; touching exactly (>=) is separated. |
| 348 | return (a.cx - b.cx).abs() < a.hx + b.hx && (a.cy - b.cy).abs() < a.hy + b.hy; |
| 349 | } |
| 350 | let dx = b.cx - a.cx; |
| 351 | let dy = b.cy - a.cy; |
| 352 | for axis in a.axes().iter().chain(b.axes().iter()) { |
| 353 | let (ax, ay) = *axis; |
| 354 | let centre_gap = (dx * ax + dy * ay).abs(); |
| 355 | let ra = project_radius(a, ax, ay); |
| 356 | let rb = project_radius(b, ax, ay); |
| 357 | if centre_gap >= ra + rb { |
| 358 | return false; |
| 359 | } |
| 360 | } |
| 361 | true |
| 362 | } |
| 363 | |
| 364 | /// The half-width of `box`'s shadow on unit axis `(ax, ay)`. |
| 365 | fn project_radius(b: &Obb, ax: f32, ay: f32) -> f32 { |
| 366 | let [u, v] = b.axes(); |
| 367 | b.hx * (u.0 * ax + u.1 * ay).abs() + b.hy * (v.0 * ax + v.1 * ay).abs() |
| 368 | } |
| 369 | |
| 370 | /// A label candidate whose collision footprint is one or more oriented boxes. |
| 371 | /// |
| 372 | /// The superset of [`Candidate`]: a point label is a single [`Obb`], a curved label is the row of |
| 373 | /// per-glyph boxes [`curved_boxes`] builds. [`alternate`](Self::alternate) is the second |
| 374 | /// variable-anchor footprint (POI only), tried when the primary collides — the same fallback |
| 375 | /// [`Candidate`] carries, generalised to a set of boxes. |
| 376 | pub struct SegmentedCandidate { |
| 377 | pub id: u64, |
| 378 | pub rank: u8, |
| 379 | pub pop: u16, |
| 380 | pub boxes: Vec<Obb>, |
| 381 | pub alternate: Option<Vec<Obb>>, |
| 382 | /// Stable feature identity for cross-tile dedup (`ID_NONE` when the label |
| 383 | /// carries no identity — such candidates are never deduped). |
| 384 | pub feature_id: u64, |
| 385 | /// Style layer index, the second half of the dedup identity. |
| 386 | pub layer_index: usize, |
| 387 | } |
| 388 | |
| 389 | impl SegmentedCandidate { |
| 390 | /// The bounding half-area of the primary footprint, for the size tie-break — a curved label's |
| 391 | /// summed glyph areas, a point label's box area. |
| 392 | fn area(&self) -> f32 { |
| 393 | self.boxes.iter().map(|b| b.hx * b.hy).sum::<f32>() * 4.0 |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | include!("placement_grid.rs"); |
| 398 | include!("placement_part1.rs"); |
| 399 | include!("placement_part2.rs"); |
| 400 | include!("placement_part3.rs"); |
| 401 | include!("placement_globe.rs"); |