From b370d16fb60cf2e651e173467af3649f7a3eabbe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 15:43:31 -0500 Subject: [PATCH 1/9] feat(labels): try places round a polygon after the ones inside With otherPositions on, a polygon's label whose two places inside are taken tries the eight places round the box of its part on the screen, in the order a point's label tries them. --- crates/map/src/symbology.rs | 2 +- crates/render/src/area_labels.rs | 40 +++- crates/render/src/lib.rs | 69 +++++-- crates/render/src/polygon_labels_tests.rs | 217 ++++++++++++++++++++-- crates/ui-egui/src/labelpane.rs | 12 +- docs/user-guide/cartography.md | 14 +- 6 files changed, 307 insertions(+), 47 deletions(-) diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index d495154847..66d77c0e82 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3013,7 +3013,7 @@ 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 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..508fb3b4c3 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -386,6 +386,22 @@ pub(super) fn pole( ) -> Option<((f32, f32), (f32, f32))> { #[cfg(test)] SEARCHES.with(|n| n.set(n.get() + 1)); + let mut rings = shown_rings(ctx, g, shown, clip)?; + 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`. +fn shown_rings(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry, shown: Option<&super::View>, clip: bool) -> Option>> { 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 +419,21 @@ 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( + ctx: &super::Ctx<'_>, + g: &rustgis_data::Geometry, + shown: Option<&super::View>, + clip: bool, +) -> Option<(f32, f32, f32, f32)> { + let rings = shown_rings(ctx, g, shown, clip)?; + 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 diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4632b22ecd..0a7225b68f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6779,6 +6779,8 @@ 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)); // 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 @@ -6797,27 +6799,61 @@ fn render_frame( Some(_) => None, None => area_labels::pole(ctx, g, bw / bh, shown, 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 { area_labels::pole(ctx, g, bw / bh, shown, 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. + // After both places inside, round the box of its part, upright in the + // view shown (#3484): the places a point's label tries, each as far off + // the box's side or corner. Not a label turned by its expression, whose + // box this isn't. A place off the view has none, but keeps its slot. + let mut round = Vec::new(); + if tries + && turned.is_none() + && (locked_at.is_none() || locked_round) + && let Some((left, top, right, bottom)) = area_labels::around(ctx, g, shown, !own_seen) + { + 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 = match shown { + _ if locked_at.is_none() && !on_shown(there) => None, + Some(to) => to + .camera + .try_to_map(there.0, there.1, 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.unwrap_or((f32::NAN, f32::NAN))) + })); + } + // Each place on the map, while the lock is taken (never from a tilted + // view): it keeps the first's, and takes none without one. 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)), @@ -6825,15 +6861,20 @@ fn render_frame( }; 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()); } + // A lock finds a place round again from the box, not from the map (one + // may be past the globe's edge): it needs the first's alone. + anchors.extend(std::iter::repeat_n(anchors[0], round.len())); 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..d24198d231 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,39 @@ fn block(m: &mut Map, v: &View, places: &[(f32, f32)]) { } } +/// 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 +200,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 +349,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 +551,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 +571,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 +769,159 @@ 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() { + // Its places inside are near its middle, well away from those round it. + let g = Geometry::Polygon(vec![vec![square(0.0, 0.0, 0.2)]]); + // 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.res, v.camera.bearing, v.camera.pitch) = (200.0, bearing, pitch); + let (mut m, _) = map(g.clone(), true); + let taken = every_place(&mut m, &v); + let around = screen_box(&v, &square(0.0, 0.0, 0.2)); + let sides: Vec<_> = taken.iter().map(|&p| side(around, p)).filter(|&s| s != INSIDE).collect(); + assert_eq!(sides, ROUND, "turned {bearing}, tilted {pitch}: {taken:?} round {around:?}"); + } +} + +#[test] +fn a_place_round_a_polygon_stands_off_it_by_the_classs_offset() { + let g = Geometry::Polygon(vec![u()]); + let v = view(); + let fifth = |offset: [f32; 2]| { + let (mut m, id) = map(g.clone(), true); + m.layer_mut(id).unwrap().labels.default.offset = offset; + every_place(&mut m, &v)[2] + }; + let (plain, off) = (fifth([0.0, 0.0]), fifth([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 (mut m, _) = map(g.clone(), true); + every_place(&mut m, &v); + let (_, top, right, _) = screen_box(&v, &u()[0]); + let size = render(&mut map(g, 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, 0.0) / 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 g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g, 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() { + // The whole view inside the polygon. + let (mut m, _) = map(Geometry::Polygon(vec![big()]), true); + let mut v = view(); + v.camera.res = 50.0; + assert_eq!(every_place(&mut m, &v).len(), 1); +} + +#[test] +fn a_visible_parts_label_goes_beside_its_polygon_where_the_view_has_room() { + let (mut m, _) = map(Geometry::Polygon(vec![big()]), true); + let v = east(); + let taken = every_place(&mut m, &v); + assert_eq!(taken.len(), 2, "{taken:?}"); + // The one place round the part in view that is in view: right of its east edge. + let (_, _, right, _) = screen_box(&v, &big()[0]); + assert!(taken[1].0 > right && (0.0..=800.0).contains(&taken[1].0) && (0.0..=600.0).contains(&taken[1].1), "{taken:?} {right}"); +} + +#[test] +fn a_multipolygon_is_labelled_round_the_part_its_label_point_picks() { + let g = Geometry::Polygon(vec![vec![square(0.6, 0.4, 0.03)], vec![square(0.0, 0.0, 0.2)]]); + let (mut m, _) = map(g, true); + let mut v = view(); + v.camera.res = 200.0; + let taken = every_place(&mut m, &v); + let sides: Vec<_> = taken.iter().map(|&p| side(screen_box(&v, &square(0.0, 0.0, 0.2)), p)).filter(|&s| s != INSIDE).collect(); + assert_eq!(sides, ROUND, "{taken:?}"); +} + +#[test] +fn on_the_globe_a_label_goes_round_the_visible_part_in_view() { + let rings = [eastward()]; + let (mut m, _) = globe(&rings, true); + 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_moved_by_hand_does_not_go_round_its_polygon() { + let (mut m, id) = map(Geometry::Polygon(vec![u()]), true); + let fid = m.layer(id).unwrap().dataset.features.first().unwrap().id; + m.layer_mut(id).unwrap().labels.default.moved = vec![rustgis_map::symbology::MovedLabel { id: fid, at: [0.0, 0.1] }]; + let v = view(); + // Placed before every other label: only a blocker moved over it could crowd it, and it stays. + let first = one(&mut m, &v); + block(&mut m, &v, &[first]); + assert!(near(one(&mut m, &v), first)); +} + +#[test] +fn a_label_turned_by_an_expression_does_not_go_round_its_polygon() { + let (mut m, id) = map(Geometry::Polygon(vec![u()]), true); + m.layer_mut(id).unwrap().labels.default.by.angle = Some("20".into()); + let v = view(); + assert_eq!(every_place(&mut m, &v).len(), 2); +} + +/// 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() { + let g = Geometry::Polygon(vec![u()]); + for taken in [2, 3] { + let (mut m, _) = map(g.clone(), true); + let v = view(); + for _ in 0..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.4)] { + 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 round a polygon may be past the globe's edge, with no place on the map: turning Lock on +/// keeps the label there all the same. +#[test] +fn locking_keeps_a_label_round_a_polygon_past_the_globes_edge() { + // 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, _) = globe(&rings, true); + let off_the_globe = + |(x, y): (f32, f32)| rustgis_map::Globe::new(&v.camera, v.width, v.height).inverse(f64::from(x), f64::from(y)).is_none(); + // Block each place it takes until it takes one past the edge. + let mut here = one(&mut m, &v); + for _ in 0..10 { + if off_the_globe(here) { + break; + } + block_at(&mut m, &[globe_under(&v, here)]); + here = one(&mut m, &v); + } + assert!(off_the_globe(here), "{here:?}"); + m.label_display.locked = true; + for frame in 0..2 { + assert!(near(one(&mut m, &v), here), "frame {frame}"); + } +} diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 28b1b87356..61f3a7eb0c 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -881,13 +881,15 @@ 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 the polygon (#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 the polygon." + ); + 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 +1638,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..172eaeb111 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -802,9 +802,12 @@ 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 + another label takes that place, it goes where it goes without this setting. With that taken too, + it goes round the polygon: just off the box round it on the screen, in the order round points + (above right, above left, below right, below left, right, left, above, below), at the places in + view, and is left out if all are 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 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; @@ -813,8 +816,9 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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, From 7905b11f5e91a94a5632dd847080a3d997a27ca3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 15:44:25 -0500 Subject: [PATCH 2/9] docs(labels): say in the command help that polygon labels also go round --- crates/engine/src/cmd/labels.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index cb49f27aac..35c56b00ef 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 round the box of the polygon on the screen, 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()) From e8cd7c21451719b23a9cddca513b5e35534c79e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 16:27:55 -0500 Subject: [PATCH 3/9] feat(labels): go round only a polygon its name doesn't fit Off the box of a large polygon a name reads as a neighbour's. --- crates/engine/src/cmd/labels.rs | 2 +- crates/map/src/symbology.rs | 2 +- crates/render/src/lib.rs | 12 ++- crates/render/src/polygon_labels_tests.rs | 110 +++++++++++++++------- crates/ui-egui/src/labelpane.rs | 4 +- docs/user-guide/cartography.md | 6 +- 6 files changed, 92 insertions(+), 44 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 35c56b00ef..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, then round the box of the polygon on the screen, 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)}"#, + 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| { diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 66d77c0e82..65e9620d75 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3013,7 +3013,7 @@ 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), and last round it (#3484). + /// 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/lib.rs b/crates/render/src/lib.rs index 0a7225b68f..35f67694b6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6817,15 +6817,19 @@ fn render_frame( { anchor = Some((f64::from(fx), f64::from(fy))); } - // After both places inside, round the box of its part, upright in the - // view shown (#3484): the places a point's label tries, each as far off - // the box's side or corner. Not a label turned by its expression, whose - // box this isn't. A place off the view has none, but keeps its slot. + // 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 has none, but keeps its slot. let mut round = Vec::new(); if tries && turned.is_none() && (locked_at.is_none() || locked_round) && let Some((left, top, right, bottom)) = area_labels::around(ctx, g, shown, !own_seen) + // A lock holds the place it took, whatever fits now. + && (locked_round || bw * label_factor > right - left || bh * label_factor > bottom - top) { let along = |d: f32, lo: f32, hi: f32| { if d < 0.0 { diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index d24198d231..aaa4065c2a 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -102,6 +102,21 @@ fn block_at(m: &mut Map, places: &[Coord]) { } } +/// 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 = 10.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)> { @@ -772,15 +787,13 @@ fn on_the_globe_a_line_is_labelled_along_its_visible_stretch_only() { #[test] fn with_both_places_inside_taken_it_goes_round_its_polygon_corners_first() { - // Its places inside are near its middle, well away from those round it. - let g = Geometry::Polygon(vec![vec![square(0.0, 0.0, 0.2)]]); // 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.res, v.camera.bearing, v.camera.pitch) = (200.0, bearing, pitch); - let (mut m, _) = map(g.clone(), true); + (v.camera.bearing, v.camera.pitch) = (bearing, pitch); + let (mut m, _) = islet(small(), true); let taken = every_place(&mut m, &v); - let around = screen_box(&v, &square(0.0, 0.0, 0.2)); + let around = screen_box(&v, &small()); let sides: Vec<_> = taken.iter().map(|&p| side(around, p)).filter(|&s| s != INSIDE).collect(); assert_eq!(sides, ROUND, "turned {bearing}, tilted {pitch}: {taken:?} round {around:?}"); } @@ -788,29 +801,25 @@ fn with_both_places_inside_taken_it_goes_round_its_polygon_corners_first() { #[test] fn a_place_round_a_polygon_stands_off_it_by_the_classs_offset() { - let g = Geometry::Polygon(vec![u()]); let v = view(); - let fifth = |offset: [f32; 2]| { - let (mut m, id) = map(g.clone(), true); + 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)[2] + every_place(&mut m, &v)[1] }; - let (plain, off) = (fifth([0.0, 0.0]), fifth([9.0, -6.0])); + 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 (mut m, _) = map(g.clone(), true); - every_place(&mut m, &v); - let (_, top, right, _) = screen_box(&v, &u()[0]); - let size = render(&mut map(g, false).0, &v).unwrap().labels[0].size; + 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, 0.0) / 2.0, text::block_height("Lake", size) / 2.0); + 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 g = Geometry::Polygon(vec![u()]); - let (mut m, _) = map(g, false); + let (mut m, _) = islet(small(), false); let v = view(); assert_eq!(every_place(&mut m, &v).len(), 1); } @@ -826,8 +835,10 @@ fn places_off_the_view_are_not_tried_round_a_polygon() { #[test] fn a_visible_parts_label_goes_beside_its_polygon_where_the_view_has_room() { - let (mut m, _) = map(Geometry::Polygon(vec![big()]), true); - let v = east(); + 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. + let v = view_at(1.341, 0.0); let taken = every_place(&mut m, &v); assert_eq!(taken.len(), 2, "{taken:?}"); // The one place round the part in view that is in view: right of its east edge. @@ -837,19 +848,20 @@ fn a_visible_parts_label_goes_beside_its_polygon_where_the_view_has_room() { #[test] fn a_multipolygon_is_labelled_round_the_part_its_label_point_picks() { - let g = Geometry::Polygon(vec![vec![square(0.6, 0.4, 0.03)], vec![square(0.0, 0.0, 0.2)]]); - let (mut m, _) = map(g, true); - let mut v = view(); - v.camera.res = 200.0; + 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, &square(0.0, 0.0, 0.2)), p)).filter(|&s| s != INSIDE).collect(); + 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_the_visible_part_in_view() { - let rings = [eastward()]; - let (mut m, _) = globe(&rings, true); +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)]); @@ -871,21 +883,20 @@ fn a_label_moved_by_hand_does_not_go_round_its_polygon() { #[test] fn a_label_turned_by_an_expression_does_not_go_round_its_polygon() { - let (mut m, id) = map(Geometry::Polygon(vec![u()]), true); + 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(), 2); + 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() { - let g = Geometry::Polygon(vec![u()]); for taken in [2, 3] { - let (mut m, _) = map(g.clone(), true); + let (mut m, _) = islet(small(), true); let v = view(); - for _ in 0..taken { + for _ in 1..taken { let here = one(&mut m, &v); block(&mut m, &v, &[here]); } @@ -893,7 +904,7 @@ fn a_lock_keeps_the_side_a_label_took_round_its_polygon() { 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.4)] { + 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:?}"); } @@ -907,7 +918,8 @@ fn locking_keeps_a_label_round_a_polygon_past_the_globes_edge() { // 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, _) = globe(&rings, true); + let (mut m, id) = globe(&rings, true); + m.layer_mut(id).unwrap().labels.default.spacing = WIDE; let off_the_globe = |(x, y): (f32, f32)| rustgis_map::Globe::new(&v.camera, v.width, v.height).inverse(f64::from(x), f64::from(y)).is_none(); // Block each place it takes until it takes one past the edge. @@ -925,3 +937,33 @@ fn locking_keeps_a_label_round_a_polygon_past_the_globes_edge() { assert!(near(one(&mut m, &v), here), "frame {frame}"); } } + +#[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:?}"); +} diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 61f3a7eb0c..24a4a2f11c 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -882,12 +882,12 @@ 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), then - // round the polygon (#3484). Not for a label curved or along a guide, whose course is its place. + // 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, then round the polygon." + "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}))); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 172eaeb111..63558de975 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -803,9 +803,11 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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. With that taken too, - it goes round the polygon: just off the box round it on the screen, in the order round points + 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, and is left out if all are taken (Labeling pane › Position › **Try other places inside and + view. 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 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 From 94bbbfc216306b86a5dc53ff88187ce826e37ea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 16:42:20 -0500 Subject: [PATCH 4/9] fix(labels): keep a locked place round a polygon where it is on the map --- crates/map/src/symbology.rs | 3 +- crates/render/src/lib.rs | 44 ++++++++++++--------- crates/render/src/polygon_labels_tests.rs | 47 +++++++++++++++-------- crates/ui-egui/src/labelpane.rs | 3 +- docs/user-guide/cartography.md | 2 +- 5 files changed, 61 insertions(+), 38 deletions(-) diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 65e9620d75..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), and last, if its text doesn't fit the polygon's box, round it (#3484). + /// 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/lib.rs b/crates/render/src/lib.rs index 35f67694b6..4a5a289a06 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6817,19 +6817,34 @@ fn render_frame( { anchor = Some((f64::from(fx), f64::from(fy))); } + // 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 has none, but keeps its slot. + // 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 tries + if let Some(place) = locked_at.filter(|_| tries && locked_round) { + // Locked there: the map place it was locked at, as the first inside is. + 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() || locked_round) + && locked_at.is_none() && let Some((left, top, right, bottom)) = area_labels::around(ctx, g, shown, !own_seen) - // A lock holds the place it took, whatever fits now. - && (locked_round || bw * label_factor > right - left || bh * label_factor > bottom - top) + && (bw * label_factor > right - left || bh * label_factor > bottom - top) { let along = |d: f32, lo: f32, hi: f32| { if d < 0.0 { @@ -6844,33 +6859,26 @@ fn render_frame( 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 = match shown { - _ if locked_at.is_none() && !on_shown(there) => None, + let here = Some(there).filter(|&at| on_shown(at)).and_then(|(x, y)| match shown { Some(to) => to .camera - .try_to_map(there.0, there.1, to.width, to.height) + .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.unwrap_or((f32::NAN, f32::NAN))) + }); + 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 first's, and takes none without one. + // view): it keeps the one it took. 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)), - }; let label_point = (x as f32, y as f32); let mut anchors = vec![on_map(first.unwrap_or(label_point))]; if own || !round.is_empty() { anchors.push(own.then(|| on_map(label_point)).flatten()); } - // A lock finds a place round again from the box, not from the map (one - // may be past the globe's edge): it needs the first's alone. - anchors.extend(std::iter::repeat_n(anchors[0], round.len())); + 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 diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index aaa4065c2a..0891cb0e8b 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -911,31 +911,25 @@ fn a_lock_keeps_the_side_a_label_took_round_its_polygon() { } } -/// A place round a polygon may be past the globe's edge, with no place on the map: turning Lock on -/// keeps the label there all the same. +/// A place past the globe's edge has no place on the map for a lock to keep: it isn't tried. #[test] -fn locking_keeps_a_label_round_a_polygon_past_the_globes_edge() { +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 off_the_globe = - |(x, y): (f32, f32)| rustgis_map::Globe::new(&v.camera, v.width, v.height).inverse(f64::from(x), f64::from(y)).is_none(); - // Block each place it takes until it takes one past the edge. - let mut here = one(&mut m, &v); - for _ in 0..10 { - if off_the_globe(here) { - break; - } + 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)]); - here = one(&mut m, &v); - } - assert!(off_the_globe(here), "{here:?}"); - m.label_display.locked = true; - for frame in 0..2 { - assert!(near(one(&mut m, &v), here), "frame {frame}"); + taken += 1; } + assert!(taken > 0); } #[test] @@ -967,3 +961,22 @@ fn a_lock_round_a_polygon_holds_once_the_name_fits() { 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:?}"); +} diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 24a4a2f11c..5505ba5d1c 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -882,7 +882,8 @@ 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), then - // round a polygon its name doesn't fit (#3484). Not for a label curved or along a guide, whose course is its place. + // 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; diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 63558de975..fc1201ec3f 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -806,7 +806,7 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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. A name that fits that box stays on its polygon, so it never reads as a neighbour's. It is + 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 that point out of view, the label stays where it goes without this. With both out of From 8cb2ed3ff98547b9580b71c9da1873c86c3301e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 17:01:30 -0500 Subject: [PATCH 5/9] fix(labels): hold a locked place round a polygon out of view, thinning its rings once --- crates/render/src/area_labels.rs | 25 +++++++++------------ crates/render/src/lib.rs | 27 ++++++++++++++++++----- crates/render/src/polygon_labels_tests.rs | 27 ++++++++++++++++++----- docs/user-guide/cartography.md | 19 ++++++++-------- 4 files changed, 65 insertions(+), 33 deletions(-) diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index 508fb3b4c3..09ece5d2d8 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -374,19 +374,17 @@ 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 mut rings = shown_rings(ctx, g, shown, clip)?; 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 }; @@ -401,7 +399,12 @@ pub(super) fn pole( /// 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`. -fn shown_rings(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry, shown: Option<&super::View>, clip: bool) -> Option>> { +pub(super) fn shown_rings( + ctx: &super::Ctx<'_>, + g: &rustgis_data::Geometry, + shown: Option<&super::View>, + clip: bool, +) -> Option>> { 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 @@ -424,13 +427,7 @@ fn shown_rings(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry, shown: Option<& /// 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( - ctx: &super::Ctx<'_>, - g: &rustgis_data::Geometry, - shown: Option<&super::View>, - clip: bool, -) -> Option<(f32, f32, f32, f32)> { - let rings = shown_rings(ctx, g, shown, clip)?; +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)) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4a5a289a06..62929bdb10 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6282,6 +6282,14 @@ 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() + .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 +6325,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; @@ -6781,6 +6790,13 @@ fn render_frame( }; // 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, + // for the search inside and the box round it alike. + 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 @@ -6797,9 +6813,9 @@ 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(|| 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 @@ -6831,7 +6847,8 @@ fn render_frame( // 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. + // 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)), @@ -6843,7 +6860,7 @@ fn render_frame( } else if tries && turned.is_none() && locked_at.is_none() - && let Some((left, top, right, bottom)) = area_labels::around(ctx, g, shown, !own_seen) + && let Some((left, top, right, bottom)) = ringed(!own_seen).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| { diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 0891cb0e8b..89163a6a1b 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -826,11 +826,12 @@ fn off_a_polygons_label_does_not_go_round_it() { #[test] fn places_off_the_view_are_not_tried_round_a_polygon() { - // The whole view inside the polygon. - let (mut m, _) = map(Geometry::Polygon(vec![big()]), true); - let mut v = view(); - v.camera.res = 50.0; - assert_eq!(every_place(&mut m, &v).len(), 1); + 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] @@ -980,3 +981,19 @@ fn a_lock_round_a_polygon_stays_as_its_part_in_view_changes() { 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:?}"); +} diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index fc1201ec3f..cc5e0fb27b 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -804,15 +804,16 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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. 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 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; + 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 that part when its name doesn't + fit it. 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 From 9b5743fce7f9f6af09bef4787b3b186d151bfcf7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 17:02:44 -0500 Subject: [PATCH 6/9] test(labels): pin one thinning of a polygon label's rings per clip --- crates/render/src/area_labels.rs | 4 ++++ crates/render/src/polygon_labels_tests.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index 09ece5d2d8..8bdb6d6457 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -405,6 +405,8 @@ pub(super) fn shown_rings( 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 @@ -453,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/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 89163a6a1b..36e34f5226 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -997,3 +997,16 @@ fn a_lock_round_a_polygon_holds_once_the_polygon_leaves_the_view() { 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() { + for (rings, v, most) in [(small(), view(), 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); + } +} From 0c707c100cdc8cfc9c43cbec8d06e757ebe7dde2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 17:32:04 -0500 Subject: [PATCH 7/9] test(labels): leave room for the place outside in any font --- crates/render/src/polygon_labels_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 36e34f5226..7438b38490 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -838,8 +838,9 @@ fn places_off_the_view_are_not_tried_round_a_polygon() { fn a_visible_parts_label_goes_beside_its_polygon_where_the_view_has_room() { 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. - let v = view_at(1.341, 0.0); + // Only a strip of the polygon's east side in view, 50 points wide: narrower than the name, + // and wide enough that, in any font, a blocker inside it leaves the place outside free. + let v = view_at(1.3144, 0.0); let taken = every_place(&mut m, &v); assert_eq!(taken.len(), 2, "{taken:?}"); // The one place round the part in view that is in view: right of its east edge. From 069d85e7d7045fba097ee0ee04470a57c7e2ab0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 17:49:30 -0500 Subject: [PATCH 8/9] fix(labels): go round the box of the whole part, not of what is in view --- crates/render/src/lib.rs | 9 +++-- crates/render/src/polygon_labels_tests.rs | 45 +++++++++-------------- docs/user-guide/cartography.md | 3 +- 3 files changed, 24 insertions(+), 33 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 62929bdb10..63d11020fc 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6286,6 +6286,7 @@ fn render_frame( // 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) @@ -6790,8 +6791,8 @@ fn render_frame( }; // 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, - // for the search inside and the box round it alike. + // 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() @@ -6801,7 +6802,7 @@ fn render_frame( // 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) => { @@ -6860,7 +6861,7 @@ fn render_frame( } else if tries && turned.is_none() && locked_at.is_none() - && let Some((left, top, right, bottom)) = ringed(!own_seen).and_then(|r| area_labels::around(r)) + && 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| { diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 7438b38490..2e08090ed3 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -108,7 +108,7 @@ fn small() -> Vec { } /// The letter spacing that makes "Lake" wider than a small polygon. -const WIDE: f32 = 10.0; +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) { @@ -787,15 +787,19 @@ fn on_the_globe_a_line_is_labelled_along_its_visible_stretch_only() { #[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, _) = islet(small(), true); + 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 around = screen_box(&v, &small()); - let sides: Vec<_> = taken.iter().map(|&p| side(around, p)).filter(|&s| s != INSIDE).collect(); - assert_eq!(sides, ROUND, "turned {bearing}, tilted {pitch}: {taken:?} round {around:?}"); + 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:?}"); } } @@ -835,17 +839,12 @@ fn places_off_the_view_are_not_tried_round_a_polygon() { } #[test] -fn a_visible_parts_label_goes_beside_its_polygon_where_the_view_has_room() { +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, 50 points wide: narrower than the name, - // and wide enough that, in any font, a blocker inside it leaves the place outside free. - let v = view_at(1.3144, 0.0); - let taken = every_place(&mut m, &v); - assert_eq!(taken.len(), 2, "{taken:?}"); - // The one place round the part in view that is in view: right of its east edge. - let (_, _, right, _) = screen_box(&v, &big()[0]); - assert!(taken[1].0 > right && (0.0..=800.0).contains(&taken[1].0) && (0.0..=600.0).contains(&taken[1].1), "{taken:?} {right}"); + // 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] @@ -871,18 +870,6 @@ fn on_the_globe_a_label_goes_round_its_polygon_in_view() { assert!(!near((x, y), here) && (0.0..=800.0).contains(&x) && (0.0..=600.0).contains(&y), "{here:?} {:?}", (x, y)); } -#[test] -fn a_label_moved_by_hand_does_not_go_round_its_polygon() { - let (mut m, id) = map(Geometry::Polygon(vec![u()]), true); - let fid = m.layer(id).unwrap().dataset.features.first().unwrap().id; - m.layer_mut(id).unwrap().labels.default.moved = vec![rustgis_map::symbology::MovedLabel { id: fid, at: [0.0, 0.1] }]; - let v = view(); - // Placed before every other label: only a blocker moved over it could crowd it, and it stays. - let first = one(&mut m, &v); - block(&mut m, &v, &[first]); - assert!(near(one(&mut m, &v), first)); -} - #[test] fn a_label_turned_by_an_expression_does_not_go_round_its_polygon() { let (mut m, id) = islet(small(), true); @@ -1003,7 +990,11 @@ fn a_lock_round_a_polygon_holds_once_the_polygon_leaves_the_view() { /// 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() { - for (rings, v, most) in [(small(), view(), 1), (small(), view_at(0.3643, 0.0), 2), (big()[0].clone(), east(), 2)] { + // 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(); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index cc5e0fb27b..20af3425fc 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -812,8 +812,7 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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 that part when its name doesn't - fit it. On a multipolygon this is the part its label is for; + 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 From 7487a91f34d5a1cd80963088de373750d1b6a800 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 17:50:31 -0500 Subject: [PATCH 9/9] docs(map): say a lock keeps anchors for places round a polygon too --- crates/map/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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.