diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index cb49f27aac..d432b9be0c 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -430,7 +430,7 @@ pub fn commands() -> Vec { .inputs(super::Inputs::single_layer) .when(need_feature_layer) .params( - r#"{"layer"?, "class"?: name (none: the Default class, by whatever name it has), "position"?: "auto"|"center"|"above"|"below"|"left"|"right"|"aboveRight"|"aboveLeft"|"belowRight"|"belowLeft"|"parallel" (along a line, straight)|"curved" (along a line, following its bends)|"perpendicular" (a point's, square to the nearest line of `to`, starting at the point; none that near: as auto) (required without offset, repeat, lineOffset, otherPositions, showAll, weight, clearance, removeDuplicates, callout, to, side, fit, abbreviations or guide), "to"?: {"layer": a line or polygon layer's name, "within"?: points (1 to 500; 20)} | null, "side"?: "away" (the side of the line the point isn't on; the default)|"left"|"right" (as the line runs), "offset"?: [right, down] points (-200 to 200 each) the label moves from where its position puts it ([0, 0]: none; perpendicular: [out along the normal, down as the text reads]; a label along a line isn't moved), "repeat"?: points (10 to 10000) between a line's labels, spaced out from the one at its middle, at most 32 a line (0 or null: the one at its middle; parallel and curved only), "lineOffset"?: points (-200 to 200) between a line and its label's nearest edge, above the line as the text reads, negative below it (0 or null: on the line; parallel and curved only), "otherPositions"?: bool (a label whose place is taken tries others: a point's round the point, corners first; a line's along the line, nearest its middle first, placed parallel or curved without a repeat; a polygon's goes first where its shape fits best inside it, then where it goes without this; true is refused for any other line label, and on polygons for a curved label or one along a guide), "fit"?: "auto"|"off" (curved along a line: "auto" abbreviates a name that can't follow the line, sets one longer than a third of it on its straightest stretch, and spreads one over labels.style's stretch of a line more than three times its length; "off" or null: as placed), "abbreviations"?: {word: abbreviation} (whole words a fitted label puts short, ignoring case, over the built-in English, Portuguese and Spanish list, as {"Creek": "Cr.", "Córrego": "Cór."}; null or {}: the built-in list alone), "showAll"?: bool (every label drawn, over the others where they crowd), "weight"?: 0 to 10 (where labels compete for a place, the heavier class's wins, whatever its layer's place; equal weights: the layer above, then the class listed first; a fraction rounded; null: 5), "clearance"?: points (0 to 100: the room the class's labels keep free of other labels, two labels keeping both their clearances apart; null: 2), "removeDuplicates"?: points (1 to 2000: a label is left out within this distance of one placed before it for another feature of its layer and class with the same text; a label moved by hand always shows; false or null: off), "callout"?: true|false|points (5 to 500: a label crowded off its spot moves to a free one nearby, a line drawn back to its feature at most this long; true keeps its length, or 40; false, 0 or null: none; not labels along a line or with an icon), "guide"?: {"layer": a line layer's name (as ridge or valley lines; not drawn by this), "field"?: a field both layers have} | null (points and polygons, not perpendicular ones: each label curved along its guide line, the one with the feature's value in field, else the longest in view under the label inside its polygon, or the nearest to its point within the text's width; a feature with none its text fits along is labelled as without a guide; null: none)}"#, + r#"{"layer"?, "class"?: name (none: the Default class, by whatever name it has), "position"?: "auto"|"center"|"above"|"below"|"left"|"right"|"aboveRight"|"aboveLeft"|"belowRight"|"belowLeft"|"parallel" (along a line, straight)|"curved" (along a line, following its bends)|"perpendicular" (a point's, square to the nearest line of `to`, starting at the point; none that near: as auto) (required without offset, repeat, lineOffset, otherPositions, showAll, weight, clearance, removeDuplicates, callout, to, side, fit, abbreviations or guide), "to"?: {"layer": a line or polygon layer's name, "within"?: points (1 to 500; 20)} | null, "side"?: "away" (the side of the line the point isn't on; the default)|"left"|"right" (as the line runs), "offset"?: [right, down] points (-200 to 200 each) the label moves from where its position puts it ([0, 0]: none; perpendicular: [out along the normal, down as the text reads]; a label along a line isn't moved), "repeat"?: points (10 to 10000) between a line's labels, spaced out from the one at its middle, at most 32 a line (0 or null: the one at its middle; parallel and curved only), "lineOffset"?: points (-200 to 200) between a line and its label's nearest edge, above the line as the text reads, negative below it (0 or null: on the line; parallel and curved only), "otherPositions"?: bool (a label whose place is taken tries others: a point's round the point, corners first; a line's along the line, nearest its middle first, placed parallel or curved without a repeat; a polygon's goes first where its shape fits best inside it, then where it goes without this, then, if its text is wider or taller than the box of the polygon on the screen, round that box, corners first; true is refused for any other line label, and on polygons for a curved label or one along a guide), "fit"?: "auto"|"off" (curved along a line: "auto" abbreviates a name that can't follow the line, sets one longer than a third of it on its straightest stretch, and spreads one over labels.style's stretch of a line more than three times its length; "off" or null: as placed), "abbreviations"?: {word: abbreviation} (whole words a fitted label puts short, ignoring case, over the built-in English, Portuguese and Spanish list, as {"Creek": "Cr.", "Córrego": "Cór."}; null or {}: the built-in list alone), "showAll"?: bool (every label drawn, over the others where they crowd), "weight"?: 0 to 10 (where labels compete for a place, the heavier class's wins, whatever its layer's place; equal weights: the layer above, then the class listed first; a fraction rounded; null: 5), "clearance"?: points (0 to 100: the room the class's labels keep free of other labels, two labels keeping both their clearances apart; null: 2), "removeDuplicates"?: points (1 to 2000: a label is left out within this distance of one placed before it for another feature of its layer and class with the same text; a label moved by hand always shows; false or null: off), "callout"?: true|false|points (5 to 500: a label crowded off its spot moves to a free one nearby, a line drawn back to its feature at most this long; true keeps its length, or 40; false, 0 or null: none; not labels along a line or with an icon), "guide"?: {"layer": a line layer's name (as ridge or valley lines; not drawn by this), "field"?: a field both layers have} | null (points and polygons, not perpendicular ones: each label curved along its guide line, the one with the feature's value in field, else the longest in view under the label inside its polygon, or the nearest to its point within the text's width; a feature with none its text fits along is labelled as without a guide; null: none)}"#, ), // Labels moved by hand (the Move Label tool, as QGIS's): kept by their feature's id. C::new("labels.move", "Move Label", "Labeling › Label Placement", |s, p| { @@ -687,7 +687,7 @@ fn label_guide(s: &Session, p: &Value, labelled: &Layer) -> Result bool { points || (lines && c.placement.along_line() && c.repeat.is_none()) || (polygons && c.places_inside_polygons()) diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 564ae921e9..6e89ff2c04 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -2309,8 +2309,8 @@ pub struct Map { /// drawn while the lock holds, there, wherever the map moves. Filled by the renderer. #[serde(skip)] pub label_lock: Option>, - /// Geographic anchors of locked non-repeated line labels, and of polygon labels trying places - /// inside. Render cache only, never saved. + /// Geographic anchors of locked non-repeated line labels, and of polygon labels trying other + /// places, inside or round their polygon. Render cache only, never saved. #[serde(skip)] pub label_lock_line_anchors: std::collections::HashMap, /// Relationships, snapping, topology rules and edit settings. diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index d495154847..1bdf1b9420 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3013,7 +3013,8 @@ pub struct LabelClass { pub placement: LabelPlacement, /// A label taken by another tries nearby positions before it is left out (#1011): /// round a point ([`LabelPlacement::alternatives`]), or along a non-repeated line. A polygon's - /// goes first where its shape fits best inside it (#3268). + /// goes first where its shape fits best inside it (#3268), and last, + /// if its text doesn't fit the polygon's box, round it (#3484). /// Off by default: placed /// elsewhere, a label may take the place another has today. #[serde(default, deserialize_with = "de_flag", skip_serializing_if = "std::ops::Not::not")] diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index ece0af298e..8bdb6d6457 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -374,18 +374,39 @@ fn globe_outline(globe: &rustgis_map::Globe, mut ring: Vec) -> Vec<(f32, /// for no polygon, one with no area near the view (or this side of the horizon) or one with a /// place behind the camera. /// -/// With `clip` (#3276), the rings are first cut to that view, so the place is in the polygon's -/// part in view and the view's edges count as its own: a name that fits in that part is whole on -/// the screen. +/// `rings` are [`shown_rings`]' of the label part. Cut to the view there (#3276), the place is in +/// the polygon's part in view and the view's edges count as its own: a name that fits in that part +/// is whole on the screen. pub(super) fn pole( ctx: &super::Ctx<'_>, - g: &rustgis_data::Geometry, + mut rings: Vec>, aspect: f32, shown: Option<&super::View>, - clip: bool, ) -> Option<((f32, f32), (f32, f32))> { #[cfg(test)] SEARCHES.with(|n| n.set(n.get() + 1)); + let here = ctx.view; + // A text of no measurable shape counts as square; a very long or tall one as 20 to 1. + let aspect = if aspect.is_finite() && aspect > 0.0 { aspect.clamp(0.05, 20.0) } else { 1.0 }; + rings.iter_mut().flatten().for_each(|p| p.0 /= aspect); + let (x, y) = rustgis_tiles::symbols::pole_of_inaccessibility(&rings, 1.0)?; + let there = (x * aspect, y); + let Some(to) = shown else { return Some((there, there)) }; + let m = to.camera.try_to_map(f64::from(there.0), f64::from(there.1), to.width, to.height)?; + let (x, y) = here.to_screen(m); + Some(((x as f32, y as f32), there)) +} + +/// The rings of `g`'s label part as [`pole`] searches them, in the points of the view the frame is +/// `shown` in (none: the frame's own), cut to the frame and that view with `clip`. +pub(super) fn shown_rings( + ctx: &super::Ctx<'_>, + g: &rustgis_data::Geometry, + shown: Option<&super::View>, + clip: bool, +) -> Option>> { + #[cfg(test)] + THINNED.with(|n| n.set(n.get() + 1)); let mut rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; let here = ctx.view; // Cut to the frame before a tilted view is projected to: a vertex far outside the frame may be @@ -403,15 +424,15 @@ pub(super) fn pole( if let Some(to) = shown.filter(|_| clip) { rings = clipped(&rings, to)?; } - // A text of no measurable shape counts as square; a very long or tall one as 20 to 1. - let aspect = if aspect.is_finite() && aspect > 0.0 { aspect.clamp(0.05, 20.0) } else { 1.0 }; - rings.iter_mut().flatten().for_each(|p| p.0 /= aspect); - let (x, y) = rustgis_tiles::symbols::pole_of_inaccessibility(&rings, 1.0)?; - let there = (x * aspect, y); - let Some(to) = shown else { return Some((there, there)) }; - let m = to.camera.try_to_map(f64::from(there.0), f64::from(there.1), to.width, to.height)?; - let (x, y) = here.to_screen(m); - Some(((x as f32, y as f32), there)) + Some(rings) +} + +/// The box round [`shown_rings`], as left, top, right and bottom: what a label goes round when its +/// places inside are taken (#3484). +pub(super) fn around(rings: &[Vec<(f32, f32)>]) -> Option<(f32, f32, f32, f32)> { + let none = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); + let (l, t, r, b) = rings.iter().flatten().fold(none, |(l, t, r, b), &(x, y)| (l.min(x), t.min(y), r.max(x), b.max(y))); + (l <= r && t <= b).then_some((l, t, r, b)) } /// The parts of `rings` (an outer ring first) inside `view`'s box, in its points; `None` with none @@ -434,6 +455,8 @@ fn clipped(rings: &[Vec<(f32, f32)>], view: &super::View) -> Option = const { std::cell::Cell::new(0) }; + /// The times [`shown_rings`] thinned a label's rings on this thread. + pub(super) static THINNED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// [`glyphs`]' characters `advances` wide and `height` tall, as [`Line::curved`] takes them. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4632b22ecd..63d11020fc 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6282,6 +6282,15 @@ fn render_frame( .and_then(|c| if globe.is_some() { Some(c) } else { flat.forward_checked(c) }) .and_then(|c| ctx.screen(c)) }; + // Features a lock holds at a place round their polygon (#3484), which may still be + // in view once the polygon has left it. + let locked_rounds: std::collections::HashSet = lock + .iter() + .filter(|_| any_inside) + .flat_map(|locks| locks.iter()) + .filter(|((layer, ..), place)| *layer == lid && place.place >= 2) + .map(|((_, feature, ..), _)| *feature) + .collect(); for (row, g) in geoms.iter().enumerate() { let Some(g) = g else { continue }; if rows.get(row) != Some(&true) { @@ -6317,7 +6326,8 @@ fn render_frame( ((any_along && matches!(g, Geometry::Line(_))) || (any_inside && matches!(g, Geometry::Polygon(_)))) && extent_in_view() }; - if point.is_none() && !reaches_view() && !moved_here() { + let held_round = || matches!(g, Geometry::Polygon(_)) && locked_rounds.contains(&label_id(row)); + if point.is_none() && !reaches_view() && !moved_here() && !held_round() { continue; } let is_point = g.kind() == GeometryType::Point; @@ -6779,11 +6789,20 @@ fn render_frame( }; there.is_some_and(on_shown) }; + // Whether its label point is in the view shown. + let own_seen = point.is_some() && in_view((x as f32, y as f32)); + // Its part's rings as shown, whole and cut to the view: each thinned once. + // The box round it is the whole one's, which the search inside thins first. + let rings: [std::cell::OnceCell<_>; 2] = Default::default(); + let ringed = |clip: bool| { + rings[usize::from(clip)].get_or_init(|| area_labels::shown_rings(ctx, g, shown, clip)).as_ref() + }; + let pole = |clip: bool| area_labels::pole(ctx, ringed(clip)?.clone(), bw / bh, shown); // Where it goes first, when that isn't its label point: locked there, // the map place it was locked at (not what a search finds now, as along // a flat stretch many places are as good); not locked, the pole, when a // search finds one in view, or with its label point out of view too, the - // pole of its part in view (#3276). Locked at the place after, neither. + // pole of its part in view (#3276). Locked at a later place, neither. let first = match locked_at { _ if !tries => None, Some(0) => { @@ -6795,45 +6814,97 @@ fn render_frame( Some((x as f32, y as f32)).filter(|&at| point.is_some() || in_view(at)) } Some(_) => None, - None => area_labels::pole(ctx, g, bw / bh, shown, false) + None => pole(false) .filter(|&(_, (px, py))| on_shown((f64::from(px), f64::from(py)))) - .or_else(|| { - let own_seen = point.is_some() && in_view((x as f32, y as f32)); - if own_seen { None } else { area_labels::pole(ctx, g, bw / bh, shown, true) } - }) + .or_else(|| if own_seen { None } else { pole(true) }) .map(|(here, _)| here), }; // Its label point, where that is a place for it: not one out of view // when it has a place in view. - let own = point.is_some() && (first.is_none() || locked_at.is_some() || in_view((x as f32, y as f32))); - if tries && !own && first.is_none() { + let own = point.is_some() && (first.is_none() || locked_at.is_some() || own_seen); + // Locked at a place round the polygon, it needs neither place inside. + let locked_round = locked_at.is_some_and(|place| place >= 2); + if tries && !own && first.is_none() && !locked_round { continue; } // A callout's line goes back to the place inside when the label point // isn't in view. if let Some((fx, fy)) = first - && !(point.is_some() && in_view((x as f32, y as f32))) + && !own_seen { anchor = Some((f64::from(fx), f64::from(fy))); } - // The first place and the label point on the map, while the lock is - // taken (never from a tilted view), for it to keep. - if tries && display.locked && lock.is_none() && !matches!(labels_to, Labels::Tilted(..)) { - let on_map = |(x, y): (f32, f32)| match &globe { - Some(globe) => globe.inverse(f64::from(x), f64::from(y)), - None => flat.inverse(view.camera.to_map(f64::from(x), f64::from(y), view.width, view.height)), + // A place in the frame's points on the map, and one on the map on the screen. + let on_map = |(x, y): (f32, f32)| match &globe { + Some(globe) => globe.inverse(f64::from(x), f64::from(y)), + None => flat.inverse(view.camera.to_map(f64::from(x), f64::from(y), view.width, view.height)), + }; + // After both places inside, a name wider or taller than the box of its + // part goes round that box, upright in the view shown (#3484): the + // places a point's label tries, each as far off the box's side or corner. + // A name that fits stays on its own polygon: off the box of a large one it + // would read as another's. Not a label turned by its expression, whose box + // this isn't. A place off the view, or with none on the map for a lock to + // keep (past the globe's edge), isn't one, but keeps its slot. + let mut round = Vec::new(); + if let Some(place) = locked_at.filter(|_| tries && locked_round) { + // Locked there: the map place it was locked at, as the first inside is, + // and like it no label where that has no place in this view. + let target = map.label_lock_line_anchors.get(&key).copied().and_then(|anchor| match &globe { + Some(globe) => globe.forward(anchor), + None => flat.forward(anchor).map(|p| view.to_screen(p)), + }); + let Some((x, y)) = target else { continue }; + // The slots before it (the label point's is the first), then its own. + round.resize(usize::from(place) - 2, LabelPlace::from((f32::NAN, f32::NAN))); + round.push(LabelPlace::from((x as f32, y as f32))); + } else if tries + && turned.is_none() + && locked_at.is_none() + && let Some((left, top, right, bottom)) = ringed(false).and_then(|r| area_labels::around(r)) + && (bw * label_factor > right - left || bh * label_factor > bottom - top) + { + let along = |d: f32, lo: f32, hi: f32| { + if d < 0.0 { + lo + } else if d > 0.0 { + hi + } else { + (lo + hi) / 2.0 + } }; + round.extend(LabelPlacement::Center.alternatives().map(|p| { + let (dx, dy) = p.offset(0.0, 0.0, 0.0, false); + let (px, py) = place_at((along(dx, left, right), along(dy, top, bottom)), p); + let there = (f64::from(px), f64::from(py)); + let here = Some(there).filter(|&at| on_shown(at)).and_then(|(x, y)| match shown { + Some(to) => to + .camera + .try_to_map(x, y, to.width, to.height) + .map(|m| ctx.view.to_screen(m)) + .map(|(x, y)| (x as f32, y as f32)), + None => Some((px, py)), + }); + LabelPlace::from(here.filter(|&at| on_map(at).is_some()).unwrap_or((f32::NAN, f32::NAN))) + })); + } + // Each place on the map, while the lock is taken (never from a tilted + // view): it keeps the one it took. + if tries && display.locked && lock.is_none() && !matches!(labels_to, Labels::Tilted(..)) { let label_point = (x as f32, y as f32); let mut anchors = vec![on_map(first.unwrap_or(label_point))]; - if own { - anchors.push(on_map(label_point)); + if own || !round.is_empty() { + anchors.push(own.then(|| on_map(label_point)).flatten()); } + anchors.extend(round.iter().map(|p: &LabelPlace| on_map((p.x, p.y)))); line_places = Some(LinePlaces { anchors, ..Default::default() }); } // The label point is the place after the first, so a lock that took it - // there finds it. - if tries && own { - line_alternatives.push(LabelPlace { x: lx, y: ly, angle: turned, glyphs: Vec::new() }); + // there finds it; without it, its slot stays before those round. + if tries && (own || !round.is_empty()) { + let (x, y) = if own { (lx, ly) } else { (f32::NAN, f32::NAN) }; + line_alternatives.push(LabelPlace { x, y, angle: turned, glyphs: Vec::new() }); + line_alternatives.append(&mut round); } let (px, py) = first.map_or((lx, ly), |first| place_at(first, class.placement)); places.push((0, px, py, turned, Vec::new())); diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index eb3134196c..2e08090ed3 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -1,5 +1,5 @@ //! A polygon's label trying other places (#3268): its pole of inaccessibility first, then where -//! it goes without the setting. +//! it goes without the setting, then round the polygon (#3484). use super::*; use rustgis_data::{Dataset, Field, FieldType, Value}; @@ -84,9 +84,14 @@ fn depth(rings: &[Vec], p: Coord) -> f64 { /// A point layer above the polygon with a heavier label centred at `places`, which take them. fn block(m: &mut Map, v: &View, places: &[(f32, f32)]) { + block_at(m, &places.iter().map(|&p| at(v, p)).collect::>()); +} + +/// [`block`] at longitudes and latitudes. +fn block_at(m: &mut Map, places: &[Coord]) { let mut d = Dataset::new("blockers", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); for &p in places { - d.push(Some(Geometry::Point(at(v, p))), vec![Value::Text("XX".into())]); + d.push(Some(Geometry::Point(p)), vec![Value::Text("XX".into())]); } let id = m.add_dataset(d); if let Some(l) = m.layer_mut(id) { @@ -97,6 +102,54 @@ fn block(m: &mut Map, v: &View, places: &[(f32, f32)]) { } } +/// A square 44 points across in [`view`]: with [`islet`]'s spacing, narrower than its name. +fn small() -> Vec { + square(0.0, 0.0, 0.02) +} + +/// The letter spacing that makes "Lake" wider than a small polygon. +const WIDE: f32 = 15.0; + +/// A map of the polygon `rings` whose name, spaced wide, doesn't fit in its box. +fn islet(rings: Vec, on: bool) -> (Map, u32) { + let (mut m, id) = map(Geometry::Polygon(vec![vec![rings]]), on); + m.layer_mut(id).unwrap().labels.default.spacing = WIDE; + (m, id) +} + +/// The places the "Lake" label takes one after another, each blocked once it has taken it, until +/// it is left out. +fn every_place(m: &mut Map, v: &View) -> Vec<(f32, f32)> { + let mut taken = Vec::new(); + while let Some(&here) = places(m, v).first() { + assert!(taken.len() < 12, "{taken:?}"); + taken.push(here); + block(m, v, &[here]); + } + taken +} + +/// The box on the screen round `ring`: left, top, right, bottom. +fn screen_box(v: &View, ring: &[Coord]) -> (f32, f32, f32, f32) { + ring.iter().fold((f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY), |b, &p| { + let (x, y) = v.to_screen(lonlat_to_merc(p)); + (b.0.min(x as f32), b.1.min(y as f32), b.2.max(x as f32), b.3.max(y as f32)) + }) +} + +/// Which side of the box `b` the place is past, across and down: -1, 0 (between its sides) or 1. +fn side((l, t, r, b): (f32, f32, f32, f32), (x, y): (f32, f32)) -> (i8, i8) { + let past = |v: f32, lo: f32, hi: f32| i8::from(v > hi) - i8::from(v < lo); + (past(x, l, r), past(y, t, b)) +} + +/// [`side`] of a place between the box's sides. +const INSIDE: (i8, i8) = (0, 0); + +/// The sides of the places round a polygon, in the order a point's label tries them: corners +/// first. +const ROUND: [(i8, i8); 8] = [(1, -1), (-1, -1), (1, 1), (-1, 1), (1, 0), (-1, 0), (0, -1), (0, 1)]; + /// The polygon's label point on the screen. fn today(v: &View, g: &Geometry) -> (f32, f32) { let (x, y) = v.to_screen(lonlat_to_merc(g.label_point().unwrap())); @@ -162,12 +215,11 @@ fn with_its_pole_taken_it_goes_to_its_label_point() { } #[test] -fn with_both_taken_it_is_unplaced_once_at_its_pole() { +fn with_every_place_taken_it_is_unplaced_once_at_its_pole() { let g = Geometry::Polygon(vec![u()]); - let (mut m, _) = map(g.clone(), true); + let (mut m, _) = map(g, true); let v = view(); - let pole = one(&mut m, &v); - block(&mut m, &v, &[pole, today(&v, &g)]); + let pole = every_place(&mut m, &v)[0]; m.label_display.show_unplaced = true; let r = render(&mut m, &v).unwrap(); assert!(r.labels.iter().all(|l| l.text != "Lake")); @@ -312,8 +364,7 @@ fn a_crowded_label_locked_without_a_pole_is_unplaced() { let mut v = v; v.camera.bearing = bearing; let (mut m, _) = map(g.clone(), true); - let at_label = one(&mut m, &v); - block(&mut m, &v, &[at_label]); + every_place(&mut m, &v); m.label_display.show_unplaced = true; m.label_display.locked = true; let r = render(&mut m, &v).unwrap(); @@ -515,11 +566,10 @@ fn turned_and_tilted_views_label_the_visible_part() { } #[test] -fn a_visible_parts_label_with_its_place_taken_is_left_out() { +fn a_visible_parts_label_with_every_place_taken_is_left_out() { let (mut m, _) = map(Geometry::Polygon(vec![big()]), true); let v = east(); - let here = one(&mut m, &v); - block(&mut m, &v, &[here]); + let here = every_place(&mut m, &v)[0]; m.label_display.show_unplaced = true; let r = render(&mut m, &v).unwrap(); assert!(r.labels.iter().all(|l| l.text != "Lake")); @@ -536,9 +586,9 @@ fn a_visible_parts_callout_points_back_to_its_place() { past_edge.camera.center.x = lonlat_to_merc(c(0.0, 0.0)).x + 410.0 * past_edge.camera.res; for v in [east(), past_edge] { let (mut m, id) = map(Geometry::Polygon(vec![big()]), true); + let here = every_place(&mut m, &v)[0]; + // Set after: a label with a callout moves off a crowded place instead of being left out. m.layer_mut(id).unwrap().labels.default.callout = Some(60.0); - let here = one(&mut m, &v); - block(&mut m, &v, &[here]); for locked in [false, true] { m.label_display.locked = locked; // Twice: the frame that takes the lock, then one replaying it. @@ -734,3 +784,221 @@ fn on_the_globe_a_line_is_labelled_along_its_visible_stretch_only() { let there = globe_under(&v, one(&mut along(50..=170), &v)); assert!((50.0..101.0).contains(&there.x), "{there:?}"); } + +#[test] +fn with_both_places_inside_taken_it_goes_round_its_polygon_corners_first() { + // A square large enough to keep the places round it well clear of a blocker inside, with a + // name spaced far wider than it is in any view here. + let around = square(0.0, 0.0, 0.03); + // Turned and tilted too: above and beside are as the screen shows them. + for (bearing, pitch) in [(0.0, 0.0), (90.0, 0.0), (30.0, 0.0), (0.0, 30.0)] { + let mut v = view(); + (v.camera.bearing, v.camera.pitch) = (bearing, pitch); + let (mut m, id) = islet(around.clone(), true); + m.layer_mut(id).unwrap().labels.default.spacing = 25.0; + let taken = every_place(&mut m, &v); + let bounds = screen_box(&v, &around); + let sides: Vec<_> = taken.iter().map(|&p| side(bounds, p)).filter(|&s| s != INSIDE).collect(); + assert_eq!(sides, ROUND, "turned {bearing}, tilted {pitch}: {taken:?} round {bounds:?}"); + } +} + +#[test] +fn a_place_round_a_polygon_stands_off_it_by_the_classs_offset() { + let v = view(); + let first = |offset: [f32; 2]| { + let (mut m, id) = islet(small(), true); + m.layer_mut(id).unwrap().labels.default.offset = offset; + every_place(&mut m, &v)[1] + }; + let (plain, off) = (first([0.0, 0.0]), first([9.0, -6.0])); + assert!(near((off.0 - plain.0, off.1 - plain.1), (9.0 * 1.33, -6.0 * 1.33)), "{plain:?} {off:?}"); + // The whole name clear of the box, just past its corner. + let (_, top, right, _) = screen_box(&v, &small()); + let size = render(&mut islet(small(), false).0, &v).unwrap().labels[0].size; + let face = text::Face { bold: false, italic: false, serif: false, family: None }; + let (hw, hh) = (text::spaced_block_width("Lake", size, face, WIDE) / 2.0, text::block_height("Lake", size) / 2.0); + assert!(near(plain, (right + hw + 2.0, top - hh - 2.0)), "{plain:?} {right} {top}"); +} + +#[test] +fn off_a_polygons_label_does_not_go_round_it() { + let (mut m, _) = islet(small(), false); + let v = view(); + assert_eq!(every_place(&mut m, &v).len(), 1); +} + +#[test] +fn places_off_the_view_are_not_tried_round_a_polygon() { + let (mut m, _) = islet(small(), true); + // The polygon against the view's right edge: the places right of it are off the view. + let v = view_at(-0.33, 0.0); + let taken = every_place(&mut m, &v); + let sides: Vec<_> = taken.iter().map(|&p| side(screen_box(&v, &small()), p)).filter(|&s| s != INSIDE).collect(); + assert_eq!(sides, [(-1, -1), (-1, 1), (-1, 0), (0, -1), (0, 1)], "{taken:?}"); +} + +#[test] +fn a_visible_parts_label_does_not_go_round_a_polygon_its_name_fits() { + let (mut m, id) = map(Geometry::Polygon(vec![big()]), true); + m.layer_mut(id).unwrap().labels.default.spacing = WIDE; + // Only a strip of the polygon's east side in view, 20 points wide: narrower than the name, + // which fits the polygon all the same. + assert_eq!(every_place(&mut m, &view_at(1.341, 0.0)).len(), 1); +} + +#[test] +fn a_multipolygon_is_labelled_round_the_part_its_label_point_picks() { + let g = Geometry::Polygon(vec![vec![square(0.2, 0.15, 0.01)], vec![small()]]); + let (mut m, id) = map(g, true); + m.layer_mut(id).unwrap().labels.default.spacing = WIDE; + let v = view(); + let taken = every_place(&mut m, &v); + let sides: Vec<_> = taken.iter().map(|&p| side(screen_box(&v, &small()), p)).filter(|&s| s != INSIDE).collect(); + assert_eq!(sides, ROUND, "{taken:?}"); +} + +#[test] +fn on_the_globe_a_label_goes_round_its_polygon_in_view() { + let rings = [square(30.0, 0.0, 4.0)]; + let (mut m, id) = globe(&rings, true); + m.layer_mut(id).unwrap().labels.default.spacing = WIDE; + let v = globe_at(0.0); + let here = one(&mut m, &v); + block_at(&mut m, &[globe_under(&v, here)]); + let (x, y) = one(&mut m, &v); + assert!(!near((x, y), here) && (0.0..=800.0).contains(&x) && (0.0..=600.0).contains(&y), "{here:?} {:?}", (x, y)); +} + +#[test] +fn a_label_turned_by_an_expression_does_not_go_round_its_polygon() { + let (mut m, id) = islet(small(), true); + m.layer_mut(id).unwrap().labels.default.by.angle = Some("20".into()); + let v = view(); + assert_eq!(every_place(&mut m, &v).len(), 1); +} + +/// A lock keeps the side a label took round its polygon, also once its label point has left the +/// view. +#[test] +fn a_lock_keeps_the_side_a_label_took_round_its_polygon() { + for taken in [2, 3] { + let (mut m, _) = islet(small(), true); + let v = view(); + for _ in 1..taken { + let here = one(&mut m, &v); + block(&mut m, &v, &[here]); + } + m.label_display.locked = true; + let before = at(&v, one(&mut m, &v)); + assert!(m.label_lock.as_ref().unwrap().iter().any(|(_, p)| usize::from(p.place) == taken), "{:?}", m.label_lock); + // Panned, then panned so far north that the label point is below the view. + for moved in [view_at(0.03, 0.02), view_at(0.0, 0.28)] { + let after = at(&moved, one(&mut m, &moved)); + assert!((after.x - before.x).abs() < 2e-3 && (after.y - before.y).abs() < 2e-3, "{taken}: {before:?} {after:?}"); + } + } +} + +/// A place past the globe's edge has no place on the map for a lock to keep: it isn't tried. +#[test] +fn a_place_past_the_globes_edge_is_not_tried_round_a_polygon() { + // Up against the west edge of a globe centred on the prime meridian. + let rings = [ring(&[(-89.0, -10.0), (-60.0, -10.0), (-60.0, 10.0), (-89.0, 10.0)])]; + let v = globe_at(0.0); + let (mut m, id) = globe(&rings, true); + m.layer_mut(id).unwrap().labels.default.spacing = WIDE; + let on_the_globe = + |(x, y): (f32, f32)| rustgis_map::Globe::new(&v.camera, v.width, v.height).inverse(f64::from(x), f64::from(y)).is_some(); + let first = one(&mut m, &v); + block_at(&mut m, &[globe_under(&v, first)]); + let mut taken = 0; + while let Some(&here) = places(&mut m, &v).first() { + assert!(on_the_globe(here) && taken < 10, "{taken}: {here:?}"); + block_at(&mut m, &[globe_under(&v, here)]); + taken += 1; + } + assert!(taken > 0); +} + +#[test] +fn a_name_that_fits_its_polygons_box_does_not_go_round_it() { + let (mut m, _) = map(Geometry::Polygon(vec![u()]), true); + // Its two places inside, and no more. + assert_eq!(every_place(&mut m, &view()).len(), 2); +} + +#[test] +fn a_name_taller_than_its_polygon_goes_round_it() { + let rings = vec![vec![ring(&[(-0.2, -0.003), (0.2, -0.003), (0.2, 0.003), (-0.2, 0.003)])]]; + let (mut m, _) = map(Geometry::Polygon(rings), true); + let taken = every_place(&mut m, &view()); + assert!(taken.len() > 2, "{taken:?}"); +} + +/// Zoomed in so that its name fits, a label locked round its polygon stays there. +#[test] +fn a_lock_round_a_polygon_holds_once_the_name_fits() { + let (mut m, _) = islet(small(), true); + let v = view(); + let here = one(&mut m, &v); + block(&mut m, &v, &[here]); + m.label_display.locked = true; + assert!(!near(one(&mut m, &v), here)); + let mut closer = v; + closer.camera.res = 40.0; + let after = one(&mut m, &closer); + assert!(side(screen_box(&closer, &small()), after) == ROUND[0], "{after:?}"); +} + +/// A lock keeps a place round a polygon where it is on the map, not on the part still in view. +#[test] +fn a_lock_round_a_polygon_stays_as_its_part_in_view_changes() { + let (mut m, _) = islet(small(), true); + let v = view(); + // Above it: between its sides, so a box of the part in view would move it. + for _ in 1..8 { + let here = one(&mut m, &v); + block(&mut m, &v, &[here]); + } + assert_eq!(side(screen_box(&v, &small()), one(&mut m, &v)), (0, -1)); + m.label_display.locked = true; + let before = at(&v, one(&mut m, &v)); + // Its label point just past the left edge. + let moved = view_at(0.3643, 0.0); + let after = at(&moved, one(&mut m, &moved)); + assert!((after.x - before.x).abs() < 2e-3 && (after.y - before.y).abs() < 2e-3, "{before:?} {after:?}"); +} + +/// A place round a polygon can still be in view once the polygon has left it: a lock holds it. +#[test] +fn a_lock_round_a_polygon_holds_once_the_polygon_leaves_the_view() { + let (mut m, _) = islet(small(), true); + let v = view(); + let here = one(&mut m, &v); + block(&mut m, &v, &[here]); + m.label_display.locked = true; + let before = at(&v, one(&mut m, &v)); + // The polygon 60 points past the left edge, its name partly in view still. + let moved = view_at(0.4332, 0.0); + assert!(screen_box(&moved, &small()).2 < -55.0); + let after = at(&moved, one(&mut m, &moved)); + assert!((after.x - before.x).abs() < 2e-3 && (after.y - before.y).abs() < 2e-3, "{before:?} {after:?}"); +} + +/// One label's rings are thinned once whole, and once more cut to the view when its label point is +/// out of it: for the search inside and the box round it alike. +#[test] +fn a_polygon_labels_rings_are_thinned_once_whole_and_once_cut_to_the_view() { + // The U seen from above its label point, its pole still in view. + let low = view_at(0.0, 0.1); + let u = u()[0].clone(); + assert!(today(&low, &Geometry::Polygon(vec![vec![u.clone()]])).1 > 600.0); + for (rings, v, most) in [(small(), view(), 1), (u, low, 1), (small(), view_at(0.3643, 0.0), 2), (big()[0].clone(), east(), 2)] { + let (mut m, _) = islet(rings, true); + area_labels::THINNED.with(|n| n.set(0)); + render(&mut m, &v).unwrap(); + let thinned = area_labels::THINNED.with(std::cell::Cell::get); + assert!((1..=most).contains(&thinned), "{thinned} of at most {most}, at {:?}", v.camera.center); + } +} diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 28b1b87356..5505ba5d1c 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -881,13 +881,16 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { } square_to(app, ui, l, c); } - // Polygons: where the text fits best inside, tried before the label's own place (#3268). Not for - // a label curved or along a guide, whose course is its place. + // Polygons: where the text fits best inside, tried before the label's own place (#3268), then + // round a polygon its name doesn't fit (#3484). Not for a label curved or along a guide, whose + // course is its place. if l.geometry_type() == rustgis_engine::data::GeometryType::Polygon && c.it.places_inside_polygons() { ui.add_space(4.0); let mut on = c.it.other_positions; - let help = tl!("The label goes where it fits best inside the polygon; if that is taken, where it goes without this."); - if ui.checkbox(&mut on, tl!("Try other places inside the polygon")).on_hover_text(help).changed() { + let help = tl!( + "The label goes where it fits best inside the polygon; if that is taken, where it goes without this, then round a polygon its text doesn't fit." + ); + if ui.checkbox(&mut on, tl!("Try other places inside and around the polygon")).on_hover_text(help).changed() { run(app, "labels.placement", c.params(json!({"otherPositions": on}))); } } @@ -1636,7 +1639,7 @@ mod tests { #[test] fn other_positions_are_set_in_the_pane_for_polygons() { use egui::accesskit::Role; - const BOX: &str = "Try other places inside the polygon"; + const BOX: &str = "Try other places inside and around the polygon"; let mut h = harness(with_cities()); h.run(); let countries = layer_id(h.state(), "Countries"); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index e6e944f4b5..20af3425fc 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -802,19 +802,25 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: - **Other places inside polygons**: a polygon's label goes where its shape fits best inside the polygon, as seen on the screen (the point with the most room round it for something as wide and tall as the text), so a name sits in the body of a lake or bay rather than against a shore. Where - another label takes that place, it goes where it goes without this setting, and is left out if - that is taken too (Labeling pane › Position › **Try other places inside the polygon**, for polygon - layers). With that point out of view, the label stays where it goes without this. With both out of - view, the label goes where its shape fits best inside the part of the polygon in view, the view's - edges counting as the polygon's own: it follows that part as the map moves (Lock holds it), and is - left out if another label takes its place. On a multipolygon this is the part its label is for; + another label takes that place, it goes where it goes without this setting. With that taken too, + a name wider or taller than the polygon on the screen (a small country, an island) goes round it: + just off the box round it, in the order round points (above right, above left, below right, + below left, right, left, above, below), at the places in view (on the globe, those on it). A name + that fits that box stays on its polygon, so it never reads as a neighbour's. It is left out if + every place is taken (Labeling pane › Position › **Try other places inside and around the + polygon**, for polygon layers). A label turned by an angle expression doesn't go round it. With + the first place inside out of view, the label starts where it goes without this. With both + places inside out of view, it goes where its shape fits best inside the part of the polygon in + view, the view's edges counting as the polygon's own: it follows that part as the map moves (Lock + holds it), and if another label takes its place it goes round the polygon as above. On a multipolygon this is the part its label is for; other parts in view don't take it. On the globe only the part on this side of the horizon counts: the shape is fitted to it, and what is behind the horizon is out of view. On a polygon more than 64 times longer than wide on screen, once narrowed to the text's shape, only its first 64 widths are searched. Curved labels and labels along a guide don't use it: the box is hidden for them, the command refuses to turn it on, and a setting already on has no effect. Off by default, - as round points; the class's position and offset apply from each of the two places (Above sets the - name above that point), and Lock keeps the place each label took + as round points; the class's position and offset apply from each of the two places inside (Above + sets the name above that point), the offset alone to those round it, and Lock keeps the place + each label took (`labels.placement={"layer": "Lakes", "otherPositions": true}`). - **Other places along lines**: a Parallel or Curved label whose place at the middle is taken, or (curved) where the line bends too sharply, tries up to seven others along the same stretch,