diff --git a/crates/render/src/layout/scale_bar.rs b/crates/render/src/layout/scale_bar.rs index 07edbbd4f8..dc66fd8ee3 100644 --- a/crates/render/src/layout/scale_bar.rs +++ b/crates/render/src/layout/scale_bar.rs @@ -296,7 +296,8 @@ pub(super) struct BarLayout { pub(super) len: f32, pub(super) bar_h: f32, /// Its labels' size in pixels, the middle of their line, and each drawn: its centre across - /// and its text. One that would touch its neighbour is left out, never the ends. + /// and its text. The ends are always drawn; where labels would touch, those between are + /// thinned evenly ([`scale_bar_kept`]). pub(super) px: f32, pub(super) label_y: f32, pub(super) labels: Vec<(f32, String)>, @@ -329,9 +330,9 @@ pub(super) struct BarUnit { /// Where a scale bar in `r` draws as `bar` asks, at `ground_per_pt` ground metres a point of /// paper: the drawing and the text-cut check ([`losses`]) take the same, so they agree. `None` -/// when it draws no bar. A label that would touch its neighbour is left out, as on any map: the -/// ends always show, and the user guide says each step is labelled where there is room. That is -/// thinning, not a loss to report. +/// when it draws no bar. Labels that would touch are thinned evenly, as on any map +/// ([`scale_bar_kept`]): the ends always show, and the user guide says so. That is thinning, not +/// a loss to report. /// /// Its labels, their room and its unit label follow its text size (#2581). Its lines above the /// bar reach no higher than the box's top, or than a plain bar's labels reach at the default size @@ -472,17 +473,10 @@ pub(super) fn bar_layout(r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, ppp: (x0 + seg * j as f32, s) }) .collect(); - let last = all.last().map(|(x, s)| x - half(s)).unwrap_or(f32::MAX); - let mut right_label = f32::MIN; - let mut labels = Vec::new(); - for (i, (x, s)) in all.into_iter().enumerate() { - let end = i == divs; - if !end && (x - half(&s) < right_label + gap || x + half(&s) + gap > last) && i != 0 { - continue; - } - right_label = x + half(&s); - labels.push((x, s)); - } + let spans: Vec<(f32, f32)> = all.iter().map(|(x, s)| (x, half(s))).map(|(x, h)| (x - h, x + h)).collect(); + let kept = scale_bar_kept(&spans, before, gap); + let right_label = spans.last().map_or(f32::MIN, |s| s.1); + let labels: Vec<(f32, String)> = all.into_iter().enumerate().filter(|(j, _)| kept.contains(j)).map(|(_, l)| l).collect(); // The unit after the bar, level with its middle, or centred over or under it on a line of its // own: after the bar in the room kept for it; on a line of its own in the box's width, moved // in as far as it must be to stay inside it. Shortened with an ellipsis, or left out when not @@ -530,6 +524,23 @@ pub(super) fn bar_layout(r: Rect, ground_per_pt: f64, bar: &BarOptions<'_>, ppp: Some(BarLayout { x0, y0, len, bar_h, px, label_y, labels, before, divs, parts, total, unit, right, unit_cut, cramped }) } +/// The divisions a scale bar labels, in order, given each label's `spans` from its left edge to +/// its right, `before` of the divisions before zero and the `gap` two labels need between them: its +/// ends and every `step`th division from zero, `step` the smallest even share of the divisions after +/// zero at which no two touch; only the ends when none is, touching or not. Evenly spaced, rather +/// than each label that happens to clear the one before it (#3490). +pub(super) fn scale_bar_kept(spans: &[(f32, f32)], before: usize, gap: f32) -> Vec { + let divs = spans.len().saturating_sub(1); + let after = divs.saturating_sub(before); + let clear = + |kept: &[usize]| kept.windows(2).all(|w| matches!((spans.get(w[0]), spans.get(w[1])), (Some(a), Some(b)) if a.1 + gap <= b.0)); + (1..=after) + .filter(|step| after.is_multiple_of(*step)) + .map(|step| (0..=divs).filter(|&j| j == 0 || j == divs || j.abs_diff(before).is_multiple_of(step)).collect::>()) + .find(|kept| clear(kept)) + .unwrap_or_else(|| vec![0, divs]) +} + /// A scale bar filling most of the element's width as `bar` asks, placed by [`bar_layout`]: its /// divisions after zero (and any before it) labelled, the first after zero split into its /// subdivisions. `ground_per_pt` is ground metres per logical point of paper; `colors` are its diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index bd0833ebfb..2153593a5e 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -1,6 +1,7 @@ use super::*; mod legend_breaks; +mod scale_bar_labels; thread_local! { /// How often [`LegendRow::symbol_side`] measured a row on this thread, and @@ -6737,20 +6738,21 @@ fn pictures_draw_as_before() { assert!(wrong.is_empty(), "{}", wrong.join("\n")); } -/// How [`scale_bars_without_details_draw_as_before`]'s bars drew before scale bars had details, -/// their labels in the built-in face. +/// How [`scale_bars_without_details_draw_as_pinned`]'s bars draw, their labels in the built-in +/// face: as before scale bars had details, but for those too close for all their labels, thinned +/// evenly (#3490). #[cfg(not(target_arch = "wasm32"))] -const PINNED: u64 = 0x3975_8d68_da45_882b; +const PINNED: u64 = 0xd4dc_54da_fba7_13eb; -/// A bar with none of the details draws exactly as main drew it: every style, unit, division +/// A bar with none of the details draws as pinned ([`PINNED`]): every style, unit, division /// count, ground resolution, density and decimal mark. Its labels are drawn in the built-in /// face, whatever fonts the machine has: in a process of its own, told so before any text. #[cfg(not(target_arch = "wasm32"))] #[test] -fn scale_bars_without_details_draw_as_before() { +fn scale_bars_without_details_draw_as_pinned() { if std::env::var_os("RUSTGIS_SCALE_BAR_PIN_CHILD").is_none() { let output = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "layout::tests::scale_bars_without_details_draw_as_before", "--nocapture"]) + .args(["--exact", "layout::tests::scale_bars_without_details_draw_as_pinned", "--nocapture"]) .env("RUSTGIS_SCALE_BAR_PIN_CHILD", "1") .env("RUSTGIS_BUILTIN_FONTS", "1") .output() diff --git a/crates/render/src/layout/tests/scale_bar_labels.rs b/crates/render/src/layout/tests/scale_bar_labels.rs new file mode 100644 index 0000000000..b58c861311 --- /dev/null +++ b/crates/render/src/layout/tests/scale_bar_labels.rs @@ -0,0 +1,111 @@ +//! Which labels a scale bar keeps when they don't all fit (#3490). + +use super::*; + +/// The labels' spans of a bar whose divisions are 10 apart, each label `widths[j]` wide and +/// centred on its division. +fn spans(widths: &[f32]) -> Vec<(f32, f32)> { + widths.iter().enumerate().map(|(j, w)| (10.0 * j as f32 - w / 2.0, 10.0 * j as f32 + w / 2.0)).collect() +} + +/// What [`scale_bar_kept`] keeps of `n` labels all `w` wide, with `before` divisions before zero. +fn even(n: usize, w: f32, before: usize) -> Vec { + scale_bar_kept(&spans(&vec![w; n]), before, 1.0) +} + +#[test] +fn a_scale_bar_keeps_every_label_that_fits() { + assert_eq!(even(5, 8.0, 0), [0, 1, 2, 3, 4]); + assert_eq!(even(2, 8.0, 0), [0, 1]); +} + +/// The case of the issue: the third label clears its neighbours but the fourth would touch the +/// last, so every second one is labelled rather than all but the fourth. +#[test] +fn a_scale_bar_with_one_label_too_close_labels_every_second_division() { + assert_eq!(scale_bar_kept(&spans(&[2.0, 7.0, 7.0, 7.0, 16.0]), 0, 1.0), [0, 2, 4]); +} + +#[test] +fn a_scale_bar_with_no_room_for_a_step_widens_it() { + assert_eq!(even(5, 25.0, 0), [0, 4], "every second one still touches"); + assert_eq!(even(11, 15.0, 0), [0, 2, 4, 6, 8, 10]); + assert_eq!(even(11, 35.0, 0), [0, 5, 10]); + assert_eq!(even(8, 15.0, 0), [0, 7], "seven divisions have no even step between"); + assert_eq!(even(7, 25.0, 0), [0, 3, 6]); +} + +/// The ends are drawn even where they touch each other. Above the default text size that makes the +/// box too narrow ([`BarLayout::cramped`]); at the default size the bar isn't flagged for it. +#[test] +fn a_scale_bar_always_keeps_its_ends() { + assert_eq!(even(5, 90.0, 0), [0, 4]); + assert_eq!(even(2, 90.0, 0), [0, 1]); +} + +/// With divisions before zero the step counts from zero, and the first label is kept. +#[test] +fn a_scale_bars_step_counts_from_zero() { + // -2 -1 0 1 2 3 4 + assert_eq!(even(7, 15.0, 2), [0, 2, 4, 6]); + // -1 touches 0, which every step keeps: only the ends are left. + assert_eq!(scale_bar_kept(&spans(&[14.0, 14.0, 4.0, 4.0, 4.0, 4.0]), 1, 1.0), [0, 5]); +} + +/// Over widths, text sizes, divisions and faces, the labels a bar places, read back from where +/// they stand along it, are its ends and, between them, every `step`th division from zero: none +/// touching but ends alone, and no finer step clear. +#[test] +fn a_scale_bar_draws_evenly_spaced_labels() { + let mut faces = vec![text::Face::default()]; + if crate::fonts::serif_available() { + let mut serif = ElementKind::scale_bar(0); + if let ElementKind::ScaleBar { font, .. } = &mut serif { + *font = rustgis_map::layout::FontFamily::Serif; + } + faces.push(BarOptions::of(&serif).unwrap().face); + } + // The bars that kept every label, some between their ends, and their ends alone. + let mut seen = [0usize; 3]; + for face in faces { + for (divisions, before) in [(4, 0), (6, 0), (7, 0), (10, 0), (4, 2), (6, 1)] { + for text_size in [8.0, 16.0, 40.0] { + for w in (60..500).step_by(11) { + let bar = BarOptions { divisions, divisions_before_zero: before, text_size, face, ..BarOptions::default() }; + let r = Rect::from_xywh(0.0, 0.0, w as f32, 400.0).unwrap(); + let Some(b) = bar_layout(r, 100.0, &bar, 1.0, false) else { continue }; + let seg = b.len / b.divs as f32; + let at: Vec = b.labels.iter().map(|(x, _)| ((x - b.x0) / seg).round() as usize).collect(); + let after = b.divs - b.before; + let step = |s: usize| (0..=b.divs).filter(move |&j| j == 0 || j == b.divs || j.abs_diff(b.before) % s == 0); + // Whether the labels of divisions `set` clear each other, each measured where it stands. + let clear = |set: &[usize]| { + let span = |j: usize| { + let each = b.total / b.divs as f64; + let mut s = bar_number(each * (j as f64 - b.before as f64), each, None, false); + if j == b.divs { + let abbr = bar_plan(100.0, f64::from(w), ScaleUnits::Auto).expect("a bar").abbr; + s = format!("{s} {abbr}"); + } + let (x, half) = (b.x0 + seg * j as f32, text::measure_in(&s, b.px / 1.33, face) / 2.0); + (x - half, x + half) + }; + let gap = 3.0 * (b.px / (SCALE_BAR_TEXT_PT as f32 * 1.33)); + set.windows(2).all(|p| span(p[0]).1 + gap <= span(p[1]).0) + }; + let finer: Vec> = + (1..=after).filter(|s| after % s == 0).map(|s| step(s).collect()).take_while(|set| *set != at).collect(); + let case = format!("{divisions}+{before} at {text_size} pt in {w} px: {at:?}"); + let stepped = (1..=after).filter(|s| after % s == 0).any(|s| step(s).eq(at.iter().copied())); + assert!(stepped || at == [0, b.divs], "{case}"); + assert!(at == [0, b.divs] || clear(&at), "touching: {case}"); + assert!(finer.iter().all(|set| !clear(set)), "a finer step was clear: {case}"); + let ends_alone = usize::from(at.len() <= 2); + let thinned = usize::from(at.len() <= b.divs); + seen[thinned + ends_alone] += 1; + } + } + } + } + assert!(seen.iter().all(|&n| n > 20), "every outcome is swept: {seen:?}"); +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index ea3e8be583..25d3b41528 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -438,8 +438,11 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu or an installed family's name, with `"fallback"` if wanted). A scale bar's pick its **Style** (alternating bar, stepped line or single line), its **Units** (metres or kilometres to suit the scale, or kilometres, metres, miles or feet), its **Divisions** (1 to 10), each - labelled where there is room, its **Color** (the lines, the dark divisions and the labels), its - **Fill** (the alternating bar's light divisions) and its **Text size** (`"textSize"`, 4 to 100 + labelled where there is room (the ends always are; where labels would touch, those between + are thinned evenly from zero, every second or third one and so on as the divisions after zero + allow, so a bar of seven divisions then labels only its ends), its **Color** (the lines, the + dark divisions and the labels), its **Fill** (the alternating bar's light divisions) and its + **Text size** (`"textSize"`, 4 to 100 points, 8 by default; the room over the bar and between the labels follows, the bar keeps its length and height and moves down, and right, in its box to make room for larger labels, which reach no further past its top and left than the default size's, and `null` gives the default