From 6ef11c2f03814cc5f3d94138e9e71bafc8bfe67d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 20 Nov 2026 07:53:30 -0500 Subject: [PATCH 1/2] feat(render): layout legend swatches draw a layer's stacked strokes and fills (#2490) A line's swatch draws its class or layer strokes (casings, offsets, dashes, markers, by symbol level) and a polygon's its stacked fills (hatches, dots, gradients, shapeburst) through the map's own paths, with the layer's transparency and reference scale, cut to its row. A diagram's categories keep their own colour. A layer with no stack keeps its plain swatch. Refs #2490 --- crates/map/src/diagram.rs | 37 ++- crates/map/src/symbol_by.rs | 1 + crates/map/src/symbology.rs | 51 ++-- crates/render/src/layout.rs | 429 +++++++++++++++++++++++++++++---- docs/user-guide/cartography.md | 10 +- docs/user-guide/layouts.md | 7 + 6 files changed, 461 insertions(+), 74 deletions(-) diff --git a/crates/map/src/diagram.rs b/crates/map/src/diagram.rs index a8df141920..3359b72fb5 100644 --- a/crates/map/src/diagram.rs +++ b/crates/map/src/diagram.rs @@ -9,10 +9,11 @@ //! always in range, and read from a project through [`de_diagram`], which takes a malformed one //! (a hostile file) as `None` and leaves the rest of the layer reading. -use rustgis_data::Dataset; +use rustgis_data::{Dataset, GeometryType}; use serde::{Deserialize, Serialize}; use crate::color::Rgba; +use crate::fills::{FillLayer, FillPattern}; use crate::symbology::{LegendEntry, LineMark, LineMarkers, LineStroke, Marker, Symbol}; /// The most categories one diagram lists (each is a slice or a bar). @@ -256,9 +257,11 @@ impl DiagramSettings { } /// The legend rows of its categories: one per category, in draw order, its field the label. - /// On a line layer the colour goes in the stroke, which is what a line's swatch draws; else it - /// is the fill, with a white outline. - pub fn legend(&self, line: bool) -> Vec { + /// Each row carries its colour in a stack of its own, or it would take the layer's stacked + /// strokes or fills and every category would look the same: on a line layer one stroke, on a + /// polygon layer one fill (with a white outline), on a point layer its mark. + pub fn legend(&self, g: GeometryType) -> Vec { + let line = g == GeometryType::Polyline; self.categories .iter() .map(|c| LegendEntry { @@ -270,7 +273,15 @@ impl DiagramSettings { size: 7.0, marker: Marker::Circle, }, - strokes: vec![category_mark(c.colour)], + strokes: match g { + GeometryType::Point => vec![category_mark(c.colour)], + GeometryType::Polyline => vec![LineStroke { color: Some(c.colour), width: Some(1.0), ..LineStroke::default() }], + _ => Vec::new(), + }, + fills: match g { + GeometryType::Polygon => vec![FillLayer { color: Some(c.colour), pattern: FillPattern::Solid }], + _ => Vec::new(), + }, fallback: false, }) .collect() @@ -510,14 +521,26 @@ mod tests { #[test] fn legend_lists_one_row_per_category() { - let l = settings().legend(false); + let l = settings().legend(GeometryType::Point); assert_eq!(l.iter().map(|e| e.label.as_str()).collect::>(), ["pop_male", "pop_female"]); assert_eq!(l[0].symbol.fill, CATEGORY_COLORS[0]); assert_eq!(l[0].symbol.stroke, Rgba::rgb(0xFF, 0xFF, 0xFF), "a white outline on a polygon or point layer"); assert!(l.iter().all(|e| !e.fallback)); assert_eq!(l[0].strokes[0].color, Some(CATEGORY_COLORS[0]), "its own mark, not the layer's stacked ones"); - let line = settings().legend(true); + let line = settings().legend(GeometryType::Polyline); assert_eq!(line[0].symbol.stroke, CATEGORY_COLORS[0], "a line's swatch draws its stroke, so the colour is there"); + assert_eq!( + line[0].strokes, + [LineStroke { color: Some(CATEGORY_COLORS[0]), width: Some(1.0), ..LineStroke::default() }], + "one stroke, not the layer's" + ); + let area = settings().legend(GeometryType::Polygon); + assert_eq!( + area[0].fills, + [FillLayer { color: Some(CATEGORY_COLORS[0]), pattern: FillPattern::Solid }], + "one fill, not the layer's" + ); + assert!(area[0].strokes.is_empty()); } #[test] diff --git a/crates/map/src/symbol_by.rs b/crates/map/src/symbol_by.rs index 2651c863d8..378905f1f6 100644 --- a/crates/map/src/symbol_by.rs +++ b/crates/map/src/symbol_by.rs @@ -132,6 +132,7 @@ impl SizeBy { label: format!("{} {}", self.field, crate::symbology::fmt_num(v)), symbol: hide_zero(Symbol { size, ..like }), strokes: scaled_marks(strokes, k), + fills: Vec::new(), fallback: false, } }) diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index a36017f202..7e5f24b10a 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -993,15 +993,28 @@ pub struct LegendEntry { pub symbol: Symbol, /// The stacked strokes its class has of its own; empty, it takes the layer's `line_strokes`. pub strokes: Vec, + /// The stacked fills its class has of its own; empty, it takes the layer's `fill_layers`. + pub fills: Vec, /// The Unique Values fallback row (``), told apart from a class whatever /// its label: a legend can leave it out without touching a class that bears the same name. pub fallback: bool, } impl LegendEntry { - /// A class's row, with the stacked strokes it has of its own, if any. - fn class(label: String, symbol: Symbol, strokes: Option<&Vec>) -> Self { - LegendEntry { label, symbol, strokes: strokes.cloned().unwrap_or_default(), fallback: false } + /// A class's row, with the stacked strokes and fills it has of its own, if any. + fn class(label: String, symbol: Symbol, strokes: Option<&Vec>, fills: Option<&Vec>) -> Self { + LegendEntry { + label, + symbol, + strokes: strokes.cloned().unwrap_or_default(), + fills: fills.cloned().unwrap_or_default(), + fallback: false, + } + } + + /// A row with no stacked strokes or fills of its own. + pub fn plain(label: String, symbol: Symbol) -> Self { + LegendEntry { label, symbol, strokes: Vec::new(), fills: Vec::new(), fallback: false } } } @@ -1703,6 +1716,7 @@ impl Renderer { other_fills, other_strokes, class_strokes, + class_fills, .. } = self else { @@ -1766,13 +1780,14 @@ impl Renderer { .into_iter() .filter(|i| used.get(*i).copied().unwrap_or(false)) .filter_map(|i| classes.get(i)) - .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k))) + .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k), class_fills.get(k))) .collect(); if other_used && visible { v.push(LegendEntry { label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()), symbol: *other, strokes: other_strokes.clone(), + fills: other_fills.clone(), fallback: true, }); } @@ -1813,7 +1828,7 @@ impl Renderer { let used = rows.is_none_or(|rows| { (0..ds.features.len()).any(|r| rows.get(r).copied().unwrap_or(true) && fi.and_then(|fi| ds.value(r, fi).as_f64()).is_none()) }); - used.then(|| LegendEntry { label: "No data".into(), symbol: self.symbol_in(ds, 0, None), strokes: Vec::new(), fallback: false }) + used.then(|| LegendEntry::plain("No data".into(), self.symbol_in(ds, 0, None))) } /// Every row of its legend, whatever the features: the classes, then a Unique Values' @@ -1821,23 +1836,26 @@ impl Renderer { pub fn legend(&self) -> Vec { match self { Renderer::Single(_) => Vec::new(), - Renderer::Unique { classes, other, class_labels, other_label, class_strokes, other_strokes, .. } => { + Renderer::Unique { + classes, other, class_labels, other_label, class_strokes, other_strokes, class_fills, other_fills, .. + } => { // Keep symbols attached to their classes in `class_order` and the fallback at the end. let mut v: Vec = self .class_order() .into_iter() .filter_map(|i| classes.get(i)) - .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k))) + .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k), class_fills.get(k))) .collect(); v.push(LegendEntry { label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()), symbol: *other, strokes: other_strokes.clone(), + fills: other_fills.clone(), fallback: true, }); v } - Renderer::Graduated { breaks, symbols, min, class_labels, class_strokes, .. } => { + Renderer::Graduated { breaks, symbols, min, class_labels, class_strokes, class_fills, .. } => { let mut lo = *min; breaks .iter() @@ -1846,19 +1864,14 @@ impl Renderer { .map(|(i, (b, s))| { let label = class_labels.get(&i).cloned().unwrap_or_else(|| range_label(lo, *b)); lo = *b; - LegendEntry::class(label, *s, class_strokes.get(&i)) + LegendEntry::class(label, *s, class_strokes.get(&i), class_fills.get(&i)) }) .collect() } Renderer::Proportional { base, min_size, max_size, min, max, .. } => vec![ - LegendEntry { label: fmt_num(*min), symbol: Symbol { size: *min_size, ..*base }, strokes: Vec::new(), fallback: false }, - LegendEntry { - label: fmt_num((min + max) / 2.0), - symbol: Symbol { size: min_size + (max_size - min_size) * 0.707, ..*base }, - strokes: Vec::new(), - fallback: false, - }, - LegendEntry { label: fmt_num(*max), symbol: Symbol { size: *max_size, ..*base }, strokes: Vec::new(), fallback: false }, + LegendEntry::plain(fmt_num(*min), Symbol { size: *min_size, ..*base }), + LegendEntry::plain(fmt_num((min + max) / 2.0), Symbol { size: min_size + (max_size - min_size) * 0.707, ..*base }), + LegendEntry::plain(fmt_num(*max), Symbol { size: *max_size, ..*base }), ], } } @@ -1987,7 +2000,7 @@ impl Renderer { // The class's row in `legend()`, which lists the classes and then `other`. Unique Values // rows are sorted by label, so that class's row is built here rather than looked up. let row = match (&mut *self, class) { - (Renderer::Unique { classes, class_labels, class_strokes, .. }, ClassRef::Value(v)) => { + (Renderer::Unique { classes, class_labels, class_strokes, class_fills, .. }, ClassRef::Value(v)) => { let i = classes.iter().position(|(k, _)| k == v).ok_or_else(|| format!("no class with the value '{v}'"))?; if let Some((k, s)) = classes.get_mut(i) { restyle(s); @@ -2004,7 +2017,7 @@ impl Renderer { } return classes .get(i) - .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k))) + .map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k), class_fills.get(k))) .ok_or_else(|| "the class has no legend row".into()); } (Renderer::Unique { classes, other, other_label, .. }, ClassRef::Other) => { diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 629db630c2..f8cf1251e9 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -2056,12 +2056,7 @@ fn layer_shown(l: &rustgis_map::Layer, scale: f64, show_no_data: bool, env: &Env fn raster_classes(l: &rustgis_map::Layer, all_classes: bool) -> Option> { let classes = l.raster.as_ref()?.legend_classes(all_classes)?; let symbol = |fill| rustgis_map::Symbol { fill, stroke: RASTER_SWATCH_EDGE, stroke_width: 0.5, size: 0.0, marker: Default::default() }; - Some( - classes - .into_iter() - .map(|(fill, label)| LegendEntry { label, symbol: symbol(fill), strokes: Vec::new(), fallback: false }) - .collect(), - ) + Some(classes.into_iter().map(|(fill, label)| LegendEntry::plain(label, symbol(fill))).collect()) } /// Names only the source whose read stopped this page, leaving unrelated failures generic. @@ -2289,6 +2284,12 @@ fn row_strokes<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> &'a [rustg if en.strokes.is_empty() { &l.line_strokes } else { &en.strokes } } +/// The stacked fills a legend's class row draws: its class's own, else its layer's, as +/// [`rustgis_map::Layer::fills`] finds them for a feature. +fn row_fills<'a>(l: &'a rustgis_map::Layer, en: &'a LegendEntry) -> &'a [rustgis_map::fills::FillLayer] { + if en.fills.is_empty() { &l.fill_layers } else { &en.fills } +} + /// The width of a legend's column of swatches at 1:`scale`, in points: it grows to hold the widest /// point symbol, so the labels line up. fn swatch_column(rows: &[LegendRow], scale: f64) -> f32 { @@ -2526,7 +2527,7 @@ fn legend_rows_missing<'a>( } // A layer with a diagram lists its categories under its classes. if let Some(d) = &l.diagram { - entries.extend(d.legend(l.geometry_type() == GeometryType::Polyline)); + entries.extend(d.legend(l.geometry_type())); } if entries.is_empty() { // A Unique Values layer that lists nothing draws nothing visible (#207); a raster has @@ -2646,14 +2647,22 @@ fn legend_column( match row { LegendRow::Plain(l, name) => { let s = l.renderer.symbol_for(&l.dataset, 0); - swatch(pm, (r.x(), y, sw, height), l, (&s, l.line_strokes.as_slice()), map.layer_opacity(l), opts.scale, ppp); + swatch(pm, (r.x(), y, sw, height), l, (&s, &l.line_strokes, &l.fill_layers), map.layer_opacity(l), opts.scale, ppp); text::text_at(pm, name, r.x() + sw + 6.0 * ppp, y + height / 2.0, 9.0 * 1.33 * ppp, dark, false, text::Align::Left, false); } LegendRow::Head(name) => { text::text_at(pm, name, r.x(), y + line / 2.0, 9.0 * 1.33 * ppp, dark, true, text::Align::Left, false); } LegendRow::Class(l, en) => { - swatch(pm, (r.x() + 6.0 * ppp, y, sw, height), l, (&en.symbol, row_strokes(l, en)), map.layer_opacity(l), opts.scale, ppp); + swatch( + pm, + (r.x() + 6.0 * ppp, y, sw, height), + l, + (&en.symbol, row_strokes(l, en), row_fills(l, en)), + map.layer_opacity(l), + opts.scale, + ppp, + ); text::text_at( pm, &en.label, @@ -2965,54 +2974,130 @@ pub fn frame_plain_under( background && seen.all(|p| rgba(p) == first) } -/// A legend entry's symbol `s` of the layer `l` in the box (`x`, `y`, `w`, `h`): a point as -/// [`point_swatch`] draws it with `strokes`, or a line or a filled box a swatch wide, in the middle -/// of the box. +/// A legend entry's symbol `s` of the layer `l` in the box (`x`, `y`, `w`, `h`), with its stacked +/// `strokes` and `fills` (#2490): a point as [`point_swatch`] draws it, or a line or a filled box a +/// swatch wide in the middle of the box, by the paths the map draws its features with. See-through +/// (`opacity`) or grown with the layer's reference scale at 1:`scale`, it is composited as one and +/// cut to the box, as a point's is. fn swatch( pm: &mut Canvas, (x, y, w, h): (f32, f32, f32, f32), l: &rustgis_map::Layer, - (s, strokes): (&rustgis_map::Symbol, &[rustgis_map::LineStroke]), + (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), opacity: f32, scale: f64, ppp: f32, ) { let gt = l.geometry_type(); + let k = l.size_factor(scale); if gt == GeometryType::Point { - point_swatch(pm, (x, y, w, h), (s, strokes), opacity, ppp * l.size_factor(scale)); + point_swatch(pm, (x, y, w, h), (s, strokes), opacity, ppp * k); return; } - let (x, w) = (x + (w - LEGEND_SWATCH * ppp) / 2.0, LEGEND_SWATCH * ppp); + // A layer with no stack keeps the swatch it always had; any stack is drawn as the map draws + // it, cut to the box. + let plain = if gt == GeometryType::Polyline { strokes.is_empty() } else { fills.is_empty() }; + if plain && opacity >= 0.999 && k == 1.0 { + flat_swatch(pm, (x, y, w, h), gt, s, (ppp, ppp)); + } else if plain { + composited(pm, (x, y, w, h), opacity, |c, (left, top)| flat_swatch(c, (x - left, y - top, w, h), gt, s, (ppp, ppp * k))); + } else { + composited(pm, (x, y, w, h), opacity, |c, (left, top)| { + stacked_swatch(c, (x - left, y - top, w, h), l, (s, strokes, fills), ppp, k) + }); + } +} + +/// The part of the box (`x`, `w`) a line or polygon swatch takes: [`LEGEND_SWATCH`] across, in its +/// middle. +fn swatch_across(x: f32, w: f32, ppp: f32) -> (f32, f32) { + (x + (w - LEGEND_SWATCH * ppp) / 2.0, LEGEND_SWATCH * ppp) +} + +/// The three points of a line swatch in the box, in pixels. +fn swatch_line((x, y, w, h): (f32, f32, f32, f32), ppp: f32) -> [(f32, f32); 3] { + let (x, w) = swatch_across(x, w, ppp); let cy = y + h / 2.0; - match gt { - GeometryType::Polyline => { - let mut pb = PathBuilder::new(); - pb.move_to(x, cy + h * 0.2); - pb.line_to(x + w * 0.4, cy - h * 0.2); - pb.line_to(x + w, cy + h * 0.1); - if let Some(p) = pb.finish() { - pm.stroke_path( - &p, - &paint(s.stroke, 1.0), - &Stroke { width: s.stroke_width.max(1.0) * ppp, ..Stroke::default() }, - Transform::identity(), - None, - ); - } - } - _ => { - if let Some(b) = Rect::from_xywh(x, y + h * 0.2, w, h * 0.6) { - pm.fill_rect(b, &paint(s.fill, 1.0), Transform::identity(), None); - let p = PathBuilder::from_rect(b); - pm.stroke_path( - &p, - &paint(s.stroke, 1.0), - &Stroke { width: s.stroke_width.max(0.5) * ppp, ..Stroke::default() }, - Transform::identity(), - None, - ); - } + [(x, cy + h * 0.2), (x + w * 0.4, cy - h * 0.2), (x + w, cy + h * 0.1)] +} + +/// A polygon swatch's box in the box, in pixels. +fn swatch_box((x, y, w, h): (f32, f32, f32, f32), ppp: f32) -> Option { + let (x, w) = swatch_across(x, w, ppp); + Rect::from_xywh(x, y + h * 0.2, w, h * 0.6) +} + +/// A line or polygon swatch of the symbol `s` alone, its shape at `ppp` and its widths at `wppp`. +fn flat_swatch(pm: &mut Canvas, cell: (f32, f32, f32, f32), gt: GeometryType, s: &rustgis_map::Symbol, (ppp, wppp): (f32, f32)) { + if gt == GeometryType::Polyline { + let [a, b, c] = swatch_line(cell, ppp); + let mut pb = PathBuilder::new(); + pb.move_to(a.0, a.1); + pb.line_to(b.0, b.1); + pb.line_to(c.0, c.1); + if let Some(p) = pb.finish() { + pm.stroke_path( + &p, + &paint(s.stroke, 1.0), + &Stroke { width: s.stroke_width.max(1.0) * wppp, ..Stroke::default() }, + Transform::identity(), + None, + ); } + } else if let Some(b) = swatch_box(cell, ppp) { + pm.fill_rect(b, &paint(s.fill, 1.0), Transform::identity(), None); + let p = PathBuilder::from_rect(b); + pm.stroke_path( + &p, + &paint(s.stroke, 1.0), + &Stroke { width: s.stroke_width.max(0.5) * wppp, ..Stroke::default() }, + Transform::identity(), + None, + ); + } +} + +/// A line or polygon swatch with its stacked `strokes` or `fills`, drawn by the map's own paths +/// for a feature of that shape: [`crate::stroke_paths::Paths`] and [`crate::Ctx::filled`], at +/// `ppp` and the layer's reference scale `k`. The canvas stands for a view whose map units are +/// its points, y up, so the shape's pixels are its coordinates. +fn stacked_swatch( + pm: &mut Canvas, + cell: (f32, f32, f32, f32), + l: &rustgis_map::Layer, + (s, strokes, fills): (&rustgis_map::Symbol, &[rustgis_map::LineStroke], &[rustgis_map::fills::FillLayer]), + ppp: f32, + k: f32, +) { + let (w, h) = (f64::from(pm.width()) / f64::from(ppp), f64::from(pm.height()) / f64::from(ppp)); + let camera = rustgis_map::Camera::new(Coord::new(w / 2.0, -h / 2.0), 1.0); + let view = View { width: w, height: h, pixels_per_point: f64::from(ppp), camera, sky: false }; + let ctx = crate::Ctx { + view: &view, + ppp: ppp * k, + wireframe: false, + cull: Extent::EMPTY, + globe: None, + sprites: Default::default(), + bursts: Default::default(), + }; + let at = |(x, y): (f32, f32)| Coord::new(f64::from(x / ppp), -f64::from(y / ppp)); + if l.geometry_type() == GeometryType::Polyline { + // Drawn level by level, as the map draws a feature's strokes with symbol levels on. + let mut ordered: Vec<(usize, rustgis_map::LineStroke)> = strokes.iter().copied().enumerate().collect(); + if l.stroke_levels { + ordered.sort_by_key(|(i, st)| st.level_at(*i)); + } + let ordered: Vec = ordered.into_iter().map(|(_, st)| st).collect(); + let part: Vec = swatch_line(cell, ppp).into_iter().map(at).collect(); + crate::stroke_paths::Paths::default().draw(&ctx, pm, &[part], s, &ordered); + } else if let Some(b) = swatch_box(cell, ppp) { + let ring: Vec = + [(b.left(), b.top()), (b.right(), b.top()), (b.right(), b.bottom()), (b.left(), b.bottom()), (b.left(), b.top())] + .into_iter() + .map(at) + .collect(); + ctx.filled(pm, &[vec![ring]], s, fills); } } @@ -3045,12 +3130,19 @@ fn point_swatch( draw_point(pm, (cx, cy), s, strokes, ppp); return; } + composited(pm, (x, y, w, h), opacity, |c, (left, top)| draw_point(c, (cx - left, cy - top), s, strokes, ppp)); +} + +/// Draws by `draw` into a picture of the box (`x`, `y`, `w`, `h`), no larger than the page, and +/// composites it as one at `opacity`, cut to the box. `draw` gets the picture and where its corner +/// sits on the canvas, in pixels. +fn composited(pm: &mut Canvas, (x, y, w, h): (f32, f32, f32, f32), opacity: f32, draw: impl FnOnce(&mut Canvas, (f32, f32))) { // Kept on the canvas: a picture as large as the canvas then covers all of it that shows. let (left, top) = (x.floor().max(0.0), y.floor().max(0.0)); let (cw, ch) = (((x + w).ceil() - left) as u32, ((y + h).ceil() - top) as u32); let (cw, ch) = (cw.min(pm.width()), ch.min(pm.height())); if let Some(mut picture) = pm.sub(cw, ch) { - draw_point(&mut picture, (cx - left, cy - top), s, strokes, ppp); + draw(&mut picture, (left, top)); // A recording keeps what lies past its picture's edge, so it is cut here, at the box. let clip = Rect::from_xywh(x, y, w, h).map(|r| crate::vector::Clip { path: PathBuilder::from_rect(r), @@ -7376,6 +7468,255 @@ Elaboração: RustGIS", assert_eq!(at(14, 37), Some((0, 255, 0))); } + /// A one-feature line or polygon layer, edited by `edit`. + fn shape_legend_map(gt: GeometryType, edit: impl FnOnce(&mut rustgis_map::Layer)) -> Map { + use rustgis_data::{Dataset, Geometry}; + let mut map = Map::new("m"); + let mut d = Dataset::new("shapes", gt, vec![]); + let (a, b, c) = (Coord::new(0.0, 0.0), Coord::new(1.0, 0.0), Coord::new(1.0, 1.0)); + let g = match gt { + GeometryType::Polyline => Geometry::Line(vec![vec![a, c]]), + _ => Geometry::Polygon(vec![vec![vec![a, b, c, a]]]), + }; + d.push(Some(g), vec![]); + map.add_dataset(d); + if let Some(l) = map.layers.last_mut() { + edit(l); + } + map + } + + /// How many pixels in `xs` × `ys` are within 40 of `c` in every channel. + fn inked(pm: &Pixmap, xs: std::ops::Range, ys: std::ops::Range, c: Rgba) -> usize { + let near = |a: u8, b: u8| a.abs_diff(b) <= 40; + ys.flat_map(|y| xs.clone().map(move |x| (x, y))) + .filter(|(x, y)| pm.pixel(*x, *y).is_some_and(|p| near(p.red(), c.r()) && near(p.green(), c.g()) && near(p.blue(), c.b()))) + .count() + } + + /// A stacked stroke `width` points wide in `color`. + fn plain_stroke(color: Rgba, width: f32) -> rustgis_map::LineStroke { + rustgis_map::LineStroke { color: Some(color), width: Some(width), ..rustgis_map::LineStroke::default() } + } + + /// Hatch lines `spacing` points apart, a point wide, across. + fn hatch(color: Rgba, spacing: f32) -> rustgis_map::fills::FillLayer { + rustgis_map::fills::FillLayer { + color: Some(color), + pattern: rustgis_map::fills::FillPattern::Hatch { angle: 0.0, spacing, width: 1.0, offset: 0.0 }, + } + } + + /// A line or polygon layer with no stacked strokes or fills keeps the swatch it always had, + /// pixel for pixel (#2490): a line through three points, or a box with its outline. + #[test] + fn a_plain_line_or_polygon_keeps_its_swatch() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(255, 0, 0), + stroke: Rgba::rgb(0, 0, 255), + stroke_width: 2.0, + ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) + }; + for gt in [GeometryType::Polyline, GeometryType::Polygon] { + let map = shape_legend_map(gt, |l| l.renderer = rustgis_map::Renderer::Single(s)); + let mut want = Pixmap::new(200, 200).unwrap(); + want.fill(tiny_skia::Color::WHITE); + let stroke = Stroke { width: 2.0, ..Stroke::default() }; + crate::canvas::with_canvas(&mut want, |c| { + if gt == GeometryType::Polyline { + let mut pb = PathBuilder::new(); + pb.move_to(0.0, 10.5); + pb.line_to(6.4, 4.5); + pb.line_to(16.0, 9.0); + c.stroke_path(&pb.finish().unwrap(), &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); + } else { + let b = Rect::from_xywh(0.0, 3.0, 16.0, 9.0).unwrap(); + c.fill_rect(b, &paint(s.fill, 1.0), Transform::identity(), None); + c.stroke_path(&PathBuilder::from_rect(b), &paint(s.stroke, 1.0), &stroke, Transform::identity(), None); + } + }); + assert!(same_corner(&point_legend(&map), &want, 16, 15), "{gt:?}"); + } + } + + /// A line's stacked strokes show in its swatch as on the map: a casing under its core, and + /// dashes (#2490). + #[test] + fn a_legend_draws_a_lines_casing_and_dashes() { + let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); + let drawn = + |strokes: Vec| point_legend(&shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = strokes)); + let cased = drawn(vec![plain_stroke(black, 8.0), plain_stroke(red, 2.0)]); + assert!(inked(&cased, 0..16, 0..15, black) > 20, "the casing"); + assert!(inked(&cased, 0..16, 0..15, red) > 5, "the core over it"); + let dashed = rustgis_map::LineStroke { + dash: rustgis_map::symbology::Dash::new(&[2.0, 4.0]), + cap: rustgis_map::LineCap::Butt, + ..plain_stroke(red, 2.0) + }; + let dashed = drawn(vec![plain_stroke(black, 8.0), dashed]); + assert!(inked(&dashed, 0..16, 0..15, red) * 3 < inked(&cased, 0..16, 0..15, red) * 2, "a dashed core shows less of it"); + // One plain stroke draws in its own colour alone. + assert_eq!(inked(&drawn(vec![plain_stroke(red, 2.0)]), 0..16, 0..15, black), 0); + } + + /// Markers along a line show in its swatch (#2490). + #[test] + fn a_legend_draws_markers_along_a_line() { + let blue = Rgba::rgb(0, 0, 255); + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![plain_stroke(Rgba::rgb(128, 128, 128), 1.0), square_mark(blue, 6.0)]; + }); + assert!(inked(&point_legend(&map), 0..16, 0..15, blue) > 10); + } + + /// With symbol levels on, a line's swatch draws its strokes level by level, as the map does. + #[test] + fn a_legend_draws_a_lines_strokes_by_level() { + let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); + let drawn = |levels: bool| { + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![ + rustgis_map::LineStroke { level: Some(1), ..plain_stroke(red, 2.0) }, + rustgis_map::LineStroke { level: Some(0), ..plain_stroke(black, 8.0) }, + ]; + l.stroke_levels = levels; + }); + inked(&point_legend(&map), 0..16, 0..15, red) + }; + assert!(drawn(true) > 5, "the core's level is above the casing's"); + assert_eq!(drawn(false), 0, "in their order, the casing covers the core"); + } + + /// A stroke shifted past its row is cut at the swatch's box, not drawn over the next row. + #[test] + fn a_legend_cuts_a_shifted_stroke_at_its_box() { + let red = Rgba::rgb(255, 0, 0); + for (offset, shows) in [(4.0, true), (30.0, false)] { + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![rustgis_map::LineStroke { offset, ..plain_stroke(red, 3.0) }]; + }); + let pm = point_legend(&map); + assert_eq!(inked(&pm, 0..16, 0..15, red) > 0, shows, "offset {offset}"); + assert_eq!(inked(&pm, 0..200, 15..200, red), 0, "offset {offset}: nothing below its row"); + } + // One plain stroke wider than the row is cut at it too. + let map = shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = vec![plain_stroke(red, 30.0)]); + let pm = point_legend(&map); + assert!(inked(&pm, 0..16, 0..15, red) > 50); + assert_eq!(inked(&pm, 0..200, 15..200, red), 0, "a wide stroke: nothing below its row"); + } + + /// A polygon's stacked fills show in its swatch: a hatch over a fill, and a class's own fills + /// in its row, the other classes' plain (#2490). + #[test] + fn a_legend_draws_a_polygons_stacked_fills() { + let (black, red, white) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0), Rgba::rgb(255, 255, 255)); + let solid = rustgis_map::fills::FillLayer { color: Some(Rgba::rgb(0, 200, 0)), pattern: rustgis_map::fills::FillPattern::Solid }; + let map = shape_legend_map(GeometryType::Polygon, |l| l.fill_layers = vec![solid, hatch(black, 3.0)]); + let pm = point_legend(&map); + assert!(inked(&pm, 1..15, 4..11, black) > 5, "the hatch"); + assert!(inked(&pm, 1..15, 4..11, Rgba::rgb(0, 200, 0)) > 5, "the fill under it"); + // Classes: only the first has fills of its own, and the layer none. + let s = rustgis_map::Symbol { fill: red, stroke_width: 0.0, ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) }; + let map = shape_legend_map(GeometryType::Polygon, |l| { + l.renderer = rustgis_map::Renderer::Unique { + field: "g".into(), + classes: vec![("a".to_string(), s), ("b".to_string(), s)], + other: s, + ramp: rustgis_map::Ramp::Ember, + class_labels: Default::default(), + other_label: None, + class_strokes: Default::default(), + other_strokes: Vec::new(), + class_fills: [("a".to_string(), vec![hatch(black, 3.0)])].into_iter().collect(), + other_fills: Vec::new(), + expression: None, + }; + }); + let pm = point_legend(&map); + // The layer's name, then a row a class, the swatch 6 points in. + assert!(inked(&pm, 7..21, 19..26, black) > 5, "class a's hatch"); + assert_eq!(inked(&pm, 7..21, 19..26, red), 0, "a hatch with no fill under it leaves the paper"); + assert!(inked(&pm, 7..21, 19..26, white) > 5); + assert_eq!(inked(&pm, 7..21, 34..41, black), 0, "class b has none"); + assert!(inked(&pm, 7..21, 34..41, red) > 50, "its symbol's fill"); + } + + /// A diagram's categories keep their own colour on a layer with stacked strokes or fills. + #[test] + fn a_diagrams_rows_keep_their_colour_on_lines_and_polygons() { + let (black, red, green) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0), Rgba::rgb(0, 255, 0)); + let category = |field: &str, colour| rustgis_map::DiagramCategory { field: field.into(), colour }; + for gt in [GeometryType::Polyline, GeometryType::Polygon] { + let map = shape_legend_map(gt, |l| { + l.line_strokes = vec![plain_stroke(black, 8.0)]; + l.fill_layers = vec![hatch(black, 3.0)]; + l.diagram = Some(rustgis_map::DiagramSettings { + kind: rustgis_map::DiagramKind::Pie, + categories: vec![category("a", red), category("b", green)], + size: rustgis_map::DiagramSize::Fixed(12.0), + start_angle: 0.0, + background: None, + stroke: rustgis_map::DiagramSettings::default_stroke(), + stroke_width: 0.75, + labels: rustgis_map::DiagramLabel::None, + }); + }); + let pm = point_legend(&map); + assert_eq!(inked(&pm, 6..22, 15..45, black), 0, "{gt:?}: not the layer's stack"); + // A one-point line is mostly part-covered pixels: its hue tells it. + let tinted = |ys: std::ops::Range, hue: fn(tiny_skia::PremultipliedColorU8) -> bool| { + ys.flat_map(|y| (6..22).map(move |x| (x, y))).filter(|(x, y)| pm.pixel(*x, *y).is_some_and(hue)).count() + }; + assert!(tinted(15..30, |p| p.red() > p.green().saturating_add(60)) > 5, "{gt:?}: red"); + assert!(tinted(30..45, |p| p.green() > p.red().saturating_add(60)) > 5, "{gt:?}: green"); + } + } + + /// A see-through line or polygon layer's swatch is see-through too, as its points' are. + #[test] + fn a_legend_draws_a_see_through_polygon_see_through() { + let s = rustgis_map::Symbol { + fill: Rgba::rgb(255, 0, 0), + stroke_width: 0.0, + ..rustgis_map::Symbol::default_for(GeometryType::Polygon, 0) + }; + let map = shape_legend_map(GeometryType::Polygon, |l| { + l.renderer = rustgis_map::Renderer::Single(s); + l.transparency = 50.0; + }); + let p = point_legend(&map).pixel(8, 7).unwrap(); + assert_eq!(p.red(), 255); + assert!((100..160).contains(&p.green()), "{}", p.green()); + } + + /// A line grows with its layer's reference scale in the swatch, as on the map. + #[test] + fn a_legend_scales_a_line_with_its_reference_scale() { + let blue = Rgba::rgb(0, 0, 255); + let drawn = |reference: Option| { + let map = shape_legend_map(GeometryType::Polyline, |l| { + l.line_strokes = vec![plain_stroke(blue, 2.0)]; + l.reference_scale = reference; + }); + inked(&point_legend(&map), 0..16, 0..15, blue) + }; + // Drawn at 1:1e6: a reference of 1:2e6 makes it twice as wide. + assert!(drawn(Some(2e6)) * 2 > drawn(None) * 3, "{} against {}", drawn(Some(2e6)), drawn(None)); + } + + /// A vector export draws the stacked fills and strokes a raster one does. + #[test] + fn a_recorded_legend_draws_stacked_fills_and_strokes() { + let (black, red) = (Rgba::rgb(0, 0, 0), Rgba::rgb(255, 0, 0)); + let map = shape_legend_map(GeometryType::Polygon, |l| l.fill_layers = vec![hatch(black, 3.0)]); + assert!(inked(&recorded_legend(&map, 200), 1..15, 4..11, black) > 5); + let map = shape_legend_map(GeometryType::Polyline, |l| l.line_strokes = vec![plain_stroke(black, 8.0), plain_stroke(red, 2.0)]); + let pm = recorded_legend(&map, 200); + assert!(inked(&pm, 0..16, 0..15, black) > 20 && inked(&pm, 0..16, 0..15, red) > 5); + } + /// A box off the pixel grid: a recording cuts its symbol at the box, not at the whole pixels /// round it, so the pixel its edge crosses is half covered. #[test] diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 99617fe04f..5c31ad2f99 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -287,7 +287,8 @@ Widths and offsets are in points: they keep their size on screen at every scale, keep their coordinates. A positive offset shifts the stroke to the right of the line's direction (the order of its vertices) and a negative one to the left, so two copies of an edge drawn in opposite directions land on opposite sides of it. Strokes are saved with the project and drawn in -exports. By command, bottom stroke first (`[]` goes back to the single stroke): +exports and in a layout legend's swatch. By command, bottom stroke first (`[]` goes back to the +single stroke): ```text layer.lineStrokes={"layer":"Rivers","strokes":[{"color":"#000000","width":11.5,"offset":8.5},{"color":"#FF8C00","width":7,"offset":8.5,"cap":"round","join":"round"}]} @@ -398,8 +399,8 @@ A gradient's `from` and `to` are places in the feature's box (`[across, down]`, (`[[0.5, "#RRGGBB"], …]`), held rather than blended with `"discrete": true`. `[]` goes back to the single fill (for a class, to the layer's fills). Fills draw on the CPU (on the -globe, patterns keep to the screen rather than the map as it turns); the -legend shows the symbol's colour. +globe, patterns keep to the screen rather than the map as it turns). A layout legend draws +them in the polygon's swatch; the Layers pane's legend shows the symbol's colour. **Hatch only flagged polygons.** Use an overlay to hatch unreliable estimates while keeping the choropleth's colours visible. @@ -411,7 +412,8 @@ the choropleth's colours visible. colour and spacing so the choropleth shows through. Set **Outline width** to 0 if the choropleth already draws the boundaries. 3. Include both layers in the [layout legend](layouts.md#layouts). The overlay's swatch - uses a solid colour, so keep “(hatched)” in its name or legend label to explain the pattern. + shows its hatch lines; the Layers pane shows a solid colour, so a name such as + “(hatched)” still helps there. The new layer contains a copy of the selected features. Recreate it if the flag values change. diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 28977ee347..a975f5ca62 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -311,6 +311,13 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu symbols grow to hold a large one, up to 2048 points, past which the symbol is cut. A legend already on the page keeps its size, so with a larger symbol its last rows may be cut and its labels run past its right edge: make it larger to fit. + - **Line and polygon symbols**: a line's swatch is drawn with the stacked strokes of its class or + layer (casings, offsets, dashes, markers and images along it, by symbol level when the layer + draws by levels), and a polygon's with its stacked fills (hatches, dots, gradients, + shapeburst), as the map draws them, with the transparency of the layer and its groups and its + reference scale at the frame's scale. A stroke wider than the row, or shifted off it, is cut at + the row; the row keeps its height. A diagram's categories keep their own colour. A layer with + no stacked strokes or fills keeps its plain swatch, see-through with the layer. - **Web layers**: a visible WMS or WMTS layer with a legend is listed by its name over its service's legend picture, the one for the frame's scale (as the Layers pane shows it), a pixel a point and narrowed to fit the legend's width, in the order the map draws its layers From 040ef48871ecd14f73b185819eaf8a7ff63427e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Fri, 20 Nov 2026 09:35:42 -0500 Subject: [PATCH 2/2] fix(render): build with main's legend rows, cut swatches with a swatch-sized mask (#2490) --- crates/render/src/layout.rs | 18 ++++++++++++------ crates/ui-egui/src/panes.rs | 2 +- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index f8cf1251e9..f567af604d 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -3143,12 +3143,18 @@ fn composited(pm: &mut Canvas, (x, y, w, h): (f32, f32, f32, f32), opacity: f32, let (cw, ch) = (cw.min(pm.width()), ch.min(pm.height())); if let Some(mut picture) = pm.sub(cw, ch) { draw(&mut picture, (left, top)); - // A recording keeps what lies past its picture's edge, so it is cut here, at the box. - let clip = Rect::from_xywh(x, y, w, h).map(|r| crate::vector::Clip { - path: PathBuilder::from_rect(r), - rule: FillRule::Winding, - transform: Transform::identity(), - }); + let Some(r) = Rect::from_xywh(x, y, w, h) else { return }; + let clip = if picture.is_recording() { + // A recording keeps what lies past its picture's edge, so it is cut here, at the box. + Some(crate::vector::Clip { path: PathBuilder::from_rect(r), rule: FillRule::Winding, transform: Transform::identity() }) + } else { + // Pixels are cut in the picture, by a mask its size rather than the page's. + if let Some(mut m) = Mask::new(cw, ch) { + m.fill_path(&PathBuilder::from_rect(r), FillRule::Winding, true, Transform::from_translate(-left, -top)); + picture.pixels().apply_mask(&m); + } + None + }; pm.place(picture, Transform::from_translate(left, top), opacity, rustgis_map::effects::Blend::Normal, clip); } } diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 88cdb7c698..ae92ee231d 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -8871,7 +8871,7 @@ mod tests { named.set_class_style(&ClassRef::Index(1), &ClassStyle { label: Some("up to 4".into()), ..Default::default() }, g).unwrap(); assert_eq!(labels(interface_legend(&named, named.legend())), ["up to 4", "up to 4", more_than.as_str()]); // Another renderer's row named like an open class is left alone. - let row = LegendEntry { label: "up to 4".into(), symbol: Symbol::default_for(g, 0), strokes: Vec::new(), fallback: false }; + let row = LegendEntry::plain("up to 4".into(), Symbol::default_for(g, 0)); assert_eq!(labels(interface_legend(&Renderer::Single(Symbol::default_for(g, 0)), vec![row])), ["up to 4"]); }