Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/service_group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ fn refresh(s: &mut Session, p: &Value) -> CmdResult {
layer.display_filters.retain(|f| rustgis_data::query::parse(&f.where_, &layer.dataset).is_ok());
layer.touch_geometry();
child.layer = layer.id;
// Locked labels name rows of the old features.
// Locked labels name the old features by id, and the new ones are numbered afresh.
if let Some(lock) = &mut s.map_mut().label_lock {
lock.retain(|((id, _, _, _), _)| *id != child.layer);
}
Expand Down
31 changes: 31 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2617,6 +2617,37 @@ fn a_change_to_where_point_labels_go_locks_them_again() {
assert!(s.map().label_lock.is_none(), "a style putting the labels elsewhere: locked again");
}

/// A lock names each label by its feature's id, not its row: deleting a feature (the rows after
/// it move up) neither shows a label left out when the lock was taken nor hides one placed (#1046).
#[test]
fn locked_labels_stay_with_their_features_when_rows_move() {
use crate::render::View;
use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value as V};
let mut s = world();
// Three buoys on one spot of the South Atlantic: only the first one's label fits.
let mut d = Dataset::new("Buoys", GeometryType::Point, vec![Field::new("name", FieldType::Text)]);
for name in ["Alpha", "Beta", "Gamma"] {
d.push(Some(Geometry::Point(rustgis_geom::Coord::new(-20.0, -30.0))), vec![V::Text(name.into())]);
}
let id = s.map_mut().add_dataset(d);
s.run("labels.enable", &json!({"layer": "Buoys", "on": true})).unwrap();
let draw = |s: &mut Session| -> Vec<String> {
let v = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false };
let labels = crate::render::render(s.map_mut(), &v).unwrap().labels;
labels.into_iter().map(|l| l.text).filter(|t| ["Alpha", "Beta", "Gamma"].contains(&t.as_str())).collect()
};
assert_eq!(draw(&mut s), ["Alpha"]);
s.run("labels.lock", &json!({"on": true})).unwrap();
assert_eq!(draw(&mut s), ["Alpha"]);
s.map_mut().layer_mut(id).unwrap().selection = vec![0];
s.run("edit.delete", &Value::Null).unwrap();
assert!(draw(&mut s).is_empty(), "Beta's label wasn't placed when the lock was taken");
s.run("labels.lock", &json!({"on": false})).unwrap();
assert_eq!(draw(&mut s), ["Beta"], "unlocked, Beta's fits");
s.run("labels.lock", &json!({"on": true})).unwrap();
assert_eq!(draw(&mut s), ["Beta"], "and is locked in turn");
}

/// A lock names each label by its class's place in the list: a change to the list (a class added,
/// moved or removed) locks the labels again on the next frame, a change within a class keeps the
/// lock (#732).
Expand Down
7 changes: 4 additions & 3 deletions crates/map/src/symbology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2346,9 +2346,10 @@ impl LabelClass {
}
}

/// A label on the map, as (layer id, row, label class in `Labeling::in_order`, repeat): a feature
/// has a label for each class labelling it (#732), and along a line each repeat is one of its own
/// (0 for the one at the line's middle, and for every label not repeated).
/// A label on the map, as (layer id, feature id, label class in `Labeling::in_order`, repeat): a
/// feature has a label for each class labelling it (#732), and along a line each repeat is one of
/// its own (0 for the one at the line's middle, and for every label not repeated). The feature is
/// named by its id, not its row, so a lock holds through edits that move rows (#1046).
pub type LabelKey = (u32, usize, usize, usize);

/// A layer's label classes read against its data, in `Labeling::in_order`: every class whose
Expand Down
74 changes: 64 additions & 10 deletions crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1838,19 +1838,22 @@ fn visit_complete(

/// A label waiting to be placed: the label, its priority and its key, and where else it may go
/// when its own place is taken (#1011): its `x`, `y` there, tried in order. Whatever moves the
/// label on its way to the screen moves them too, as it does its icon.
/// label on its way to the screen moves them too, as it does its icon. `row` is its feature's
/// row where it was offered: only a hint, checked against the key's feature id before use
/// (a streamed layer's rows are a chunk's), `usize::MAX` for none.
#[derive(Clone, Debug)]
struct Candidate {
label: PlacedLabel,
priority: f64,
key: rustgis_map::LabelKey,
alternatives: Vec<(f32, f32)>,
row: usize,
}

/// A label with no alternatives.
/// A label with no alternatives and no row.
impl From<(PlacedLabel, f64, rustgis_map::LabelKey)> for Candidate {
fn from((label, priority, key): (PlacedLabel, f64, rustgis_map::LabelKey)) -> Candidate {
Candidate { label, priority, key, alternatives: Vec::new() }
Candidate { label, priority, key, alternatives: Vec::new(), row: usize::MAX }
}
}

Expand Down Expand Up @@ -2295,12 +2298,24 @@ fn raise_labels(map: &Map, view: &View, candidates: &mut [Candidate]) {
let flat = map.flat();
let cam = view.camera;
let (w, h) = (view.width, view.height);
for Candidate { label: l, key: (id, row, _, _), alternatives, .. } in candidates.iter_mut() {
// Each extruded layer's rows by feature id, the label keys naming features by id (#1046).
let mut rows: std::collections::HashMap<u32, std::collections::HashMap<usize, usize>> = std::collections::HashMap::new();
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
for Candidate { label: l, key: (id, fid, _, _), alternatives, row: offered, .. } in candidates.iter_mut() {
let Some(layer) = map.layer(*id).filter(|l| l.geometry_type() == GeometryType::Polygon) else { continue };
let Some(x) = &layer.extrusion else { continue };
let features = &layer.dataset.features;
// The row it was offered from while its feature is there, else looked up by id; one not
// among them, as a streamed layer's, rises by the height no field gives.
let row = Some(*offered)
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
.filter(|&r| features.get(r).is_some_and(|f| f.id as usize == *fid))
.or_else(|| {
let by_id = rows.entry(*id).or_insert_with(|| features.iter().enumerate().map(|(r, f)| (f.id as usize, r)).collect());
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
by_id.get(fid).copied()
})
.unwrap_or(usize::MAX);
let Some(m) = cam.try_to_map(f64::from(l.x), f64::from(l.y), w, h) else { continue };
// At the label's place (Web Mercator stretches the ground toward the poles).
let up = (effects::extrusion_metres(&layer.dataset, x, *row)
let up = (effects::extrusion_metres(&layer.dataset, x, row)
/ (flat.ground_per_unit(m) * map.body().ratio()).max(1e-9)
/ cam.res.max(1e-9))
.clamp(0.0, 1e7);
Expand Down Expand Up @@ -3282,7 +3297,9 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac
let layer: &rustgis_map::Layer = layer;
// Its symbol by expression, compiled once for the drawing (none: the layer's own).
let styler = layer.styler(Some(scale));
let label_row = |row: usize| if complete_source { layer.dataset.features.get(row).map_or(row, |f| f.id as usize) } else { row };
// A label is named by its feature's id, not its row: a lock holds through edits that
// move rows (#1046).
let label_id = |row: usize| layer.dataset.features.get(row).map_or(row, |f| f.id as usize);
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible stale lock after a delete and an add (confidence: medium, about 65%). The key now relies on feature ids being stable and never reused while a lock is held. Dataset::push (crates/data/src/lib.rs:339-342) assigns max(existing ids) + 1, so when the feature with the highest id is deleted, the next feature added (edit.rs:63 uses push) gets that same id. The new feature then inherits the deleted feature's lock keys: its label is drawn or suppressed according to the old lock, which is the same symptom as #1046. The new test only deletes row 0 (id 1), so it doesn't cover this.

A possible fix is a monotonic high-water mark on Dataset (for example next_id, serde-defaulted to the current max), so ids are never reused within a dataset. Alternatively, drop the lock whenever a feature is deleted. A regression test would be: lock with the last feature's label placed, delete it, add a new feature, then check that the new feature's label follows the unlocked placement.

let (labels, selection, ds_ptr) = (&layer.labels, &layer.selection, &layer.dataset);
// The globe draws the lon/lat geometry itself; the flat map its Web Mercator copy.
let geoms: Vec<Option<&Geometry>> = if globe.is_some() {
Expand Down Expand Up @@ -3635,7 +3652,7 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac
for (ci, class) in classes.classes_of(ds_ptr, row) {
// Locked, only the labels placed then: one class's, not every class's (and
// along a line, only its repeats placed then, below).
if locked_classes.as_ref().is_some_and(|k| !k.contains(&(lid, label_row(row), ci))) {
if locked_classes.as_ref().is_some_and(|k| !k.contains(&(lid, label_id(row), ci))) {
continue;
}
if point.is_none() && !along_line(class.placement, g) {
Expand Down Expand Up @@ -3718,7 +3735,7 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac
let pri = (n_layers - li) as f64 * 1e12 - ci as f64 * 1e9 + area;
let last = places.len().saturating_sub(1);
for (n, (i, mut lx, mut ly, angle, glyphs)) in places.into_iter().enumerate() {
let key = (lid, label_row(row), ci, i);
let key = (lid, label_id(row), ci, i);
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
// Locked, only the repeats placed then.
if lock.as_ref().is_some_and(|k| !k.contains_key(&key)) {
continue;
Expand Down Expand Up @@ -3767,6 +3784,7 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac
priority: pri - i as f64,
key,
alternatives,
row,
});
}
}
Expand Down Expand Up @@ -5018,7 +5036,8 @@ mod tests {
#[test]
fn labels_try_their_alternatives() {
let blocker = || Candidate::from((label("Blocker", 100.0, None, 0.0), 9.0, (u32::MAX, 0, 0, 0)));
let taken = |alternatives| Candidate { label: label("Taken", 100.0, None, 0.0), priority: 1.0, key: (1, 0, 0, 0), alternatives };
let taken =
|alternatives| Candidate { label: label("Taken", 100.0, None, 0.0), priority: 1.0, key: (1, 0, 0, 0), alternatives, row: 0 };
let at = |p: &Placement| p.labels.iter().map(|l| (l.text.clone(), l.x, l.y)).collect::<Vec<_>>();
// None: left out, as before.
let p = place_labels(vec![blocker(), taken(Vec::new())], Vec::new(), 400.0, 200.0, false);
Expand Down Expand Up @@ -5049,6 +5068,7 @@ mod tests {
priority: 1.0,
key: (1, 0, 0, 0),
alternatives,
row: 0,
};
let c = tilt_candidate(offer((10.0, 50.0), vec![(10.0, 60.0), (10.0, 150.0), (20.0, 160.0)]), &at).unwrap();
assert_eq!((c.label.x, c.label.y), (1010.0, 150.0));
Expand Down Expand Up @@ -5096,7 +5116,7 @@ mod tests {
let (x, y) = ((i % 200) as f32 * 10.0, (i / 200) as f32 * 10.0);
let l = PlacedLabel { x, y, ..label("ab", x, None, 0.0) };
let alternatives = if others { round.map(|(dx, dy)| (x + dx, y + dy)).to_vec() } else { Vec::new() };
Candidate { label: l, priority: -f64::from(i), key: (u32::MAX, i as usize, 0, 0), alternatives }
Candidate { label: l, priority: -f64::from(i), key: (u32::MAX, i as usize, 0, 0), alternatives, row: usize::MAX }
})
.collect()
};
Expand Down Expand Up @@ -6397,6 +6417,40 @@ mod tests {
assert!((shapes[0].height / 200_000.0 - 1.0).abs() < 0.05, "{}", shapes[0].height);
}

/// A label's key names its feature by id (#1046): an extruded feature's label rises by its own
/// height, also once its row no longer follows its id.
#[test]
fn labels_rise_by_their_own_features_height() {
let mut m = Map::new("Map");
let mut d = Dataset::new("blocks", GeometryType::Polygon, vec![Field::new("h", FieldType::Double)]);
let s = 0.1;
let ring = vec![Coord::new(-s, -s), Coord::new(s, -s), Coord::new(s, s), Coord::new(-s, s), Coord::new(-s, -s)];
for h in [0.0, 100_000.0, 0.0] {
d.push(Some(Geometry::Polygon(vec![vec![ring.clone()]])), vec![Value::Float(h)]);
}
// The first one deleted: the tall one (id 2) is row 0 and the low one (id 3) row 1.
d.features.remove(0);
let id = m.add_dataset(d);
m.layer_mut(id).unwrap().extrusion = Some(rustgis_map::effects::Extrusion {
field: Some("h".into()),
height: 0.0,
factor: 1.0,
face_culling: true,
lighting: true,
shadows: true,
});
let camera = Camera { center: Coord::new(0.0, 0.0), res: 2000.0, bearing: 0.0, pitch: 60.0 };
let view = View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false };
let at_centre = |text: &str| PlacedLabel { y: 150.0, ..label(text, 200.0, None, 0.0) };
// The tall one with no row, looked up by id; the low one offered from row 0 before the
// tall one took it there: the row is a hint the id overrules.
let low = Candidate { row: 0, ..(at_centre("Low"), 1.0, (id, 3, 0, 0)).into() };
let mut c: Vec<Candidate> = vec![(at_centre("Tall"), 1.0, (id, 2, 0, 0)).into(), low];
raise_labels(&m, &view, &mut c);
assert!(c[0].label.y < 150.0 - 15.0, "the tall one rises onto its roof: {}", c[0].label.y);
assert!((c[1].label.y - 150.0).abs() < 1.0, "the low one stays on the ground: {}", c[1].label.y);
}

/// Extruded features with junk heights or roof indices (hostile data) give finite geometry
/// or are left out, never garbage.
#[test]
Expand Down
Loading