From d8313cfc0298f8e645942afd6c36087676f3c268 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 15:09:43 -0500 Subject: [PATCH 01/11] feat(labels): try a polygon's pole of inaccessibility first, from labels.placement and the pane --- crates/data/src/geometry.rs | 9 + crates/engine/src/cmd/labels.rs | 33 +-- crates/engine/src/tests.rs | 59 +++++- crates/map/src/symbology.rs | 3 +- crates/render/src/area_labels.rs | 8 + crates/render/src/lib.rs | 32 ++- crates/render/src/polygon_labels_tests.rs | 247 ++++++++++++++++++++++ crates/tiles/src/symbols.rs | 2 +- crates/ui-egui/src/labelpane.rs | 54 +++++ docs/user-guide/cartography.md | 9 + 10 files changed, 426 insertions(+), 30 deletions(-) create mode 100644 crates/render/src/polygon_labels_tests.rs diff --git a/crates/data/src/geometry.rs b/crates/data/src/geometry.rs index faa7df5a06..ec1961e065 100644 --- a/crates/data/src/geometry.rs +++ b/crates/data/src/geometry.rs @@ -310,6 +310,15 @@ impl Geometry { false } + /// The part of a polygon [`label_point`](Self::label_point) places its point in: the largest + /// valid one. `None` for other geometries. + pub fn label_part(&self) -> Option<&Vec>> { + match self { + Geometry::Polygon(polys) => largest_part(polys), + _ => None, + } + } + /// A point for a label or a pop-up: the point itself, the middle vertex of the longest line /// part, or the centroid of the largest valid polygon (moved inside it if the centroid falls out). /// diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 3442a0bbd2..d096768da4 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -275,7 +275,8 @@ pub fn commands() -> Vec { // `to: null`: this call takes the line away. let clears = matches!(to, Some(None)); let id = s.layer_id(p)?; - let (points, lines) = points_and_lines(s.map().layer(id).ok_or("no such layer")?); + let held = held_geometries(s.map().layer(id).ok_or("no such layer")?); + let lines = held.1; let guide = label_guide(s, p, s.map().layer(id).ok_or("no such layer")?)?; // A repeat or line offset given where it does nothing (not along a line), kept for // when the class is placed along one, and said (#2639). @@ -344,8 +345,8 @@ pub fn commands() -> Vec { } // Asked of the class as this call leaves it, so a position or a repeat given with // it counts. On where it would do nothing is refused; off is taken anywhere. - if others == Some(true) && !tries_other_places(points, lines, c) { - return Err("otherPositions is for points, and for lines placed parallel or curved without a repeat".into()); + if others == Some(true) && !tries_other_places(held, c) { + return Err("otherPositions is for points, for polygons whose labels aren't curved or along a guide, and for lines placed parallel or curved without a repeat".into()); } if !(lines && c.placement.along_line()) { if repeat.is_some_and(|r| r.is_some()) { @@ -429,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; true is refused for any other line label and on polygons), "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 to the point inside it farthest from its edges, 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)}"#, ), // 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| { @@ -598,10 +599,10 @@ pub fn commands() -> Vec { ] } -/// Whether the layer holds points and lines: declared so, or among its features, as the renderer +/// Whether the layer holds points, lines and polygons: declared so, or among its features, as the renderer /// goes by each feature's geometry. -fn points_and_lines(l: &Layer) -> (bool, bool) { - (l.has_geometry(GeometryType::Point), l.has_geometry(GeometryType::Polyline)) +fn held_geometries(l: &Layer) -> (bool, bool, bool) { + (l.has_geometry(GeometryType::Point), l.has_geometry(GeometryType::Polyline), l.has_geometry(GeometryType::Polygon)) } /// `labels.placement`'s `to`: the line or polygon layer a perpendicular label is square to, by @@ -665,11 +666,14 @@ fn label_guide(s: &Session, p: &Value, labelled: &Layer) -> Result bool { - points || (lines && c.placement.along_line() && c.repeat.is_none()) +fn tries_other_places((points, lines, polygons): (bool, bool, bool), c: &LabelClass) -> bool { + points + || (lines && c.placement.along_line() && c.repeat.is_none()) + || (polygons && c.placement != LabelPlacement::Curved && c.guide.is_none()) } /// `labels.by`: sets a label class's expressions, each checked against the layer's fields. @@ -776,16 +780,17 @@ pub(crate) fn lock_holds(l: &Layer, b: &Labeling) -> bool { /// Whether the layer's classes and those of `b` (listed alike) put their labels in the same places. /// A lock names the place round its point or along its line a label took by its number among its -/// class's (#1011, #1187), so another position, or trying the others turned on or off, locks the +/// class's (#1011, #1187, #3268), so another position, or trying the others turned on or off, locks the /// labels again; with no class trying them a new position keeps the lock, as before. The flag only /// counts where it has an effect: kept on a line's class at a position off the line, or with a /// repeat, it does nothing ([`tries_other_places`]). Along a line, off it, each place is tried on /// both sides, the label's own first: its number says which, so the other side, or a distance /// where there was none, locks the labels again too; another distance on the same side doesn't. fn same_places(l: &Layer, b: &Labeling) -> bool { - let (points, lines) = points_and_lines(l); + let held = held_geometries(l); + let lines = held.1; let classes = |labels: &Labeling| { - let tries = |c: &LabelClass| c.other_positions && tries_other_places(points, lines, c); + let tries = |c: &LabelClass| c.other_positions && tries_other_places(held, c); // -1 below, 1 above, 0 on the line (-0.0 too). let side = |c: &LabelClass| { if lines && c.placement.along_line() { i8::from(c.line_offset > 0.0) - i8::from(c.line_offset < 0.0) } else { 0 } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 49fd20805d..78820b3024 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9564,8 +9564,8 @@ fn converting_labels_along_lines_says_what_they_lose() { /// A point label class tries the other places round its point when told to (#1011): alone it keeps /// the position, junk is refused (in it or in the position) and so is turning it on for lines at a -/// position off them and for polygons, it undoes, the project keeps it, and turning it on or off -/// while the labels are locked locks them again (the places they took no longer stand). +/// position off them, it undoes, the project keeps it, and turning it on or off while the labels +/// are locked locks them again (the places they took no longer stand). #[test] fn labels_take_other_positions_round_points() { use crate::render::View; @@ -9591,12 +9591,11 @@ fn labels_take_other_positions_round_points() { assert!(!class(&s).0); s.run("labels.placement", &json!({"layer": "Cities", "position": null, "otherPositions": false})).unwrap(); assert_eq!(class(&s), (false, placement), "null is no position"); - // Only a point's label goes round it: on is refused for a line off its line (along it, see - // labels_take_other_positions_along_lines) and for polygons, off taken anywhere. - for layer in ["Rivers", "Countries"] { - assert!(s.run("labels.placement", &json!({"layer": layer, "otherPositions": true})).is_err(), "{layer}"); - s.run("labels.placement", &json!({"layer": layer, "otherPositions": false})).unwrap(); - } + // On is refused for a line off its line (along it, see + // labels_take_other_positions_along_lines; polygons, labels_take_other_positions_in_polygons), + // off taken anywhere. + assert!(s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": true})).is_err()); + s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": false})).unwrap(); s.run("labels.placement", &json!({"layer": "Cities", "otherPositions": true})).unwrap(); let text = serde_json::to_string(&s.project).unwrap(); assert!(Session::new(serde_json::from_str(&text).unwrap()).map().layer_by_name("Cities").unwrap().labels.default.other_positions); @@ -9614,6 +9613,47 @@ fn labels_take_other_positions_round_points() { assert!(s.map().label_lock.is_none(), "turned on: locked again"); } +/// A polygon label class tries its pole of inaccessibility when told to (#3268): at any position +/// but curved, and without a guide. A refusal changes nothing, it undoes, the project keeps it, and +/// turning it on or off locks the labels again. +#[test] +fn labels_take_other_positions_in_polygons() { + use crate::render::View; + let mut s = world(); + let id = s.map().layer_by_name("Countries").unwrap().id; + let on = |s: &Session| s.map().layer(id).unwrap().labels.default.other_positions; + assert!(!on(&s)); + s.run("labels.placement", &json!({"layer": id, "otherPositions": true})).unwrap(); + assert!(on(&s)); + s.run("edit.undo", &json!({})).unwrap(); + assert!(!on(&s), "undoes"); + for position in ["center", "above", "parallel"] { + s.run("labels.placement", &json!({"layer": id, "position": position, "otherPositions": true})).unwrap(); + s.run("labels.placement", &json!({"layer": id, "otherPositions": false})).unwrap(); + } + s.run("labels.placement", &json!({"layer": id, "position": "auto"})).unwrap(); + assert!(s.run("labels.placement", &json!({"layer": id, "position": "curved", "otherPositions": true})).is_err()); + let guide = json!({"layer": "Rivers"}); + assert!(s.run("labels.placement", &json!({"layer": id, "guide": guide, "otherPositions": true})).is_err()); + let class = &s.map().layer(id).unwrap().labels.default; + assert!(!class.other_positions && class.guide.is_none() && class.placement == rustgis_map::LabelPlacement::Auto, "nothing changes"); + for position in ["curved", "auto"] { + s.run("labels.placement", &json!({"layer": id, "position": position, "otherPositions": false})).unwrap(); + } + s.run("labels.placement", &json!({"layer": id, "otherPositions": true})).unwrap(); + let text = serde_json::to_string(&s.project).unwrap(); + assert!(on(&Session::new(serde_json::from_str(&text).unwrap()))); + s.run("labels.enable", &json!({"layer": id, "on": true})).unwrap(); + let v = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false }; + for turn in [false, true] { + s.run("labels.lock", &json!({"on": true})).unwrap(); + crate::render::render(s.map_mut(), &v).unwrap(); + assert!(s.map().label_lock.is_some()); + s.run("labels.placement", &json!({"layer": id, "otherPositions": turn})).unwrap(); + assert!(s.map().label_lock.is_none(), "turned {turn}: locked again"); + } +} + /// A line label class tries other places along its line when told to (#1187): only placed parallel /// or curved and without a repeat, judged on what the call leaves, in the class it names. A refusal /// changes nothing, a later position or repeat keeps the flag, it undoes, the project keeps it, and @@ -9654,9 +9694,6 @@ fn labels_take_other_positions_along_lines() { for bad in [json!("yes"), json!(1), Value::Null] { assert!(s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": bad})).is_err(), "{bad}"); } - // Polygons have no such places, even placed parallel. - assert!(s.run("labels.placement", &json!({"layer": "Countries", "position": "parallel", "otherPositions": true})).is_err()); - s.run("labels.placement", &json!({"layer": "Countries", "otherPositions": false})).unwrap(); // Judged in the class named, not in Default; a class that isn't there is refused. s.run("labels.placement", &json!({"layer": "Rivers", "position": "above", "otherPositions": false})).unwrap(); s.run("labels.class.add", &json!({"layer": "Rivers", "name": "Big"})).unwrap(); diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 3c6bfe4e75..49c1b527a2 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2728,7 +2728,8 @@ pub struct LabelClass { #[serde(default)] 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. + /// round a point ([`LabelPlacement::alternatives`]), or along a non-repeated line. A polygon's + /// goes first to the point inside it farthest from its edges (#3268). /// 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 300abd3bf4..50fbdb2d8e 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -337,6 +337,14 @@ pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec>]) -> O .collect() } +/// The point of `g`'s label part farthest from its edges on the screen (#3268), to about a point, +/// from its rings thinned as [`screen_rings`] thins them. `None` for no polygon, one with no area +/// near the view or one with a place behind the globe. +pub(super) fn pole(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry) -> Option<(f32, f32)> { + let rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; + rustgis_tiles::symbols::pole_of_inaccessibility(&rings, 1.0) +} + /// [`glyphs`]' characters `advances` wide and `height` tall, as [`Line::curved`] takes them. fn curved( ctx: &super::Ctx<'_>, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d882334ae9..8710b7dbf6 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6173,15 +6173,17 @@ fn render_frame( let (bw, bh) = (text::spaced_block_width(&text, csize, face, class.spacing), text::block_height(&text, csize)); // Where a placement puts it, moved as its class says (points, as the // text's size), unless along a line. - let place = |p: LabelPlacement| { + let place_at = |(x, y): (f32, f32), p: LabelPlacement| { let (dx, dy) = p.offset(bw, bh, marker, is_point); let (dx, dy) = ((dx + class.offset[0] * 1.33) * label_factor, (dy + class.offset[1] * 1.33) * label_factor); - (x as f32 + dx, y as f32 + dy) + (x + dx, y + dy) }; + let place = |p: LabelPlacement| place_at((x as f32, y as f32), p); // Where it goes, each with its repeat's index: by its feature (0), or along // a line at its middle and, repeated, every so far either side. let mut places: Vec<(usize, f32, f32, Option, Vec)> = Vec::new(); let mut curves = None; + // (A polygon's too: its label point, after its pole.) let mut line_alternatives = Vec::new(); let mut line_places = None; // Turned square to a line: no other places round its point. @@ -6521,7 +6523,28 @@ fn render_frame( .filter(|a| *a != 0.0) .map(|a| rustgis_tiles::symbols::upright(a.to_radians())) .filter(|a| *a != 0.0); - places.push((0, lx, ly, turned, Vec::new())); + // A polygon's label trying other places (#3268) goes to its pole of + // inaccessibility first, then here. A curved or guided one has its own + // course, which this is only what's left of. + let pole = (class.other_positions + && moved.is_none() + && class.guide.is_none() + && class.placement != LabelPlacement::Curved) + .then(|| area_labels::pole(ctx, g)) + .flatten() + // Out of view it isn't tried, so View Unplaced shows the label here. + // Locked, it is: the lock names a place by its number, the pole's + // first, and an unseen place is passed over as the lock is taken. + .filter(|&(px, py)| { + display.locked || ((0.0..=vw).contains(&f64::from(px)) && (0.0..=vh).contains(&f64::from(py))) + }); + if let Some(pole) = pole { + let (px, py) = place_at(pole, class.placement); + places.push((0, px, py, turned, Vec::new())); + line_alternatives.push(LabelPlace { x: lx, y: ly, angle: turned, glyphs: Vec::new() }); + } else { + places.push((0, lx, ly, turned, Vec::new())); + } } // Heavier classes first (#2803; labels moved by hand before all of them, // so the others keep off them), then, among equals, layers above, the @@ -16756,3 +16779,6 @@ mod lod_tests; #[cfg(test)] mod line_positions_tests; + +#[cfg(test)] +mod polygon_labels_tests; diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs new file mode 100644 index 0000000000..8e0555175f --- /dev/null +++ b/crates/render/src/polygon_labels_tests.rs @@ -0,0 +1,247 @@ +//! A polygon's label trying other places (#3268): its pole of inaccessibility first, then where +//! it goes without the setting. + +use super::*; +use rustgis_data::{Dataset, Field, FieldType, Value}; +use rustgis_map::{Camera, LabelPlacement}; + +fn c(x: f64, y: f64) -> Coord { + Coord::new(x, y) +} + +fn ring(points: &[(f64, f64)]) -> Vec { + points.iter().chain(points.first()).map(|&(x, y)| c(x, y)).collect() +} + +/// A U open to the north, in degrees: arms and base 0.1 wide. Its label point is in the widest +/// span, the base's, against its south edge; its pole is in a corner of the base, farther in. +fn u() -> Vec> { + vec![ring(&[(-0.25, -0.2), (0.25, -0.2), (0.25, 0.2), (0.15, 0.2), (0.15, -0.1), (-0.15, -0.1), (-0.15, 0.2), (-0.25, 0.2)])] +} + +fn square(x: f64, y: f64, half: f64) -> Vec { + ring(&[(x - half, y - half), (x + half, y - half), (x + half, y + half), (x - half, y + half)]) +} + +/// A map with one polygon layer labelled "Lake", trying other places when `on`. +fn map(geometry: Geometry, on: bool) -> (Map, u32) { + let mut m = Map::new("Map"); + let mut d = Dataset::new("areas", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + d.push(Some(geometry), vec![Value::Text("Lake".into())]); + let id = m.add_dataset(d); + if let Some(l) = m.layer_mut(id) { + l.labels.enabled = true; + l.labels.default.other_positions = on; + } + (m, id) +} + +fn view_at(lon: f64, lat: f64) -> View { + let camera = Camera { center: lonlat_to_merc(c(lon, lat)), res: 100.0, bearing: 0.0, pitch: 0.0 }; + View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false } +} + +fn view() -> View { + view_at(0.0, 0.0) +} + +fn places(m: &mut Map, v: &View) -> Vec<(f32, f32)> { + render(m, v).unwrap().labels.into_iter().filter(|l| l.text == "Lake").map(|l| (l.x, l.y)).collect() +} + +fn one(m: &mut Map, v: &View) -> (f32, f32) { + let p = places(m, v); + assert_eq!(p.len(), 1, "{p:?}"); + p[0] +} + +/// The longitude and latitude under a place on the screen. +fn at(v: &View, (x, y): (f32, f32)) -> Coord { + rustgis_geom::merc_to_lonlat(v.camera.to_map(f64::from(x), f64::from(y), v.width, v.height)) +} + +/// How far, in degrees, the place is from the nearest edge, negative outside the polygon. +fn depth(rings: &[Vec], p: Coord) -> f64 { + let mut inside = false; + let mut best = f64::INFINITY; + for r in rings { + for w in r.windows(2) { + let (a, b) = (w[0], w[1]); + if (a.y > p.y) != (b.y > p.y) && p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x { + inside = !inside; + } + let (dx, dy) = (b.x - a.x, b.y - a.y); + let t = (((p.x - a.x) * dx + (p.y - a.y) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + best = best.min((p.x - a.x - t * dx).hypot(p.y - a.y - t * dy)); + } + } + if inside { best } else { -best } +} + +/// 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)]) { + 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())]); + } + let id = m.add_dataset(d); + if let Some(l) = m.layer_mut(id) { + l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol { size: 1.0, ..l.symbol(0) }); + l.labels.enabled = true; + l.labels.default.placement = LabelPlacement::Center; + l.labels.default.weight = 10; + } +} + +/// 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())); + (x as f32, y as f32) +} + +fn near(a: (f32, f32), b: (f32, f32)) -> bool { + (a.0 - b.0).hypot(a.1 - b.1) < 1.0 +} + +#[test] +fn off_a_polygons_label_stays_at_its_label_point() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), false); + let v = view(); + assert!(near(one(&mut m, &v), today(&v, &g))); +} + +#[test] +fn on_it_goes_to_the_point_farthest_from_the_edges() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let placed = one(&mut m, &v); + assert!(!near(placed, today(&v, &g)), "{placed:?}"); + // The widest circle fits a corner of the base, radius 0.0586; an arm's is 0.05. + let d = depth(&u(), at(&v, placed)); + assert!(d > 0.054, "{d}"); +} + +#[test] +fn with_its_pole_taken_it_goes_to_its_label_point() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + block(&mut m, &v, &[pole]); + assert!(near(one(&mut m, &v), today(&v, &g))); +} + +#[test] +fn with_both_taken_it_is_unplaced_once_at_its_pole() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + block(&mut m, &v, &[pole, today(&v, &g)]); + m.label_display.show_unplaced = true; + let r = render(&mut m, &v).unwrap(); + assert!(r.labels.iter().all(|l| l.text != "Lake")); + let unplaced: Vec<_> = r.unplaced.iter().filter(|l| l.text == "Lake").map(|l| (l.x, l.y)).collect(); + assert_eq!(unplaced.len(), 1); + assert!(near(unplaced[0], pole), "{unplaced:?} {pole:?}"); +} + +#[test] +fn a_polygons_pole_keeps_out_of_its_hole() { + // A ring wider on the west: the hole is off centre. + let rings = vec![square(0.0, 0.0, 0.2), square(0.05, 0.0, 0.1)]; + let (mut m, _) = map(Geometry::Polygon(vec![rings.clone()]), true); + let v = view(); + let d = depth(&rings, at(&v, one(&mut m, &v))); + assert!(d > 0.065, "in the wide side, away from the hole: {d}"); +} + +#[test] +fn a_multipolygons_pole_is_in_the_part_its_label_point_picks() { + let g = Geometry::Polygon(vec![vec![square(0.33, 0.2, 0.03)], u()]); + let (mut m, _) = map(g, true); + let v = view(); + let d = depth(&u(), at(&v, one(&mut m, &v))); + assert!(d > 0.054, "{d}"); +} + +#[test] +fn a_polygon_without_area_keeps_its_label_point() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let v = view(); + let off = places(&mut map(g.clone(), false).0, &v); + assert_eq!(places(&mut map(g, true).0, &v), off); +} + +#[test] +fn a_label_moved_by_hand_stays_where_it_was_put() { + let (mut m, id) = map(Geometry::Polygon(vec![u()]), true); + let fid = m.layer(id).unwrap().dataset.features.get(0).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(); + let placed = at(&v, one(&mut m, &v)); + assert!((placed.x - 0.0).abs() < 2e-3 && (placed.y - 0.1).abs() < 2e-3, "{placed:?}"); +} + +#[test] +fn a_curved_label_has_no_pole() { + let g = Geometry::Polygon(vec![u()]); + let v = view(); + let render_curved = |on: bool| { + let (mut m, id) = map(g.clone(), on); + // A name too long for the centre line falls back to a straight label. + let l = m.layer_mut(id).unwrap(); + l.labels.default.placement = LabelPlacement::Curved; + render(&mut m, &v).unwrap().labels.into_iter().map(|l| (l.x, l.y)).collect::>() + }; + assert_eq!(render_curved(true), render_curved(false)); +} + +#[test] +fn a_lock_keeps_the_place_each_polygon_label_took() { + let g = Geometry::Polygon(vec![u()]); + for taken in [false, true] { + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + if taken { + block(&mut m, &v, &[pole]); + } + m.label_display.locked = true; + let before = at(&v, one(&mut m, &v)); + let kept = m.label_lock.as_ref().unwrap().iter().find(|(_, place)| place.place == u8::from(taken)); + assert!(kept.is_some(), "{:?}", m.label_lock); + let moved = view_at(0.03, 0.02); + 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:?}"); + } +} + +/// With its pole out of view a label is at its label point, as without the setting, and a lock +/// taken then keeps it there when the pole comes into view. +#[test] +fn a_pole_out_of_view_leaves_the_label_at_its_label_point() { + let g = Geometry::Polygon(vec![u()]); + // The pole is above this view; the label point is inside it. + let low = view_at(0.0, -0.435); + let (mut m, _) = map(g.clone(), true); + assert!(near(one(&mut m, &low), today(&low, &g))); + m.label_display.locked = true; + assert!(near(one(&mut m, &low), today(&low, &g))); + let v = view(); + assert!(near(one(&mut m, &v), today(&v, &g)), "locked, it stays"); +} + +#[test] +fn turned_and_tilted_views_place_the_pole() { + let g = Geometry::Polygon(vec![u()]); + for (bearing, pitch) in [(30.0, 0.0), (0.0, 30.0)] { + let mut v = view(); + (v.camera.bearing, v.camera.pitch) = (bearing, pitch); + let off = one(&mut map(g.clone(), false).0, &v); + let on = one(&mut map(g.clone(), true).0, &v); + assert!(!near(on, off), "turned {bearing}, tilted {pitch}: {on:?}"); + } +} diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index 84c244d322..aa530f0a63 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -554,7 +554,7 @@ fn signed_area(r: &[(f32, f32)]) -> f32 { /// The point inside a polygon (outer ring, then holes) farthest from its edges, to within /// `precision` (after Mapbox's polylabel, ISC; see `INCLUDED` in `xtask/src/notices.rs`): where a /// label sits best in an area. `None` for a polygon with no area. -pub(crate) fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Option<(f32, f32)> { +pub fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Option<(f32, f32)> { let outer = poly.first()?; let (mut x0, mut y0, mut x1, mut y1) = (f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for p in outer.iter().filter(|p| p.0.is_finite() && p.1.is_finite()) { diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 00f999eebc..e591b39b75 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -881,6 +881,16 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { } square_to(app, ui, l, c); } + // Polygons: their pole of inaccessibility, tried before the label's own place (#3268). Not for + // a label curved or along a guide, whose course is its place. + if l.geometry_type() == rustgis_engine::data::GeometryType::Polygon && cur != LabelPlacement::Curved && c.it.guide.is_none() { + ui.add_space(4.0); + let mut on = c.it.other_positions; + let help = tl!("The label goes to the point inside the polygon farthest from its edges; 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() { + run(app, "labels.placement", c.params(json!({"otherPositions": on}))); + } + } // Lines: the text along them, straight or bending with them. if l.geometry_type() == rustgis_engine::data::GeometryType::Polyline { ui.add_space(4.0); @@ -1620,6 +1630,50 @@ mod tests { assert!(h.query_by_role_and_label(Role::CheckBox, BOX).is_none(), "not for polygons"); } + /// A polygon layer's labels can try other places inside their polygons (#3268): the box is + /// there but for a curved label or one along a guide, it undoes, and hiding it keeps what it was + /// set to. + #[test] + fn other_positions_are_set_in_the_pane_for_polygons() { + use egui::accesskit::Role; + const BOX: &str = "Try other places inside the polygon"; + let mut h = harness(with_cities()); + h.run(); + let countries = layer_id(h.state(), "Countries"); + h.state_mut().session.run("layer.select", &json!({"layer": countries})).unwrap(); + h.run(); + open_tab(&mut h, "Position"); + let on = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.state().session.map().layer_by_name("Countries").unwrap().labels.default.other_positions + }; + assert!(!on(&h)); + h.get_by_role_and_label(Role::CheckBox, BOX).click(); + h.run(); + assert!(on(&h)); + h.state_mut().session.run("edit.undo", &json!({})).unwrap(); + h.run(); + assert!(!on(&h)); + h.get_by_role_and_label(Role::CheckBox, BOX).click(); + h.run(); + for change in [json!({"position": "curved"}), json!({"position": "auto", "guide": {"layer": "Rivers"}})] { + let mut p = change.clone(); + p["layer"] = json!(countries); + h.state_mut().session.run("labels.placement", &p).unwrap(); + h.run(); + assert!(h.query_by_role_and_label(Role::CheckBox, BOX).is_none(), "{change}"); + assert!(on(&h), "hidden, it's kept"); + } + h.state_mut().session.run("labels.placement", &json!({"layer": countries, "guide": null})).unwrap(); + h.run(); + h.get_by_role_and_label(Role::CheckBox, BOX).click(); + h.run(); + assert!(!on(&h)); + let cities = layer_id(h.state(), "Cities"); + h.state_mut().session.run("layer.select", &json!({"layer": cities})).unwrap(); + h.run(); + assert!(h.query_by_role_and_label(Role::CheckBox, BOX).is_none(), "not for points"); + } + /// A point's label placed square to a line (#2263) is chosen in the pane, starting on a line /// layer of the map, and shows as chosen however it was set. #[test] diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 1478f3f7bc..423b531bab 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -764,6 +764,15 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: take the place a less important one had. The class's offset applies to every place, and Lock keeps the place each label took (`labels.placement={"layer": "Cities", "otherPositions": true}`). +- **Other places inside polygons**: a polygon's label goes to the point inside it farthest from + its edges, as seen on the screen, so a name sits in the body of a lake or bay rather than against + a shore. Where another label takes that point, 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. Not for Curved labels or labels along a guide, where the box is hidden and the + setting does nothing. Off by default, as round points; the class's offset applies to both places, + 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, nearest the middle first, and goes to the first that will do (Labeling pane › Position › Along From d0dbb1ee58a9e245bbb77f75ce284d3199794f44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 15:20:58 -0500 Subject: [PATCH 02/11] style(labels): format, clippy and review wording for polygon label places --- crates/engine/src/cmd/labels.rs | 4 ++-- crates/render/src/polygon_labels_tests.rs | 4 ++-- crates/ui-egui/src/labelpane.rs | 3 ++- docs/user-guide/cartography.md | 5 +++-- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index d096768da4..b2beeaaf25 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -276,7 +276,7 @@ pub fn commands() -> Vec { let clears = matches!(to, Some(None)); let id = s.layer_id(p)?; let held = held_geometries(s.map().layer(id).ok_or("no such layer")?); - let lines = held.1; + let (_, lines, _) = held; let guide = label_guide(s, p, s.map().layer(id).ok_or("no such layer")?)?; // A repeat or line offset given where it does nothing (not along a line), kept for // when the class is placed along one, and said (#2639). @@ -788,7 +788,7 @@ pub(crate) fn lock_holds(l: &Layer, b: &Labeling) -> bool { /// where there was none, locks the labels again too; another distance on the same side doesn't. fn same_places(l: &Layer, b: &Labeling) -> bool { let held = held_geometries(l); - let lines = held.1; + let (_, lines, _) = held; let classes = |labels: &Labeling| { let tries = |c: &LabelClass| c.other_positions && tries_other_places(held, c); // -1 below, 1 above, 0 on the line (-0.0 too). diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 8e0555175f..0814cb5e38 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -178,7 +178,7 @@ fn a_polygon_without_area_keeps_its_label_point() { #[test] fn a_label_moved_by_hand_stays_where_it_was_put() { let (mut m, id) = map(Geometry::Polygon(vec![u()]), true); - let fid = m.layer(id).unwrap().dataset.features.get(0).unwrap().id; + 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(); let placed = at(&v, one(&mut m, &v)); @@ -191,7 +191,7 @@ fn a_curved_label_has_no_pole() { let v = view(); let render_curved = |on: bool| { let (mut m, id) = map(g.clone(), on); - // A name too long for the centre line falls back to a straight label. + // Along the centre line, or straight where it does not fit: the same either way. let l = m.layer_mut(id).unwrap(); l.labels.default.placement = LabelPlacement::Curved; render(&mut m, &v).unwrap().labels.into_iter().map(|l| (l.x, l.y)).collect::>() diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index e591b39b75..aa0bbac2bd 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -886,7 +886,8 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { if l.geometry_type() == rustgis_engine::data::GeometryType::Polygon && cur != LabelPlacement::Curved && c.it.guide.is_none() { ui.add_space(4.0); let mut on = c.it.other_positions; - let help = tl!("The label goes to the point inside the polygon farthest from its edges; if that is taken, where it goes without this."); + let help = + tl!("The label goes to the point inside the polygon farthest from its edges; 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() { run(app, "labels.placement", c.params(json!({"otherPositions": on}))); } diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 423b531bab..31344199bc 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -770,8 +770,9 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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. Not for Curved labels or labels along a guide, where the box is hidden and the - setting does nothing. Off by default, as round points; the class's offset applies to both places, - and Lock keeps the place each label took + setting does nothing. 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 (`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 3f64dabc2d524c36f324ac38fc36423465a98ef0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 15:33:52 -0500 Subject: [PATCH 03/11] fix(labels): place a polygon's label where its shape fits best, not at the largest circle --- crates/engine/src/cmd/labels.rs | 2 +- crates/map/src/symbology.rs | 2 +- crates/render/src/area_labels.rs | 19 +++++++---- crates/render/src/lib.rs | 8 ++--- crates/render/src/polygon_labels_tests.rs | 41 +++++++++++++++++++---- crates/ui-egui/src/labelpane.rs | 5 ++- docs/user-guide/cartography.md | 7 ++-- 7 files changed, 59 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index b2beeaaf25..68a3e48aca 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 to the point inside it farthest from its edges, 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; 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 49c1b527a2..b8eaf70671 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2729,7 +2729,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 to the point inside it farthest from its edges (#3268). + /// goes first where its shape fits best inside it (#3268). /// 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 50fbdb2d8e..8cf5903b56 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -337,12 +337,19 @@ pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec>]) -> O .collect() } -/// The point of `g`'s label part farthest from its edges on the screen (#3268), to about a point, -/// from its rings thinned as [`screen_rings`] thins them. `None` for no polygon, one with no area -/// near the view or one with a place behind the globe. -pub(super) fn pole(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry) -> Option<(f32, f32)> { - let rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; - rustgis_tiles::symbols::pole_of_inaccessibility(&rings, 1.0) +/// Where in `g`'s label part a label `aspect` times as wide as it is tall fits best on the screen +/// (#3268), to about a point, from its rings thinned as [`screen_rings`] thins them: the pole of +/// inaccessibility with the rings narrowed `aspect` times, so the centre of the largest ellipse of +/// that shape inside them. The largest circle's would put a wide name in a corner of a U or an L, +/// out over its side. `None` for no polygon, one with no area near the view or one with a place +/// behind the globe. +pub(super) fn pole(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry, aspect: f32) -> Option<(f32, f32)> { + let mut rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; + // 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)?; + Some((x * aspect, y)) } /// [`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 8710b7dbf6..02c8d512a3 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6523,14 +6523,14 @@ fn render_frame( .filter(|a| *a != 0.0) .map(|a| rustgis_tiles::symbols::upright(a.to_radians())) .filter(|a| *a != 0.0); - // A polygon's label trying other places (#3268) goes to its pole of - // inaccessibility first, then here. A curved or guided one has its own - // course, which this is only what's left of. + // A polygon's label trying other places (#3268) goes first where its + // shape fits best inside (a pole of inaccessibility), then here. A curved + // or guided one has its own course, which this is only what's left of. let pole = (class.other_positions && moved.is_none() && class.guide.is_none() && class.placement != LabelPlacement::Curved) - .then(|| area_labels::pole(ctx, g)) + .then(|| area_labels::pole(ctx, g, bw / bh)) .flatten() // Out of view it isn't tried, so View Unplaced shows the label here. // Locked, it is: the lock names a place by its number, the pole's diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 0814cb5e38..47c7b3be65 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -14,7 +14,7 @@ fn ring(points: &[(f64, f64)]) -> Vec { } /// A U open to the north, in degrees: arms and base 0.1 wide. Its label point is in the widest -/// span, the base's, against its south edge; its pole is in a corner of the base, farther in. +/// span, the base's, against its south edge; a name fits best half way up the base. fn u() -> Vec> { vec![ring(&[(-0.25, -0.2), (0.25, -0.2), (0.25, 0.2), (0.15, 0.2), (0.15, -0.1), (-0.15, -0.1), (-0.15, 0.2), (-0.25, 0.2)])] } @@ -25,9 +25,13 @@ fn square(x: f64, y: f64, half: f64) -> Vec { /// A map with one polygon layer labelled "Lake", trying other places when `on`. fn map(geometry: Geometry, on: bool) -> (Map, u32) { + named(geometry, on, "Lake") +} + +fn named(geometry: Geometry, on: bool, name: &str) -> (Map, u32) { let mut m = Map::new("Map"); let mut d = Dataset::new("areas", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); - d.push(Some(geometry), vec![Value::Text("Lake".into())]); + d.push(Some(geometry), vec![Value::Text(name.into())]); let id = m.add_dataset(d); if let Some(l) = m.layer_mut(id) { l.labels.enabled = true; @@ -118,9 +122,31 @@ fn on_it_goes_to_the_point_farthest_from_the_edges() { let v = view(); let placed = one(&mut m, &v); assert!(!near(placed, today(&v, &g)), "{placed:?}"); - // The widest circle fits a corner of the base, radius 0.0586; an arm's is 0.05. + // Half way across the base, which is 0.1 tall. let d = depth(&u(), at(&v, placed)); - assert!(d > 0.054, "{d}"); + assert!(d > 0.045, "{d}"); +} + +/// The place is the one the label's shape fits best, not the largest circle's: a wide name stays +/// whole inside a U or an L, whose largest circles sit in a corner. +#[test] +fn a_wide_name_stays_inside_its_polygon() { + let l = vec![ring(&[(-0.25, -0.2), (0.25, -0.2), (0.25, -0.1), (-0.1, -0.1), (-0.1, 0.2), (-0.25, 0.2)])]; + let name = "Horseshoe Lake"; + // Zoomed out: the arms and base are about as wide as half the name. + let mut v = view(); + v.camera.res = 200.0; + for rings in [u(), l] { + let (mut m, _) = named(Geometry::Polygon(vec![rings.clone()]), true, name); + let placed = render(&mut m, &v).unwrap().labels; + let p = placed.iter().find(|l| l.text == name).unwrap(); + let face = text::Face { bold: false, italic: false, serif: false, family: None }; + let (hw, hh) = (text::spaced_block_width(name, p.size, face, 0.0) / 2.0, text::block_height(name, p.size) / 2.0); + for (dx, dy) in [(-hw, -hh), (hw, -hh), (-hw, hh), (hw, hh)] { + let corner = at(&v, (p.x + dx, p.y + dy)); + assert!(depth(&rings, corner) > 0.0, "{corner:?} of the box at {:?}", (p.x, p.y)); + } + } } #[test] @@ -150,12 +176,13 @@ fn with_both_taken_it_is_unplaced_once_at_its_pole() { #[test] fn a_polygons_pole_keeps_out_of_its_hole() { - // A ring wider on the west: the hole is off centre. + // A ring with its hole off centre. let rings = vec![square(0.0, 0.0, 0.2), square(0.05, 0.0, 0.1)]; let (mut m, _) = map(Geometry::Polygon(vec![rings.clone()]), true); let v = view(); let d = depth(&rings, at(&v, one(&mut m, &v))); - assert!(d > 0.065, "in the wide side, away from the hole: {d}"); + // The widest bands round the hole are those north and south of it, 0.1 tall. + assert!(d > 0.045, "in a band, away from the hole: {d}"); } #[test] @@ -164,7 +191,7 @@ fn a_multipolygons_pole_is_in_the_part_its_label_point_picks() { let (mut m, _) = map(g, true); let v = view(); let d = depth(&u(), at(&v, one(&mut m, &v))); - assert!(d > 0.054, "{d}"); + assert!(d > 0.045, "{d}"); } #[test] diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index aa0bbac2bd..66c079e377 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -881,13 +881,12 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { } square_to(app, ui, l, c); } - // Polygons: their pole of inaccessibility, tried before the label's own place (#3268). Not for + // 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. if l.geometry_type() == rustgis_engine::data::GeometryType::Polygon && cur != LabelPlacement::Curved && c.it.guide.is_none() { ui.add_space(4.0); let mut on = c.it.other_positions; - let help = - tl!("The label goes to the point inside the polygon farthest from its edges; if that is taken, where it goes without this."); + 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() { run(app, "labels.placement", c.params(json!({"otherPositions": on}))); } diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 31344199bc..80883aff0a 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -764,9 +764,10 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: take the place a less important one had. The class's offset applies to every place, and Lock keeps the place each label took (`labels.placement={"layer": "Cities", "otherPositions": true}`). -- **Other places inside polygons**: a polygon's label goes to the point inside it farthest from - its edges, as seen on the screen, so a name sits in the body of a lake or bay rather than against - a shore. Where another label takes that point, it goes where it goes without this setting, and +- **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. Not for Curved labels or labels along a guide, where the box is hidden and the From fd3e76dc2b583037585c8b9e7a37217851511115 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 15:40:08 -0500 Subject: [PATCH 04/11] docs(render): say how closely a polygon label's place is searched --- crates/render/src/area_labels.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index 8cf5903b56..23c4e80a65 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -338,11 +338,12 @@ pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec>]) -> O } /// Where in `g`'s label part a label `aspect` times as wide as it is tall fits best on the screen -/// (#3268), to about a point, from its rings thinned as [`screen_rings`] thins them: the pole of -/// inaccessibility with the rings narrowed `aspect` times, so the centre of the largest ellipse of -/// that shape inside them. The largest circle's would put a wide name in a corner of a U or an L, -/// out over its side. `None` for no polygon, one with no area near the view or one with a place -/// behind the globe. +/// (#3268), from its rings thinned as [`screen_rings`] thins them: the pole of inaccessibility with +/// the rings narrowed `aspect` times, so the centre of the largest ellipse of that shape inside +/// them. The largest circle's would put a wide name in a corner of a U or an L, out over its side. +/// Searched in the narrowed rings, to about a point up and down and `aspect` points across (a +/// two-hundredth of a large polygon where that is coarser). `None` for no polygon, one with no area +/// near the view or one with a place behind the globe. pub(super) fn pole(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry, aspect: f32) -> Option<(f32, f32)> { let mut rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; // A text of no measurable shape counts as square; a very long or tall one as 20 to 1. From 960e7d162570f3a84e1be9e9c6f3a5db9b782493 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 15:48:02 -0500 Subject: [PATCH 05/11] fix(render): keep a locked polygon label when its frame has no place inside --- crates/engine/src/cmd/labels.rs | 4 +--- crates/map/src/symbology.rs | 6 ++++++ crates/render/src/lib.rs | 17 +++++++++-------- crates/render/src/polygon_labels_tests.rs | 15 +++++++++++++++ crates/ui-egui/src/labelpane.rs | 2 +- docs/user-guide/cartography.md | 4 ++-- 6 files changed, 34 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 68a3e48aca..c6361bff54 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -671,9 +671,7 @@ fn label_guide(s: &Session, p: &Value, labelled: &Layer) -> Result bool { - points - || (lines && c.placement.along_line() && c.repeat.is_none()) - || (polygons && c.placement != LabelPlacement::Curved && c.guide.is_none()) + points || (lines && c.placement.along_line() && c.repeat.is_none()) || (polygons && c.places_inside_polygons()) } /// `labels.by`: sets a label class's expressions, each checked against the layer's fields. diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index b8eaf70671..a4e859022d 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3573,6 +3573,12 @@ impl LabelPlacement { } impl LabelClass { + /// Whether this class's polygon labels have a place inside to try before their own (#3268): + /// not those curved or along a guide, whose course is their place. + pub fn places_inside_polygons(&self) -> bool { + self.placement != LabelPlacement::Curved && self.guide.is_none() + } + /// The Default class: on the first text field that looks like a name. pub fn default_for(ds: &Dataset) -> LabelClass { let field = ds diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 02c8d512a3..822f26b04e 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6526,10 +6526,11 @@ fn render_frame( // A polygon's label trying other places (#3268) goes first where its // shape fits best inside (a pole of inaccessibility), then here. A curved // or guided one has its own course, which this is only what's left of. - let pole = (class.other_positions + let tries = class.other_positions && moved.is_none() - && class.guide.is_none() - && class.placement != LabelPlacement::Curved) + && class.places_inside_polygons() + && matches!(g, Geometry::Polygon(_)); + let pole = tries .then(|| area_labels::pole(ctx, g, bw / bh)) .flatten() // Out of view it isn't tried, so View Unplaced shows the label here. @@ -6538,13 +6539,13 @@ fn render_frame( .filter(|&(px, py)| { display.locked || ((0.0..=vw).contains(&f64::from(px)) && (0.0..=vh).contains(&f64::from(py))) }); - if let Some(pole) = pole { - let (px, py) = place_at(pole, class.placement); - places.push((0, px, py, turned, Vec::new())); + // Here again as the place after the pole's, with a pole this frame or + // without, so a lock that took it second still finds it. + if tries { line_alternatives.push(LabelPlace { x: lx, y: ly, angle: turned, glyphs: Vec::new() }); - } else { - places.push((0, lx, ly, turned, Vec::new())); } + let (px, py) = pole.map_or((lx, ly), |pole| place_at(pole, class.placement)); + places.push((0, px, py, turned, Vec::new())); } // Heavier classes first (#2803; labels moved by hand before all of them, // so the others keep off them), then, among equals, layers above, the diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 47c7b3be65..e50aa14b49 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -272,3 +272,18 @@ fn turned_and_tilted_views_place_the_pole() { assert!(!near(on, off), "turned {bearing}, tilted {pitch}: {on:?}"); } } + +/// A lock that took the label point (place 1) still finds it in a frame with no pole, as with a +/// vertex behind the globe. +#[test] +fn a_lock_on_the_label_point_holds_without_a_pole() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let (mut m, _) = map(g, true); + let v = view(); + m.label_display.locked = true; + let at_lock = one(&mut m, &v); + for (_, place) in m.label_lock.as_mut().unwrap() { + place.place = 1; + } + assert!(near(one(&mut m, &v), at_lock)); +} diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 66c079e377..28b1b87356 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -883,7 +883,7 @@ fn position(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { } // 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. - if l.geometry_type() == rustgis_engine::data::GeometryType::Polygon && cur != LabelPlacement::Curved && c.it.guide.is_none() { + 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."); diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 80883aff0a..b2ae920a98 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -770,8 +770,8 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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. Not for Curved labels or labels along a guide, where the box is hidden and the - setting does nothing. Off by default, as round points; the class's position and offset apply from + without this. Not for Curved labels or labels along a guide, where the box is hidden, + turning the setting on is refused and one already on does nothing. 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 (`labels.placement={"layer": "Lakes", "otherPositions": true}`). From 2a7eef07dcae50184666f9bd0182353abb27906f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 16:28:18 -0500 Subject: [PATCH 06/11] fix(labels): keep the lock and fit polygon labels in turned, tilted and very long cases --- crates/engine/src/cmd/labels.rs | 4 +++- crates/engine/src/tests.rs | 5 ++++ crates/render/src/area_labels.rs | 29 +++++++++++++++++++---- crates/render/src/lib.rs | 23 ++++++++++++++---- crates/render/src/polygon_labels_tests.rs | 26 ++++++++++++++++---- crates/tiles/src/symbols.rs | 20 ++++++++++++++-- docs/user-guide/cartography.md | 5 ++-- 7 files changed, 94 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index c6361bff54..9423ae2684 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -793,7 +793,9 @@ fn same_places(l: &Layer, b: &Labeling) -> bool { let side = |c: &LabelClass| { if lines && c.placement.along_line() { i8::from(c.line_offset > 0.0) - i8::from(c.line_offset < 0.0) } else { 0 } }; - labels.classes.iter().chain([&labels.default]).map(|c| (c.placement, tries(c), c.repeat.is_some(), side(c))).collect::>() + // A repeat counts only along a line, where it places labels. + let repeats = |c: &LabelClass| lines && c.placement.along_line() && c.repeat.is_some(); + labels.classes.iter().chain([&labels.default]).map(|c| (c.placement, tries(c), repeats(c), side(c))).collect::>() }; classes(&l.labels).into_iter().zip(classes(b)).all(|(x, y)| x == y || !(x.1 || y.1)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 78820b3024..e5b169c8dc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9645,6 +9645,11 @@ fn labels_take_other_positions_in_polygons() { assert!(on(&Session::new(serde_json::from_str(&text).unwrap()))); s.run("labels.enable", &json!({"layer": id, "on": true})).unwrap(); let v = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false }; + // A repeat does nothing on a polygon, so it keeps the lock. + s.run("labels.lock", &json!({"on": true})).unwrap(); + crate::render::render(s.map_mut(), &v).unwrap(); + s.run("labels.placement", &json!({"layer": id, "repeat": 144})).unwrap(); + assert!(s.map().label_lock.is_some(), "a repeat moves no polygon label"); for turn in [false, true] { s.run("labels.lock", &json!({"on": true})).unwrap(); crate::render::render(s.map_mut(), &v).unwrap(); diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index 23c4e80a65..c8ed7d257e 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -342,15 +342,36 @@ pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec>]) -> O /// the rings narrowed `aspect` times, so the centre of the largest ellipse of that shape inside /// them. The largest circle's would put a wide name in a corner of a U or an L, out over its side. /// Searched in the narrowed rings, to about a point up and down and `aspect` points across (a -/// two-hundredth of a large polygon where that is coarser). `None` for no polygon, one with no area -/// near the view or one with a place behind the globe. -pub(super) fn pole(ctx: &super::Ctx<'_>, g: &rustgis_data::Geometry, aspect: f32) -> Option<(f32, f32)> { +/// two-hundredth of a large polygon where that is coarser). +/// +/// The text stays upright in the view the frame is `shown` in (a turned or tilted one; none: the +/// frame's own), so the search is made there. The place is given in the frame's points, then in +/// that view's. `None` for no polygon, one with no area near the view or one with a place behind +/// the globe or the camera. +pub(super) fn pole( + ctx: &super::Ctx<'_>, + g: &rustgis_data::Geometry, + aspect: f32, + shown: Option<&super::View>, +) -> Option<((f32, f32), (f32, f32))> { let mut rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; + let here = ctx.view; + if let Some(to) = shown { + for p in rings.iter_mut().flatten() { + let m = here.camera.to_map(f64::from(p.0), f64::from(p.1), here.width, here.height); + let (x, y) = to.camera.try_to_screen(m, to.width, to.height)?; + *p = (x as f32, y as f32); + } + } // 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)?; - Some((x * aspect, y)) + 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)) } /// [`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 822f26b04e..9c7268bfa9 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2867,6 +2867,9 @@ enum Labels<'a> { Shared, } +/// A coordinate far outside any view, for a place kept only for its number. +const NO_PLACE: f32 = -1.0e5; + /// Labels farther than this (as a fraction of the centre's scale) are left out of a tilted view. const LABEL_MIN_DEPTH_SCALE: f64 = 0.3; @@ -6530,21 +6533,33 @@ fn render_frame( && moved.is_none() && class.places_inside_polygons() && matches!(g, Geometry::Polygon(_)); + // The view the frame is shown in, where that isn't its own. + let shown = match &labels_to { + Labels::Turned(to) | Labels::Tilted(to, _) => Some(*to), + Labels::Own | Labels::Shared => None, + }; let pole = tries - .then(|| area_labels::pole(ctx, g, bw / bh)) + .then(|| area_labels::pole(ctx, g, bw / bh, shown)) .flatten() // Out of view it isn't tried, so View Unplaced shows the label here. // Locked, it is: the lock names a place by its number, the pole's // first, and an unseen place is passed over as the lock is taken. - .filter(|&(px, py)| { - display.locked || ((0.0..=vw).contains(&f64::from(px)) && (0.0..=vh).contains(&f64::from(py))) + .filter(|&(_, (px, py))| { + let (w, h) = shown.map_or((vw, vh), |to| (to.width, to.height)); + display.locked || ((0.0..=w).contains(&f64::from(px)) && (0.0..=h).contains(&f64::from(py))) }); // Here again as the place after the pole's, with a pole this frame or // without, so a lock that took it second still finds it. if tries { line_alternatives.push(LabelPlace { x: lx, y: ly, angle: turned, glyphs: Vec::new() }); } - let (px, py) = pole.map_or((lx, ly), |pole| place_at(pole, class.placement)); + let (px, py) = match pole { + Some((pole, _)) => place_at(pole, class.placement), + // Locked without one, the pole's number keeps a place no view + // shows, so a lock taken now names the label point by its own. + None if tries && display.locked => (NO_PLACE, NO_PLACE), + None => (lx, ly), + }; places.push((0, px, py, turned, Vec::new())); } // Heavier classes first (#2803; labels moved by hand before all of them, diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index e50aa14b49..ac99c34745 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -133,10 +133,12 @@ fn on_it_goes_to_the_point_farthest_from_the_edges() { fn a_wide_name_stays_inside_its_polygon() { let l = vec![ring(&[(-0.25, -0.2), (0.25, -0.2), (0.25, -0.1), (-0.1, -0.1), (-0.1, 0.2), (-0.25, 0.2)])]; let name = "Horseshoe Lake"; - // Zoomed out: the arms and base are about as wide as half the name. - let mut v = view(); - v.camera.res = 200.0; - for rings in [u(), l] { + // Zoomed out: the arms and base are about as wide as half the name. Turned and tilted too: + // the shape is fitted where the text is read, upright on the screen. + for (rings, bearing, pitch) in [u(), l].into_iter().flat_map(|r| [(0.0, 0.0), (90.0, 0.0), (0.0, 30.0)].map(|(b, p)| (r.clone(), b, p))) + { + let mut v = view(); + (v.camera.res, v.camera.bearing, v.camera.pitch) = (200.0, bearing, pitch); let (mut m, _) = named(Geometry::Polygon(vec![rings.clone()]), true, name); let placed = render(&mut m, &v).unwrap().labels; let p = placed.iter().find(|l| l.text == name).unwrap(); @@ -144,7 +146,7 @@ fn a_wide_name_stays_inside_its_polygon() { let (hw, hh) = (text::spaced_block_width(name, p.size, face, 0.0) / 2.0, text::block_height(name, p.size) / 2.0); for (dx, dy) in [(-hw, -hh), (hw, -hh), (-hw, hh), (hw, hh)] { let corner = at(&v, (p.x + dx, p.y + dy)); - assert!(depth(&rings, corner) > 0.0, "{corner:?} of the box at {:?}", (p.x, p.y)); + assert!(depth(&rings, corner) > 0.0, "turned {bearing}, tilted {pitch}: {corner:?} of the box at {:?}", (p.x, p.y)); } } } @@ -287,3 +289,17 @@ fn a_lock_on_the_label_point_holds_without_a_pole() { } assert!(near(one(&mut m, &v), at_lock)); } + +/// A lock taken where no place inside can be found (here a polygon with no area; on the globe, +/// one reaching behind it) names the label point by its own number, so the label doesn't move +/// when a place inside appears. +#[test] +fn a_lock_taken_without_a_pole_names_the_label_point() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + m.label_display.locked = true; + assert!(near(one(&mut m, &v), today(&v, &g))); + assert!(m.label_lock.as_ref().unwrap().iter().all(|(_, p)| p.place == 1), "{:?}", m.label_lock); + assert!(near(one(&mut m, &v), today(&v, &g))); +} diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index aa530f0a63..fc98de3ba8 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -551,6 +551,10 @@ fn signed_area(r: &[(f32, f32)]) -> f32 { s / 2.0 } +/// The most cells [`pole_of_inaccessibility`] starts with along a side. The short side takes one, +/// so this is the most it starts with in all. +const MAX_POLE_CELLS: usize = 4096; + /// The point inside a polygon (outer ring, then holes) farthest from its edges, to within /// `precision` (after Mapbox's polylabel, ISC; see `INCLUDED` in `xtask/src/notices.rs`): where a /// label sits best in an area. `None` for a polygon with no area. @@ -564,7 +568,9 @@ pub fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Opti if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 { return None; } - let cell = w.min(h); + // Squares as wide as the short side, no more than 4096 along the long one, so the whole of a + // very long shape is searched. + let cell = w.min(h).max(w.max(h) / MAX_POLE_CELLS as f32); // A label needs its point to about a pixel, or a two-hundredth of the polygon when that is // coarser: a large polygon isn't searched to a fraction of a pixel. let precision = precision.max(w.max(h) / 200.0).max(1e-3); @@ -574,7 +580,7 @@ pub fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Opti }; let mut queue: std::collections::BinaryHeap = std::collections::BinaryHeap::new(); let h0 = cell / 2.0; - let (nx, ny) = (((w / cell).ceil() as usize).min(64), ((h / cell).ceil() as usize).min(64)); + let (nx, ny) = (((w / cell).ceil() as usize).min(MAX_POLE_CELLS), ((h / cell).ceil() as usize).min(MAX_POLE_CELLS)); for i in 0..nx { for j in 0..ny { queue.push(make((x0 + h0 + i as f32 * cell, y0 + h0 + j as f32 * cell), h0)); @@ -898,6 +904,16 @@ mod tests { assert_eq!(kept, vec![7.0, 8.0, 9.0], "the last layers' labels, placed first, are kept"); } + /// The search covers the whole of a very long shape: here its one wide part is far past 64 + /// times its width along it. + #[test] + fn the_pole_of_a_very_long_polygon_is_found_anywhere_along_it() { + let ring = + vec![(0.0, 0.0), (0.5, 0.0), (0.5, 9000.0), (5.0, 9000.0), (5.0, 9200.0), (0.5, 9200.0), (0.5, 10_000.0), (0.0, 10_000.0)]; + let (x, y) = pole_of_inaccessibility(&[ring], 1.0).expect("an inside place"); + assert!(x > 1.0 && (9000.0..9200.0).contains(&y), "{x}, {y}"); + } + #[test] fn hostile_geometry_is_safe() { let layer = diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index b2ae920a98..40a42c44ed 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -770,8 +770,9 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: 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. Not for Curved labels or labels along a guide, where the box is hidden, - turning the setting on is refused and one already on does nothing. Off by default, as round points; the class's position and offset apply from + without this. 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 (`labels.placement={"layer": "Lakes", "otherPositions": true}`). From aec4fb918d8fe7d27c079dcc1ef5e7f2e709414b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 16:39:59 -0500 Subject: [PATCH 07/11] fix(render, tiles): keep the unplaced preview under a reserved place and search thin polygons across --- crates/render/src/lib.rs | 6 +++++- crates/render/src/polygon_labels_tests.rs | 19 +++++++++++++++++++ crates/tiles/src/symbols.rs | 19 ++++++++++++++----- 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 9c7268bfa9..aa9feee9e0 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8459,6 +8459,10 @@ fn place_labels_with_previews( at = Some((0, original.clone(), text, icon, false, false)); } } + // A place kept only for its number is never seen: the next one seen stands for the + // label where none holds all of it. (Known by how far off it is: a turned view + // turns it too.) + let reserved = original.x.abs().max(original.y.abs()) >= NO_PLACE.abs() / 2.0; let mut ready = std::iter::once(original).chain(alternatives); for i in 0..count { let place = match &curves { @@ -8499,7 +8503,7 @@ fn place_labels_with_previews( } let (show_text, show_icon) = shows(&l, &text, &icon, &grid, locked); let whole = show_text == has_text && show_icon == has_icon; - if i == 0 || whole { + if i == 0 || whole || (reserved && at.is_none()) { at = Some((i, LabelPlace::take(&mut l), text, icon, show_text, show_icon)); } if whole { diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index ac99c34745..5e42212f64 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -303,3 +303,22 @@ fn a_lock_taken_without_a_pole_names_the_label_point() { assert!(m.label_lock.as_ref().unwrap().iter().all(|(_, p)| p.place == 1), "{:?}", m.label_lock); assert!(near(one(&mut m, &v), today(&v, &g))); } + +/// Locked with no place inside, a crowded label still shows as unplaced. +#[test] +fn a_crowded_label_locked_without_a_pole_is_unplaced() { + let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); + let v = view(); + for bearing in [0.0, 90.0] { + 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]); + m.label_display.show_unplaced = true; + m.label_display.locked = true; + let r = render(&mut m, &v).unwrap(); + assert!(r.labels.iter().all(|l| l.text != "Lake"), "turned {bearing}"); + assert_eq!(r.unplaced.iter().filter(|l| l.text == "Lake").count(), 1, "turned {bearing}"); + } +} diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index fc98de3ba8..7ec9cf32b7 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -551,8 +551,9 @@ fn signed_area(r: &[(f32, f32)]) -> f32 { s / 2.0 } -/// The most cells [`pole_of_inaccessibility`] starts with along a side. The short side takes one, -/// so this is the most it starts with in all. +/// The most cells [`pole_of_inaccessibility`] starts with along a side: a shape up to this many +/// times longer than wide is searched along all of it. The short side takes one, so this is the +/// most it starts with in all. const MAX_POLE_CELLS: usize = 4096; /// The point inside a polygon (outer ring, then holes) farthest from its edges, to within @@ -568,9 +569,8 @@ pub fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Opti if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 { return None; } - // Squares as wide as the short side, no more than 4096 along the long one, so the whole of a - // very long shape is searched. - let cell = w.min(h).max(w.max(h) / MAX_POLE_CELLS as f32); + // Squares as wide as the short side, so they start across the shape's width. + let cell = w.min(h); // A label needs its point to about a pixel, or a two-hundredth of the polygon when that is // coarser: a large polygon isn't searched to a fraction of a pixel. let precision = precision.max(w.max(h) / 200.0).max(1e-3); @@ -914,6 +914,15 @@ mod tests { assert!(x > 1.0 && (9000.0..9200.0).contains(&y), "{x}, {y}"); } + /// Longer than the cells reach, a shape is still searched across its width. + #[test] + fn the_pole_search_starts_inside_a_thin_polygons_width() { + let ring = + vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1000.0), (0.1, 1000.0), (0.1, 9000.0), (1.0, 9000.0), (1.0, 10_000.0), (0.0, 10_000.0)]; + let (x, y) = pole_of_inaccessibility(&[ring], 1.0).expect("an inside place"); + assert!((0.0..1.0).contains(&x) && (0.0..10_000.0).contains(&y), "{x}, {y}"); + } + #[test] fn hostile_geometry_is_safe() { let layer = From 151fd4b2e5d53d43e618fcf7e864c2d04e6d21ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 17:27:53 -0500 Subject: [PATCH 08/11] fix(tiles): leave the polygon pole search as it was --- crates/tiles/src/symbols.rs | 27 +-------------------------- 1 file changed, 1 insertion(+), 26 deletions(-) diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index 7ec9cf32b7..aa530f0a63 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -551,11 +551,6 @@ fn signed_area(r: &[(f32, f32)]) -> f32 { s / 2.0 } -/// The most cells [`pole_of_inaccessibility`] starts with along a side: a shape up to this many -/// times longer than wide is searched along all of it. The short side takes one, so this is the -/// most it starts with in all. -const MAX_POLE_CELLS: usize = 4096; - /// The point inside a polygon (outer ring, then holes) farthest from its edges, to within /// `precision` (after Mapbox's polylabel, ISC; see `INCLUDED` in `xtask/src/notices.rs`): where a /// label sits best in an area. `None` for a polygon with no area. @@ -569,7 +564,6 @@ pub fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Opti if !(w.is_finite() && h.is_finite()) || w <= 0.0 || h <= 0.0 { return None; } - // Squares as wide as the short side, so they start across the shape's width. let cell = w.min(h); // A label needs its point to about a pixel, or a two-hundredth of the polygon when that is // coarser: a large polygon isn't searched to a fraction of a pixel. @@ -580,7 +574,7 @@ pub fn pole_of_inaccessibility(poly: &[Vec<(f32, f32)>], precision: f32) -> Opti }; let mut queue: std::collections::BinaryHeap = std::collections::BinaryHeap::new(); let h0 = cell / 2.0; - let (nx, ny) = (((w / cell).ceil() as usize).min(MAX_POLE_CELLS), ((h / cell).ceil() as usize).min(MAX_POLE_CELLS)); + let (nx, ny) = (((w / cell).ceil() as usize).min(64), ((h / cell).ceil() as usize).min(64)); for i in 0..nx { for j in 0..ny { queue.push(make((x0 + h0 + i as f32 * cell, y0 + h0 + j as f32 * cell), h0)); @@ -904,25 +898,6 @@ mod tests { assert_eq!(kept, vec![7.0, 8.0, 9.0], "the last layers' labels, placed first, are kept"); } - /// The search covers the whole of a very long shape: here its one wide part is far past 64 - /// times its width along it. - #[test] - fn the_pole_of_a_very_long_polygon_is_found_anywhere_along_it() { - let ring = - vec![(0.0, 0.0), (0.5, 0.0), (0.5, 9000.0), (5.0, 9000.0), (5.0, 9200.0), (0.5, 9200.0), (0.5, 10_000.0), (0.0, 10_000.0)]; - let (x, y) = pole_of_inaccessibility(&[ring], 1.0).expect("an inside place"); - assert!(x > 1.0 && (9000.0..9200.0).contains(&y), "{x}, {y}"); - } - - /// Longer than the cells reach, a shape is still searched across its width. - #[test] - fn the_pole_search_starts_inside_a_thin_polygons_width() { - let ring = - vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1000.0), (0.1, 1000.0), (0.1, 9000.0), (1.0, 9000.0), (1.0, 10_000.0), (0.0, 10_000.0)]; - let (x, y) = pole_of_inaccessibility(&[ring], 1.0).expect("an inside place"); - assert!((0.0..1.0).contains(&x) && (0.0..10_000.0).contains(&y), "{x}, {y}"); - } - #[test] fn hostile_geometry_is_safe() { let layer = From 54aed1fa5d34de8d9fc11ebf6fe7b5c61097e266 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 18:07:06 -0500 Subject: [PATCH 09/11] fix(render): keep a locked polygon label at the map place it was locked at --- crates/map/src/lib.rs | 3 +- crates/render/src/lib.rs | 46 +++++++++++++++++------ crates/render/src/polygon_labels_tests.rs | 23 ++++++++++++ 3 files changed, 60 insertions(+), 12 deletions(-) diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 868991549a..9625b918b8 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -2232,7 +2232,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. Render cache only, never saved. + /// Geographic anchors of locked non-repeated line labels, and of polygon labels trying places + /// inside. 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/render/src/lib.rs b/crates/render/src/lib.rs index aa9feee9e0..07ef3af515 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6538,23 +6538,47 @@ fn render_frame( Labels::Turned(to) | Labels::Tilted(to, _) => Some(*to), Labels::Own | Labels::Shared => None, }; - let pole = tries - .then(|| area_labels::pole(ctx, g, bw / bh, shown)) - .flatten() - // Out of view it isn't tried, so View Unplaced shows the label here. - // Locked, it is: the lock names a place by its number, the pole's - // first, and an unseen place is passed over as the lock is taken. - .filter(|&(_, (px, py))| { - let (w, h) = shown.map_or((vw, vh), |to| (to.width, to.height)); - display.locked || ((0.0..=w).contains(&f64::from(px)) && (0.0..=h).contains(&f64::from(py))) - }); + // Locked at the pole: where it was then, not where a search finds it + // now, as along a flat stretch many places are as good. + let key = (lid, label_id(row), ci, 0); + let at_pole = lock.as_ref().and_then(|k| k.get(&key)).is_some_and(|won| won.place == 0); + let held = map.label_lock_line_anchors.get(&key).copied().filter(|_| tries && at_pole); + let pole = match held { + Some(anchor) => match &globe { + Some(globe) => globe.forward(anchor), + None => flat.forward(anchor).map(|p| view.to_screen(p)), + } + .map(|(x, y)| (x as f32, y as f32)), + None => tries + .then(|| area_labels::pole(ctx, g, bw / bh, shown)) + .flatten() + // Out of view it isn't tried, so View Unplaced shows the label + // here. Locked, it is: the lock names a place by its number, + // the pole's first, and an unseen place is passed over as the + // lock is taken. + .filter(|&(_, (px, py))| { + let (w, h) = shown.map_or((vw, vh), |to| (to.width, to.height)); + display.locked || ((0.0..=w).contains(&f64::from(px)) && (0.0..=h).contains(&f64::from(py))) + }) + .map(|(here, _)| here), + }; + // Each place's own 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)), + }; + let anchors = vec![pole.and_then(on_map), on_map((x as f32, y as f32))]; + line_places = Some(LinePlaces { anchors, ..Default::default() }); + } // Here again as the place after the pole's, with a pole this frame or // without, so a lock that took it second still finds it. if tries { line_alternatives.push(LabelPlace { x: lx, y: ly, angle: turned, glyphs: Vec::new() }); } let (px, py) = match pole { - Some((pole, _)) => place_at(pole, class.placement), + Some(pole) => place_at(pole, class.placement), // Locked without one, the pole's number keeps a place no view // shows, so a lock taken now names the label point by its own. None if tries && display.locked => (NO_PLACE, NO_PLACE), diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 5e42212f64..ef4ff6c135 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -322,3 +322,26 @@ fn a_crowded_label_locked_without_a_pole_is_unplaced() { assert_eq!(r.unplaced.iter().filter(|l| l.text == "Lake").count(), 1, "turned {bearing}"); } } + +/// A lock keeps the map place a polygon label's pole was at, not the search: along a flat stretch +/// many places are as good, and which one a search finds changes with the view. +#[test] +fn a_locked_polygon_label_stays_at_the_place_it_was_locked() { + for bearing in [0.0, 90.0] { + let (mut m, _) = map(Geometry::Polygon(vec![u()]), true); + let mut v = view(); + v.camera.bearing = bearing; + m.label_display.locked = true; + let placed = at(&v, one(&mut m, &v)); + let kept: Vec = m.label_lock_line_anchors.values().copied().collect(); + assert_eq!(kept.len(), 1, "turned {bearing}"); + assert!((kept[0].x - placed.x).abs() < 2e-3 && (kept[0].y - placed.y).abs() < 2e-3, "{kept:?} {placed:?}"); + // Another place along the base, as another search might find. + let other = c(placed.x + 0.05, placed.y); + m.label_lock_line_anchors.values_mut().for_each(|a| *a = other); + let mut moved = view_at(0.03, 0.02); + moved.camera.bearing = bearing; + let after = at(&moved, one(&mut m, &moved)); + assert!((after.x - other.x).abs() < 2e-3 && (after.y - other.y).abs() < 2e-3, "turned {bearing}: {after:?} {other:?}"); + } +} From e998e15c71d9d344997a40e4b34b67f0b06b62db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 19:00:13 -0500 Subject: [PATCH 10/11] fix(render): search no pole for a label locked at its label point --- crates/render/src/area_labels.rs | 8 ++++++++ crates/render/src/lib.rs | 7 ++++--- crates/render/src/polygon_labels_tests.rs | 16 ++++++++++++++++ docs/user-guide/cartography.md | 18 +++++++++--------- 4 files changed, 37 insertions(+), 12 deletions(-) diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index c8ed7d257e..2aa5210c6d 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -354,6 +354,8 @@ pub(super) fn pole( aspect: f32, shown: Option<&super::View>, ) -> Option<((f32, f32), (f32, f32))> { + #[cfg(test)] + SEARCHES.with(|n| n.set(n.get() + 1)); let mut rings = screen_rings(ctx, std::slice::from_ref(g.label_part()?))?; let here = ctx.view; if let Some(to) = shown { @@ -374,6 +376,12 @@ pub(super) fn pole( Some(((x as f32, y as f32), there)) } +#[cfg(test)] +thread_local! { + /// The [`pole`] searches made on this thread. + pub(super) static SEARCHES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// [`glyphs`]' characters `advances` wide and `height` tall, as [`Line::curved`] takes them. fn curved( ctx: &super::Ctx<'_>, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 07ef3af515..e11f0271ba 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6541,15 +6541,16 @@ fn render_frame( // Locked at the pole: where it was then, not where a search finds it // now, as along a flat stretch many places are as good. let key = (lid, label_id(row), ci, 0); - let at_pole = lock.as_ref().and_then(|k| k.get(&key)).is_some_and(|won| won.place == 0); - let held = map.label_lock_line_anchors.get(&key).copied().filter(|_| tries && at_pole); + // Locked at its label point (place 1), no pole is looked for. + let locked_at = lock.as_ref().and_then(|k| k.get(&key)).map(|won| won.place); + let held = map.label_lock_line_anchors.get(&key).copied().filter(|_| tries && locked_at == Some(0)); let pole = match held { Some(anchor) => match &globe { Some(globe) => globe.forward(anchor), None => flat.forward(anchor).map(|p| view.to_screen(p)), } .map(|(x, y)| (x as f32, y as f32)), - None => tries + None => (tries && locked_at.is_none_or(|place| place == 0)) .then(|| area_labels::pole(ctx, g, bw / bh, shown)) .flatten() // Out of view it isn't tried, so View Unplaced shows the label diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index ef4ff6c135..2cc1dc3da4 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -345,3 +345,19 @@ fn a_locked_polygon_label_stays_at_the_place_it_was_locked() { assert!((after.x - other.x).abs() < 2e-3 && (after.y - other.y).abs() < 2e-3, "turned {bearing}: {after:?} {other:?}"); } } + +/// Locked at its label point, a label's pole isn't searched for again. +#[test] +fn a_lock_at_the_label_point_searches_for_no_pole() { + let g = Geometry::Polygon(vec![u()]); + let (mut m, _) = map(g.clone(), true); + let v = view(); + let pole = one(&mut m, &v); + block(&mut m, &v, &[pole]); + m.label_display.locked = true; + assert!(near(one(&mut m, &v), today(&v, &g))); + area_labels::SEARCHES.with(|n| n.set(0)); + let moved = view_at(0.03, 0.02); + assert!(near(one(&mut m, &moved), today(&moved, &g))); + area_labels::SEARCHES.with(|n| assert_eq!(n.get(), 0)); +} diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 40a42c44ed..da9f0cc5cf 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -766,15 +766,15 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: (`labels.placement={"layer": "Cities", "otherPositions": true}`). - **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. 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 + 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. 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 (`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 86f5eed7b466390e0d9c741088a1a8c3ed06eab8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Sat, 28 Nov 2026 19:17:36 -0500 Subject: [PATCH 11/11] fix(render): keep a locked polygon label by the map place it went first --- crates/render/src/area_labels.rs | 4 +- crates/render/src/lib.rs | 61 +++++++++-------------- crates/render/src/polygon_labels_tests.rs | 25 ++++++++-- 3 files changed, 48 insertions(+), 42 deletions(-) diff --git a/crates/render/src/area_labels.rs b/crates/render/src/area_labels.rs index 2aa5210c6d..5439a6e892 100644 --- a/crates/render/src/area_labels.rs +++ b/crates/render/src/area_labels.rs @@ -342,7 +342,9 @@ pub(super) fn screen_rings(ctx: &super::Ctx<'_>, polys: &[Vec>]) -> O /// the rings narrowed `aspect` times, so the centre of the largest ellipse of that shape inside /// them. The largest circle's would put a wide name in a corner of a U or an L, out over its side. /// Searched in the narrowed rings, to about a point up and down and `aspect` points across (a -/// two-hundredth of a large polygon where that is coarser). +/// two-hundredth of a large polygon where that is coarser). It starts with at most 64 cells along +/// a side and takes at most about 1,000 steps: on a shape more than 64 times longer than wide, as +/// narrowed, only its first 64 widths are searched. /// /// The text stays upright in the view the frame is `shown` in (a turned or tilted one; none: the /// frame's own), so the search is made there. The place is given in the frame's points, then in diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index e11f0271ba..8283f08553 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2867,9 +2867,6 @@ enum Labels<'a> { Shared, } -/// A coordinate far outside any view, for a place kept only for its number. -const NO_PLACE: f32 = -1.0e5; - /// Labels farther than this (as a fraction of the centre's scale) are left out of a tilted view. const LABEL_MIN_DEPTH_SCALE: f64 = 0.3; @@ -6538,53 +6535,47 @@ fn render_frame( Labels::Turned(to) | Labels::Tilted(to, _) => Some(*to), Labels::Own | Labels::Shared => None, }; - // Locked at the pole: where it was then, not where a search finds it - // now, as along a flat stretch many places are as good. let key = (lid, label_id(row), ci, 0); - // Locked at its label point (place 1), no pole is looked for. let locked_at = lock.as_ref().and_then(|k| k.get(&key)).map(|won| won.place); - let held = map.label_lock_line_anchors.get(&key).copied().filter(|_| tries && locked_at == Some(0)); - let pole = match held { - Some(anchor) => match &globe { - Some(globe) => globe.forward(anchor), - None => flat.forward(anchor).map(|p| view.to_screen(p)), + // 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. Locked at the place after, neither. + let first = match locked_at { + _ if !tries => None, + Some(0) => { + 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 }; + Some((x as f32, y as f32)) } - .map(|(x, y)| (x as f32, y as f32)), - None => (tries && locked_at.is_none_or(|place| place == 0)) - .then(|| area_labels::pole(ctx, g, bw / bh, shown)) - .flatten() - // Out of view it isn't tried, so View Unplaced shows the label - // here. Locked, it is: the lock names a place by its number, - // the pole's first, and an unseen place is passed over as the - // lock is taken. + Some(_) => None, + None => area_labels::pole(ctx, g, bw / bh, shown) .filter(|&(_, (px, py))| { let (w, h) = shown.map_or((vw, vh), |to| (to.width, to.height)); - display.locked || ((0.0..=w).contains(&f64::from(px)) && (0.0..=h).contains(&f64::from(py))) + (0.0..=w).contains(&f64::from(px)) && (0.0..=h).contains(&f64::from(py)) }) .map(|(here, _)| here), }; - // Each place's own on the map, while the lock is taken (never from a - // tilted view), for it to keep. + // 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)), }; - let anchors = vec![pole.and_then(on_map), on_map((x as f32, y as f32))]; + let own = (x as f32, y as f32); + let anchors = vec![on_map(first.unwrap_or(own)), on_map(own)]; line_places = Some(LinePlaces { anchors, ..Default::default() }); } - // Here again as the place after the pole's, with a pole this frame or - // without, so a lock that took it second still finds it. + // The label point is the place after the first, so a lock that took it + // there finds it. if tries { line_alternatives.push(LabelPlace { x: lx, y: ly, angle: turned, glyphs: Vec::new() }); } - let (px, py) = match pole { - Some(pole) => place_at(pole, class.placement), - // Locked without one, the pole's number keeps a place no view - // shows, so a lock taken now names the label point by its own. - None if tries && display.locked => (NO_PLACE, NO_PLACE), - None => (lx, ly), - }; + let (px, py) = first.map_or((lx, ly), |first| place_at(first, class.placement)); places.push((0, px, py, turned, Vec::new())); } // Heavier classes first (#2803; labels moved by hand before all of them, @@ -8484,10 +8475,6 @@ fn place_labels_with_previews( at = Some((0, original.clone(), text, icon, false, false)); } } - // A place kept only for its number is never seen: the next one seen stands for the - // label where none holds all of it. (Known by how far off it is: a turned view - // turns it too.) - let reserved = original.x.abs().max(original.y.abs()) >= NO_PLACE.abs() / 2.0; let mut ready = std::iter::once(original).chain(alternatives); for i in 0..count { let place = match &curves { @@ -8528,7 +8515,7 @@ fn place_labels_with_previews( } let (show_text, show_icon) = shows(&l, &text, &icon, &grid, locked); let whole = show_text == has_text && show_icon == has_icon; - if i == 0 || whole || (reserved && at.is_none()) { + if i == 0 || whole { at = Some((i, LabelPlace::take(&mut l), text, icon, show_text, show_icon)); } if whole { diff --git a/crates/render/src/polygon_labels_tests.rs b/crates/render/src/polygon_labels_tests.rs index 2cc1dc3da4..150a77fb2d 100644 --- a/crates/render/src/polygon_labels_tests.rs +++ b/crates/render/src/polygon_labels_tests.rs @@ -291,16 +291,17 @@ fn a_lock_on_the_label_point_holds_without_a_pole() { } /// A lock taken where no place inside can be found (here a polygon with no area; on the globe, -/// one reaching behind it) names the label point by its own number, so the label doesn't move -/// when a place inside appears. +/// one reaching behind it) keeps the label point's map place as the first, so the label doesn't +/// move when a place inside appears. #[test] -fn a_lock_taken_without_a_pole_names_the_label_point() { +fn a_lock_taken_without_a_pole_keeps_the_label_point() { let g = Geometry::Polygon(vec![vec![ring(&[(-0.2, 0.0), (0.0, 0.0), (0.2, 0.0)])]]); let (mut m, _) = map(g.clone(), true); let v = view(); m.label_display.locked = true; assert!(near(one(&mut m, &v), today(&v, &g))); - assert!(m.label_lock.as_ref().unwrap().iter().all(|(_, p)| p.place == 1), "{:?}", m.label_lock); + assert!(m.label_lock.as_ref().unwrap().iter().all(|(_, p)| p.place == 0), "{:?}", m.label_lock); + assert_eq!(m.label_lock_line_anchors.len(), 1); assert!(near(one(&mut m, &v), today(&v, &g))); } @@ -361,3 +362,19 @@ fn a_lock_at_the_label_point_searches_for_no_pole() { assert!(near(one(&mut m, &moved), today(&moved, &g))); area_labels::SEARCHES.with(|n| assert_eq!(n.get(), 0)); } + +/// Lock doesn't bring in a pole just out of view, whose name would show in part: the label stays +/// where it was. +#[test] +fn locking_leaves_a_label_whose_pole_is_just_out_of_view() { + let g = Geometry::Polygon(vec![u()]); + let pole = at(&view(), one(&mut map(g.clone(), true).0, &view())); + // The pole 3 points above the top of the view. + let mut v = view(); + v.camera.center.y = lonlat_to_merc(pole).y - 303.0 * v.camera.res; + let (mut m, _) = map(g.clone(), true); + assert!(near(one(&mut m, &v), today(&v, &g))); + m.label_display.locked = true; + assert!(near(one(&mut m, &v), today(&v, &g)), "as before the lock"); + assert!(near(one(&mut m, &v), today(&v, &g)), "and locked"); +}