From 362b0305548d1c2d290975e23bddbaa0c4cf6860 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 13:41:10 +0100 Subject: [PATCH 1/2] perf(render): a GPU layer's meshes cut into tiles and made on several threads (#2541) --- crates/render/examples/vector_layers_bench.rs | 5 +- crates/render/src/gpu_scene.rs | 21 +- crates/render/src/layer_meshes.rs | 24 +- crates/render/src/lib.rs | 86 +-- crates/render/src/mesh.rs | 129 ++-- crates/render/src/mesh_tiles.rs | 575 ++++++++++++++++++ crates/render/src/stream_tests.rs | 18 +- crates/render/src/tile_mesh.rs | 10 +- crates/ui-egui/src/mapgpu.rs | 78 ++- crates/ui-egui/src/mapgpu.wgsl | 11 + 10 files changed, 849 insertions(+), 108 deletions(-) create mode 100644 crates/render/src/mesh_tiles.rs diff --git a/crates/render/examples/vector_layers_bench.rs b/crates/render/examples/vector_layers_bench.rs index 78a068cfc2..31f10f7dc5 100644 --- a/crates/render/examples/vector_layers_bench.rs +++ b/crates/render/examples/vector_layers_bench.rs @@ -128,10 +128,11 @@ fn main() { let mut m = Map::new("bench"); m.basemap = Basemap::Blank; let mut layers = Vec::new(); - // The data's extent, longitude/latitude: the sequences are fitted to it. + // The data's extent, longitude/latitude: the sequences are fitted to it. A layer is held in + // its file's own system (a sheet's LV95, say), so its box is converted. let mut extent = rustgis_geom::Extent::EMPTY; for d in datasets { - extent = extent.union(&d.extent()); + extent = extent.union(&d.extent_to_lonlat(&d.extent())); let vertices: usize = d.features.iter().filter_map(|f| f.geometry.as_ref()).map(rustgis_map::lod::vertices).sum(); let (name, rows) = (d.name.clone(), d.features.len()); layers.push((m.add_dataset(d), name, rows, vertices)); diff --git a/crates/render/src/gpu_scene.rs b/crates/render/src/gpu_scene.rs index 722754338d..3161502beb 100644 --- a/crates/render/src/gpu_scene.rs +++ b/crates/render/src/gpu_scene.rs @@ -109,10 +109,19 @@ pub enum DrawCmd { /// picture lives. A see-through layer drawn alone is one at the layer's opacity, so a change /// of transparency alone draws nothing again. Image { pixmap: Arc, opacity: f32 }, - /// Tessellated polygon fills and line/ring strokes of one layer run. Shared: a layer that looks - /// as it did keeps its mesh from one scene to the next (`layer_meshes`), and the GPU keeps the - /// buffers of a mesh it has uploaded while the mesh lives. - Mesh { origin: [f64; 2], vertices: Arc>, indices: Arc> }, + /// Tessellated polygon fills and line/ring strokes of one layer run, or of one tile of it + /// (`mesh_tiles`). Shared: a layer that looks as it did keeps its meshes from one scene to + /// the next (`layer_meshes`), and the GPU keeps the buffers of a mesh it has uploaded while + /// the mesh lives. + Mesh { + origin: [f64; 2], + vertices: Arc>, + indices: Arc>, + /// A tile's mesh is drawn only inside its square (least x and y, greatest x and y, map + /// units from `origin`): its features are cut a stroke's reach past it, and the next + /// tile draws the rest. + square: Option<[f32; 4]>, + }, /// Point markers: instances of a small set of unit-space shape templates, shared as /// [`DrawCmd::Mesh`] is. Points { origin: [f64; 2], instances: Arc> }, @@ -141,8 +150,8 @@ impl DrawCmd { pub fn share(&self) -> Option { Some(match self { DrawCmd::Image { pixmap, opacity } => DrawCmd::Image { pixmap: Arc::clone(pixmap), opacity: *opacity }, - DrawCmd::Mesh { origin, vertices, indices } => { - DrawCmd::Mesh { origin: *origin, vertices: Arc::clone(vertices), indices: Arc::clone(indices) } + DrawCmd::Mesh { origin, vertices, indices, square } => { + DrawCmd::Mesh { origin: *origin, vertices: Arc::clone(vertices), indices: Arc::clone(indices), square: *square } } DrawCmd::Points { origin, instances } => DrawCmd::Points { origin: *origin, instances: Arc::clone(instances) }, DrawCmd::Extrusion { .. } => return None, diff --git a/crates/render/src/layer_meshes.rs b/crates/render/src/layer_meshes.rs index c39c9864e9..de4d4ddc11 100644 --- a/crates/render/src/layer_meshes.rs +++ b/crates/render/src/layer_meshes.rs @@ -1,10 +1,11 @@ //! Each layer's GPU mesh kept from one scene to the next (#1057): restyling, editing or //! filtering one layer of a map drawn on the GPU tessellates that layer again, not every layer. //! -//! A layer's mesh ([`crate::mesh::collect_layer`]) is made from the layer, the geometry copy it -//! draws, the rows it draws, and the view: which features reach it (the GPU's cull, wider than -//! the view so the camera can move the scene), the 0.35 px decimation, the stroke widths in -//! pixels and where f32 holds its vertices. A kept mesh is taken again when all of those are +//! A layer's mesh ([`crate::mesh::collect_layer`]: its tiles' meshes and its markers) is made +//! from the layer, the geometry copy it draws, the rows it draws, and the view: which features +//! reach it (the GPU's cull, wider than the view so the camera can move the scene), the 0.35 px +//! decimation, the tiles at that scale, the stroke widths in pixels and where f32 holds its +//! vertices. A kept mesh is taken again when all of those are //! as they were: the layer by its look ([`LayerLook`]), the rest by [`Made`] and the rows drawn. //! The mesh taken is then the one tessellating the layer again would make, vertex for vertex. //! @@ -125,8 +126,8 @@ impl Meshes { /// A command sharing `cmd`'s data, when it is a mesh or points. fn share(cmd: &DrawCmd) -> Option { match cmd { - DrawCmd::Mesh { origin, vertices, indices } => { - Some(DrawCmd::Mesh { origin: *origin, vertices: Arc::clone(vertices), indices: Arc::clone(indices) }) + DrawCmd::Mesh { origin, vertices, indices, square } => { + Some(DrawCmd::Mesh { origin: *origin, vertices: Arc::clone(vertices), indices: Arc::clone(indices), square: *square }) } DrawCmd::Points { origin, instances } => Some(DrawCmd::Points { origin: *origin, instances: Arc::clone(instances) }), _ => None, @@ -349,8 +350,11 @@ mod tests { use rustgis_geom::{Coord, Extent}; use rustgis_map::{Camera, Map, Renderer, Rgba, Symbol}; + /// A square `s` degrees on a side, its south-west corner at `x` east and 0.2° north: clear of + /// the borders of the meshes' tiles at the views here, so a layer is one mesh. fn square(x: f64, s: f64) -> Geometry { - Geometry::Polygon(vec![vec![vec![Coord::new(x, 0.0), Coord::new(x + s, 0.0), Coord::new(x + s, s), Coord::new(x, s)]]]) + let y = 0.2; + Geometry::Polygon(vec![vec![vec![Coord::new(x, y), Coord::new(x + s, y), Coord::new(x + s, y + s), Coord::new(x, y + s)]]]) } /// A map of two polygon layers drawn on the GPU, `a` under `b`, and a view of them. @@ -364,8 +368,8 @@ mod tests { d.push(Some(square(x, 1.0)), vec![]); m.add_dataset(d) }; - let (a, b) = (layer("a", 0.0), layer("b", 2.0)); - let camera = Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(1.5, 0.5)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; + let (a, b) = (layer("a", 0.2), layer("b", 2.2)); + let camera = Camera { center: rustgis_geom::lonlat_to_merc(Coord::new(1.7, 0.7)), res: 2000.0, bearing: 0.0, pitch: 0.0 }; (m, a, b, View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }) } @@ -509,6 +513,7 @@ mod tests { origin: [0.0; 2], vertices: Arc::new(vec![bytemuck::Zeroable::zeroed(); n]), indices: Arc::new(Vec::new()), + square: None, }; let one = bytes_of(&[mesh(4096)]) + ENTRY_BYTES + 1; // Room for two of the three. @@ -579,6 +584,7 @@ mod tests { origin: [0.0; 2], vertices: Arc::new(vec![bytemuck::Zeroable::zeroed(); n]), indices: Arc::new(Vec::new()), + square: None, }; let size = |n: usize| bytes_of(&[mesh(n)]) + ENTRY_BYTES + 1; let max = size(6000) + size(3000) + size(500); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 426475cad9..3e0eb317e5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -27,6 +27,7 @@ mod line_markers; pub mod logo; mod mapgrid; mod mesh; +mod mesh_tiles; mod native_tiles; mod pattern_fill; pub mod pdf; @@ -4732,6 +4733,9 @@ fn render_frame( }; // GPU meshes reach further (`GPU_CULL_MARGIN`), so the camera fast path can move them. let mesh_cull = cull_extent(view, GPU_CULL_MARGIN); + // A tilted view widens a far stroke past a tile's reach (the shader scales it by depth), so + // it keeps one mesh a layer; a flat one cuts its layers into tiles of the cull. + let mesh_tiled = (view.camera.pitch == 0.0).then_some(&mesh_cull); let mesh_visible = |e: &Extent| match &globe { Some(g) => g.may_see(e), None => e.intersects(&mesh_cull), @@ -5574,9 +5578,10 @@ fn render_frame( && layer.renderer.expression().is_none() && !upright.contains(&layer.id); // Lyon refuses degenerate geometry tiny-skia draws fine, a layer too dense to mesh - // (`MAX_LAYER_VERTICES`) is quicker splatted, and zoomed in far, features reaching too - // far for f32 are drawn where they are by the CPU (#902): collect_layer reports all - // three, and the layer runs the CPU branch below like any ineligible one. It meshes the + // (`MAX_LAYER_VERTICES`) is quicker splatted, and zoomed in far, markers reaching too + // far for f32 are drawn where they are by the CPU (#902; lines and polygons are meshed + // in tiles, each from its own corner, `mesh_tiles`): collect_layer reports all three, + // and the layer runs the CPU branch below like any ineligible one. It meshes the // thinned copy the CPU draws. A turned or tilted view takes no CPU pictures // (`gpu_turned`), so there such a layer sends the whole view to the CPU renderer, not // just itself. @@ -5616,6 +5621,7 @@ fn render_frame( extents, &rows, &mesh_visible, + mesh_tiled, ctx.wireframe, ctx.ppp, map_per_px, @@ -11499,30 +11505,32 @@ mod tests { } } - /// So does one with a layer drawn on the CPU for another reason: a polygon reaching too far - /// from its origin for f32, zoomed in all the way. The layer above it is never meshed. + /// So does a turned one with a layer drawn on the CPU for another reason: markers too far + /// apart for f32 from their origin, zoomed in all the way (a tilted view stands markers up, + /// drawn otherwise). The layer above it is never meshed. #[test] - fn a_turned_or_tilted_view_stops_trying_the_gpu_after_a_layer_drawn_on_the_cpu() { + fn a_turned_view_stops_trying_the_gpu_after_a_layer_drawn_on_the_cpu() { let mut m = Map::new("Map"); // The world's outline is too far for f32 this far in as well: none. m.basemap = rustgis_map::Basemap::Blank; - // About 5 km across, over a view of a few centimetres. - square_layer(&mut m, "far", 1.0 - 0.025, 0.5 - 0.025, 0.05); + // One feature's markers about 5 km apart, one of them in a view of a few centimetres. + let mut far = Dataset::new("far", GeometryType::Point, vec![]); + far.push(Some(Geometry::MultiPoint(vec![Coord::new(1.0, 0.5), Coord::new(1.05, 0.5)])), vec![]); + m.add_dataset(far); square_layer(&mut m, "near", 1.0, 0.5, 1e-7); let at = lonlat_to_merc(Coord::new(1.0, 0.5)); - for (bearing, pitch) in [(30.0, 0.0), (0.0, 50.0)] { - let camera = Camera { center: at, res: rustgis_map::camera::MIN_RES, bearing, pitch }; - let view = View { width: 400.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; - MESHED.with(|m| m.borrow_mut().clear()); - let Some(RenderOutput::Cpu(gpu)) = render_backend(&mut m, &view, Backend::Gpu) else { - panic!("turned {bearing}°, tilted {pitch}°: drawn on the CPU") - }; - let meshed = MESHED.with(|m| m.borrow().clone()); - assert!(meshed.contains(&("far".into(), false)), "turned {bearing}°, tilted {pitch}°: tried: {meshed:?}"); - assert!(!meshed.iter().any(|(n, _)| n == "near"), "turned {bearing}°, tilted {pitch}°: went on: {meshed:?}"); - let cpu = render(&mut m, &view).expect("cpu"); - assert!(gpu.pixmap.data() == cpu.pixmap.data(), "turned {bearing}°, tilted {pitch}°: as the CPU draws it"); - } + let (bearing, pitch) = (30.0, 0.0); + let camera = Camera { center: at, res: rustgis_map::camera::MIN_RES, bearing, pitch }; + let view = View { width: 400.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + MESHED.with(|m| m.borrow_mut().clear()); + let Some(RenderOutput::Cpu(gpu)) = render_backend(&mut m, &view, Backend::Gpu) else { + panic!("turned {bearing}°, tilted {pitch}°: drawn on the CPU") + }; + let meshed = MESHED.with(|m| m.borrow().clone()); + assert!(meshed.contains(&("far".into(), false)), "turned {bearing}°, tilted {pitch}°: tried: {meshed:?}"); + assert!(!meshed.iter().any(|(n, _)| n == "near"), "turned {bearing}°, tilted {pitch}°: went on: {meshed:?}"); + let cpu = render(&mut m, &view).expect("cpu"); + assert!(gpu.pixmap.data() == cpu.pixmap.data(), "turned {bearing}°, tilted {pitch}°: as the CPU draws it"); } #[test] @@ -11639,10 +11647,11 @@ mod tests { } #[test] - fn zoomed_in_past_f32_large_features_are_drawn_on_the_cpu_where_they_are() { + fn zoomed_in_past_f32_large_features_are_meshed_in_tiles_near_their_origins() { // A 10° square's west edge at the deepest zoom (#902): its vertices lie hundreds of km - // from the mesh's origin, which f32 can't hold to a pixel at a tenth of a millimetre per - // pixel, so the layer is drawn on the CPU, with the edge through the middle of the view. + // from the view, which f32 can't hold to a pixel at a tenth of a millimetre per pixel + // from one origin. Cut into tiles (#2541), each mesh holds only its tile's part, from the + // tile's corner: the edge lies where it belongs, through the middle of the view. let mut m = Map::new("Map"); m.basemap = rustgis_map::Basemap::Blank; square_layer(&mut m, "s", 0.0, 40.0, 10.0); @@ -11652,25 +11661,28 @@ mod tests { let view = View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; let kinds = cmd_kinds(&scene); - assert!(!kinds.contains(&"mesh"), "no mesh f32 would misplace: {kinds:?}"); - let Some(pixmap) = scene.cmds.iter().find_map(|c| match c { - gpu_scene::DrawCmd::Image { pixmap, .. } => Some(pixmap), - _ => None, - }) else { - panic!("the square is drawn on the CPU: {kinds:?}") - }; - let alpha = |x: u32| pixmap.pixel(x, 150).map_or(0, |p| p.alpha()); - assert_eq!(alpha(195), 0, "west of the edge is outside the square"); - assert!(alpha(205) > 0, "east of the edge is inside it"); + assert!(kinds.contains(&"mesh") && !kinds.contains(&"image"), "meshed: {kinds:?}"); + let map_per_px = rustgis_map::camera::MIN_RES; + assert!(gpu_scene::f32_holds(gpu_scene::reach(&scene.cmds), map_per_px), "every tile within f32's reach"); + let mut west = f64::INFINITY; + for c in &scene.cmds { + if let gpu_scene::DrawCmd::Mesh { origin, vertices, square, .. } = c { + assert!(square.is_some(), "a tile"); + west = vertices.iter().map(|v| origin[0] + f64::from(v.position[0])).fold(west, f64::min); + } + } + assert!(west.abs() < map_per_px, "the edge where it belongs: {west}"); - // Zoomed out, the same square is a mesh, and the scene says how far in it holds. + // Zoomed out, the same square is cut into tiles too, and the scene says how far in it + // holds: as far as a tile's side (and its outline's reach past it) from its corner. let mut camera = view.camera; camera.res = 1_000.0; let view = View { camera, ..view }; let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; assert!(cmd_kinds(&scene).contains(&"mesh")); - let half = (rustgis_geom::lonlat_to_merc(Coord::new(10.0, 50.0)).y - rustgis_geom::lonlat_to_merc(Coord::new(0.0, 40.0)).y) / 2.0; - assert!((gpu_scene::reach(&scene.cmds) - half).abs() < 1.0, "reach {} vs {half}", gpu_scene::reach(&scene.cmds)); + let side = crate::mesh_tiles::tile_side(1_000.0).expect("tiles"); + let reach = gpu_scene::reach(&scene.cmds); + assert!(reach >= side && reach < side * 1.01, "reach {reach} vs a tile's side {side}"); } #[test] diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index 0cdc0174d0..8af436d1e9 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -210,7 +210,7 @@ pub(crate) fn fill_polygon( /// far past both edges (#1295). Tessellated wider than drawn only folds a few sharp joins /// lyon would not have. 1.0 when the product isn't a usable width (the tests' `map_per_px` of /// 0). -fn tessellation_width(width_px: f32, map_per_px: f64) -> f32 { +pub(crate) fn tessellation_width(width_px: f32, map_per_px: f64) -> f32 { let w = (f64::from(width_px) * map_per_px * (1.0 + 2.0 * GPU_CULL_MARGIN)) as f32; // The round joins' tolerance is a fraction of it: that must be a positive normal float too. if w > 0.0 && (w * STROKE_TOLERANCE).is_normal() { w } else { 1.0 } @@ -226,7 +226,7 @@ const STROKE_TOLERANCE: f32 = 0.005; /// vertex shader applies the real width. Ring outlines take no width floor (`Ctx::polygon`), /// line parts floor at half a physical pixel (`Ctx::line`). `Err(TooDense)` once the vertices /// would pass `limit`, as soon as one doesn't fit. -fn stroke( +pub(crate) fn stroke( rings: &[Vec], origin: [f64; 2], color: [f32; 4], @@ -327,7 +327,7 @@ pub(crate) fn marker_instances(c: Coord, origin: [f64; 2], s: &Symbol, ppp: f32, /// Appends a tessellated part with its indices rebased onto the shared vertex list. `Err` when /// lyon failed the part or the result would overflow the u32 index space. -fn extend_mesh( +pub(crate) fn extend_mesh( v: &mut Vec, i: &mut Vec, part: Result, Vec)>, TessError>, @@ -348,7 +348,7 @@ fn extend_mesh( /// no-ops, and not emitting them is identical output for less work. `Err` when lyon refuses /// the geometry, or once the mesh passes `limit` vertices — the layer then falls back to the /// CPU path entirely. -fn append_geometry( +pub(crate) fn append_geometry( v: &mut Vec, i: &mut Vec, pts: &mut Vec, @@ -407,7 +407,7 @@ pub(crate) const NO_LIMIT: usize = usize::MAX; /// draw as instances and count nothing. It is an early out, not a bound: lyon adds vertices /// where an EvenOdd ring crosses itself, and decimation drops some, so the tessellation itself /// stops at the limit ([`Capped`]). -fn estimate_vertices(g: &Geometry, s: &Symbol, wireframe: bool) -> usize { +pub(crate) fn estimate_vertices(g: &Geometry, s: &Symbol, wireframe: bool) -> usize { fn stroked<'a>(rings: impl Iterator>, closed: bool) -> usize { rings.map(|r| 2 * r.len() + joins(r, closed) + if closed { 0 } else { 32 }).sum() } @@ -440,14 +440,37 @@ fn estimate_vertices(g: &Geometry, s: &Symbol, wireframe: bool) -> usize { } } +/// How far a feature's stroke reaches past its geometry as tessellated, map units: half the +/// widest it is drawn at before the scene is made again ([`tessellation_width`]), and a pixel +/// at that scale beside it. 0 for a feature with no stroke (a fill, a point: markers aren't +/// tiled). +fn stroke_reach(g: &Geometry, s: &Symbol, wireframe: bool, ppp: f32, map_per_px: f64) -> f64 { + let width_px = match g { + Geometry::Point(_) | Geometry::MultiPoint(_) => return 0.0, + Geometry::Line(_) if s.stroke.a() > 0 => (s.stroke_width * ppp).max(0.5), + Geometry::Line(_) => return 0.0, + Geometry::Polygon(_) if wireframe => s.stroke_width.max(1.0) * ppp, + Geometry::Polygon(_) if s.stroke_width > 0.0 && s.stroke.a() > 0 => s.stroke_width * ppp, + Geometry::Polygon(_) => return 0.0, + }; + if !width_px.is_finite() { + return 0.0; + } + let widest = map_per_px * (1.0 + 2.0 * GPU_CULL_MARGIN); + f64::from(tessellation_width(width_px, map_per_px)) / 2.0 + widest +} + /// Collects one GPU-eligible layer, or one streamed batch of it, into Mesh/Points commands. /// `geoms`, `extents`, `rows` and `visible` are the render loop's own (geometries as the CPU /// draws them, their cached extents, row filter, extent cull), so the GPU draws exactly the -/// features the CPU would. `limit` is what is left of the layer's [`MAX_LAYER_VERTICES`] (its -/// earlier batches took the rest). `Ok` with the mesh vertices pushed; `Err(Refused)` when -/// lyon refused a feature, `Err(TooDense)` when the mesh would pass `limit`, `Err(Imprecise)` when -/// the features reach too far for f32 at this zoom — the caller then draws the layer -/// (or batch) with tiny-skia instead (nothing is pushed part-way). +/// features the CPU would. Its lines and polygons are cut into the tiles of `area` (the scene's +/// cull, [`crate::mesh_tiles`]), meshed on several threads, or made one mesh when `area` is +/// `None` (a tilted view, whose far strokes are wider than a tile's reach); its markers follow +/// them as one command. `limit` is what is left of the layer's [`MAX_LAYER_VERTICES`] (its earlier batches +/// took the rest). `Ok` with the mesh vertices pushed; `Err(Refused)` when lyon refused a +/// feature, `Err(TooDense)` when the mesh would pass `limit`, `Err(Imprecise)` when the +/// features reach too far for f32 at this zoom — the caller then draws the layer (or batch) +/// with tiny-skia instead (nothing is pushed part-way). pub(crate) fn collect_layer( cmds: &mut Vec, layer: &Layer, @@ -455,17 +478,20 @@ pub(crate) fn collect_layer( extents: &[Extent], rows: &[bool], visible: &dyn Fn(&Extent) -> bool, + area: Option<&Extent>, wireframe: bool, ppp: f32, map_per_px: f64, limit: usize, ) -> Result { - // Stable origin: the centre of the drawn features' extent, so the features are listed - // first — with their symbols and estimates, each worked out once. The same pass gives up on - // a layer too dense to mesh before any of it is tessellated. + // The features are listed first, with their symbols and estimates, each worked out once. + // The same pass gives up on a layer too dense to mesh before any of it is tessellated. + // Markers are kept apart: they draw as instances, after the layer's meshes. let mut ext = Extent::EMPTY; + let mut marked = Extent::EMPTY; let mut estimate = 0usize; let mut features = Vec::new(); + let mut markers = Vec::new(); for (row, g) in geoms.iter().enumerate() { let Some(g) = g else { continue }; // Culled on the extent the CPU path culls on (the full geometry's, cached), so both @@ -476,33 +502,68 @@ pub(crate) fn collect_layer( } ext = ext.union(&e); let s = layer.symbol(row); + if matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_)) { + // A character or an image has no shape template: its layer draws on the CPU. + if matches!(s.marker, Marker::Char(_) | Marker::Picture(_)) { + return Err(TessError::Refused); + } + marked = marked.union(&e); + markers.push((*g, s)); + continue; + } let n = estimate_vertices(g, &s, wireframe); estimate = estimate.saturating_add(n); if estimate > limit { return Err(TessError::TooDense); } - features.push((*g, s, n)); + let reach = stroke_reach(g, &s, wireframe, ppp, map_per_px); + features.push(crate::mesh_tiles::Feature { geometry: g, symbol: s, estimate: n, extent: e, reach }); } if ext.is_empty() { return Ok(0); } - let origin = origin_for(&ext, map_per_px)?; - let (mut v, mut i, mut pts) = (Vec::new(), Vec::new(), Vec::new()); - for (g, s, n) in &features { - // The estimate is rough: a feature estimated not to fit isn't started, and - // `append_geometry` stops one that overflows at the first vertex past the limit. - if v.len().saturating_add(*n) > limit { - return Err(TessError::TooDense); + let tiled = if features.is_empty() { + Some(Ok((Vec::new(), 0))) + } else { + area.and_then(|area| crate::mesh_tiles::tile_meshes(&features, area, wireframe, ppp, map_per_px, limit)) + }; + let (meshes, used) = match tiled { + Some(made) => made?, + // No tiles at this scale, or too many: one mesh, its origin the centre of the drawn + // features' extent. + None => { + let origin = origin_for(&ext, map_per_px)?; + let (mut v, mut i) = (Vec::new(), Vec::new()); + for f in &features { + // The estimate is rough: a feature estimated not to fit isn't started, and + // `append_geometry` stops one that overflows at the first vertex past the limit. + if v.len().saturating_add(f.estimate) > limit { + return Err(TessError::TooDense); + } + append_geometry(&mut v, &mut i, &mut Vec::new(), f.geometry, &f.symbol, origin, wireframe, ppp, map_per_px, limit)?; + } + let used = v.len(); + let mesh = (!i.is_empty()).then(|| DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i), square: None }); + (mesh.into_iter().collect(), used) } - append_geometry(&mut v, &mut i, &mut pts, g, s, origin, wireframe, ppp, map_per_px, limit)?; - } - let used = v.len(); - if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); - } - if !pts.is_empty() { - cmds.push(DrawCmd::Points { origin, instances: Arc::new(pts) }); - } + }; + // The markers' origin: the centre of their extent. + let points = if markers.is_empty() { + None + } else { + let origin = origin_for(&marked, map_per_px)?; + let mut pts = Vec::new(); + for (g, s) in &markers { + match g { + Geometry::Point(c) => pts.extend(marker_instances(*c, origin, s, ppp, None)), + Geometry::MultiPoint(cs) => cs.iter().for_each(|c| pts.extend(marker_instances(*c, origin, s, ppp, None))), + _ => {} + } + } + (!pts.is_empty()).then(|| DrawCmd::Points { origin, instances: Arc::new(pts) }) + }; + cmds.extend(meshes); + cmds.extend(points); Ok(used) } @@ -527,7 +588,7 @@ pub(crate) fn collect_highlight(cmds: &mut Vec, g: &Geometry, s: &Symbo )?; extend_mesh(&mut v, &mut i, stroke_lines(parts, origin, premul(s.stroke), s.stroke_width * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i), square: None }); } } Geometry::Polygon(polys) => { @@ -535,7 +596,7 @@ pub(crate) fn collect_highlight(cmds: &mut Vec, g: &Geometry, s: &Symbo extend_mesh(&mut v, &mut i, fill_polygon(polys, origin, premul(SELECTION.with_alpha(40)), map_per_px, NO_LIMIT))?; extend_mesh(&mut v, &mut i, stroke_rings(polys, origin, premul(SELECTION), 2.0 * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i), square: None }); } } } @@ -559,7 +620,7 @@ pub(crate) fn collect_basemap( extend_mesh(&mut v, &mut i, stroke_rings(polys, origin, premul(outline), 0.6 * ppp, map_per_px, NO_LIMIT))?; } if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i), square: None }); } Ok(()) } @@ -578,7 +639,7 @@ pub(crate) fn collect_graticule( let (mut v, mut i) = (Vec::new(), Vec::new()); extend_mesh(&mut v, &mut i, stroke_lines(lines, origin, premul(grat), width * ppp, map_per_px, NO_LIMIT))?; if !i.is_empty() { - cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i) }); + cmds.push(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i), square: None }); } Ok(()) } diff --git a/crates/render/src/mesh_tiles.rs b/crates/render/src/mesh_tiles.rs new file mode 100644 index 0000000000..3cfcf08b9d --- /dev/null +++ b/crates/render/src/mesh_tiles.rs @@ -0,0 +1,575 @@ +//! A layer's GPU mesh cut into square tiles (#2541), each tessellated on its own and drawn only +//! inside its square (the GPU marks the square in the stencil, as it draws vector tiles), so a +//! layer's tiles can be tessellated on several threads. +//! +//! The tiles are a grid of squares, a power of two map units on a side: the one nearest +//! [`TILE_PX`] physical pixels at the scene's scale. Each tile's mesh has the tile's south-west +//! corner as its origin. A feature reaches the tiles its extent touches, grown by half its +//! stroke's width as tessellated ([`crate::mesh`]'s `tessellation_width`): a stroke near a +//! border spills into the next tile, and that tile draws the spill. A feature lying wholly +//! within a tile grown by that much is tessellated as it is. A larger one is cut to the grown +//! tile first, so a big polygon isn't tessellated whole in every tile it touches: +//! - a fill's rings are clipped to it (Sutherland–Hodgman, ring by ring, which keeps the +//! even-odd rule inside the tile); +//! - a line, or a polygon's outline, is cut into the parts inside it. A part ends on the grown +//! tile's edge, so its round cap lies outside the square, under the stencil: no seams. +//! +//! Point markers aren't tiled: a marker near a border would be cut by the square. A layer's +//! markers are one command after its tiles, as before. +//! +//! The scene is the same on any number of threads: the tiles come out in grid order. A small +//! layer is meshed on one thread, and the threads are no more than the memory set aside for +//! drawing holds ([`threads_for`]). + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use rustgis_data::Geometry; +use rustgis_geom::{Coord, Extent}; +use rustgis_map::Symbol; + +use crate::gpu_scene::{DrawCmd, MeshVertex}; +use crate::mesh::TessError; + +/// About how many physical pixels a tile is on a side. +pub(crate) const TILE_PX: f64 = 512.0; + +/// The most tiles a layer is cut into; past it (a scene far larger than a screen) the layer is +/// one mesh, as before. +const MAX_TILES: usize = 4096; + +/// A layer estimated at fewer vertices than this is meshed on one thread: starting threads would +/// cost more than they save. +const THREADS_FROM_VERTICES: usize = 50_000; + +/// The bytes a mesh vertex takes while a tile is tessellated: the vertex (40 bytes), its share of +/// the indices and lyon's scratch. +const SCRATCH_PER_VERTEX: usize = 96; + +/// The threads to mesh `tiles` on: one for a small layer, else as many as the tiles and the user's +/// thread count allow, and no more than [`rustgis_data::memory::thread_scratch`] holds beyond one +/// thread's, each meshing a tile as big as the biggest (by the features' estimates, each counted +/// whole in every tile it reaches). +fn threads_for(features: &[Feature<'_>], tiles: &[(Tile, Vec)]) -> usize { + let estimate = + |members: &[usize]| members.iter().filter_map(|k| features.get(*k)).map(|f| f.estimate).fold(0usize, usize::saturating_add); + let total = features.iter().map(|f| f.estimate).fold(0usize, usize::saturating_add); + if total < THREADS_FROM_VERTICES { + return 1; + } + let biggest = tiles.iter().map(|(_, m)| estimate(m)).max().unwrap_or(0).saturating_mul(SCRATCH_PER_VERTEX).max(1); + let affordable = (rustgis_data::memory::thread_scratch() / biggest).saturating_add(1); + rustgis_data::threads::for_items(tiles.len()).min(affordable).max(1) +} + +/// The side of the tiles, map units: the power of two nearest [`TILE_PX`] physical pixels at +/// `map_per_px` map units per physical pixel. `None` for a scale that isn't a positive number. +pub(crate) fn tile_side(map_per_px: f64) -> Option { + let side = 2f64.powf((TILE_PX * map_per_px).log2().round()); + (map_per_px.is_finite() && map_per_px > 0.0 && side.is_normal()).then_some(side) +} + +/// A tile of the grid, by column and row (x and y over the side, rounded down). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Tile { + row: i64, + column: i64, +} + +impl Tile { + /// Its south-west corner, map units: its mesh's origin. + fn corner(self, side: f64) -> [f64; 2] { + [self.column as f64 * side, self.row as f64 * side] + } +} + +/// One feature of a layer to tile: its geometry, symbol, its estimate of vertices, its extent +/// and how far its stroke reaches past it (map units). +pub(crate) struct Feature<'a> { + pub geometry: &'a Geometry, + pub symbol: Symbol, + pub estimate: usize, + pub extent: Extent, + pub reach: f64, +} + +/// The tiles of a layer's features within `area`, each with the features (by index) reaching +/// it, in grid order. `None` when they would be more than [`MAX_TILES`]. +fn buckets(features: &[Feature<'_>], area: &Extent, side: f64) -> Option)>> { + let index = |v: f64| (v / side).floor() as i64; + let mut tiles: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (k, f) in features.iter().enumerate() { + let r = f.reach; + let grown = Extent::new(f.extent.min_x - r, f.extent.min_y - r, f.extent.max_x + r, f.extent.max_y + r); + // Only the tiles of the scene's area: what lies past it isn't drawn. + let e = + Extent::new(grown.min_x.max(area.min_x), grown.min_y.max(area.min_y), grown.max_x.min(area.max_x), grown.max_y.min(area.max_y)); + if !(e.min_x <= e.max_x && e.min_y <= e.max_y) { + continue; + } + let (columns, rows) = (index(e.min_x)..=index(e.max_x), index(e.min_y)..=index(e.max_y)); + let span = |r: &std::ops::RangeInclusive| r.end().saturating_sub(*r.start()).saturating_add(1); + let count = span(&columns).saturating_mul(span(&rows)); + if usize::try_from(count).map_or(true, |n| n > MAX_TILES) { + return None; + } + for row in rows { + for column in columns.clone() { + tiles.entry(Tile { row, column }).or_default().push(k); + } + } + if tiles.len() > MAX_TILES { + return None; + } + } + Some(tiles.into_iter().collect()) +} + +/// The finite runs of a ring or line: a point that isn't finite breaks it there, as +/// `decimate_runs` breaks it. +fn finite_runs(pts: &[Coord]) -> impl Iterator { + pts.split(|c| !c.is_finite()).filter(|r| !r.is_empty()) +} + +/// A ring clipped to `b` (Sutherland–Hodgman): the part inside it, closed along its edges; +/// empty when less than a triangle is left. +fn clip_ring(pts: &[Coord], b: &Extent) -> Vec { + let mut cur: Vec = pts.to_vec(); + for edge in 0..4 { + if cur.is_empty() { + break; + } + let inside = |p: Coord| match edge { + 0 => p.x >= b.min_x, + 1 => p.x <= b.max_x, + 2 => p.y >= b.min_y, + _ => p.y <= b.max_y, + }; + let cross = |p: Coord, q: Coord| match edge { + 0 => Coord::new(b.min_x, p.y + (q.y - p.y) * (b.min_x - p.x) / (q.x - p.x)), + 1 => Coord::new(b.max_x, p.y + (q.y - p.y) * (b.max_x - p.x) / (q.x - p.x)), + 2 => Coord::new(p.x + (q.x - p.x) * (b.min_y - p.y) / (q.y - p.y), b.min_y), + _ => Coord::new(p.x + (q.x - p.x) * (b.max_y - p.y) / (q.y - p.y), b.max_y), + }; + let mut out = Vec::with_capacity(cur.len() + 4); + let Some(&last) = cur.last() else { break }; + let mut prev = last; + for &p in &cur { + match (inside(prev), inside(p)) { + (true, true) => out.push(p), + (true, false) => out.push(cross(prev, p)), + (false, true) => { + out.push(cross(prev, p)); + out.push(p); + } + (false, false) => {} + } + prev = p; + } + cur = out; + } + if cur.len() < 3 { Vec::new() } else { cur } +} + +/// The parts of a line inside `b`, each segment clipped by Liang–Barsky. +fn clip_line(pts: &[Coord], b: &Extent) -> Vec> { + let mut parts: Vec> = Vec::new(); + let mut cur: Vec = Vec::new(); + for w in pts.windows(2) { + let (Some(&p), Some(&q)) = (w.first(), w.get(1)) else { continue }; + let (dx, dy) = (q.x - p.x, q.y - p.y); + let (mut t0, mut t1) = (0.0f64, 1.0f64); + let mut keep = true; + for (num, den) in [(p.x - b.min_x, -dx), (b.max_x - p.x, dx), (p.y - b.min_y, -dy), (b.max_y - p.y, dy)] { + if den == 0.0 { + if num < 0.0 { + keep = false; + break; + } + } else { + let t = num / den; + if den < 0.0 { + t0 = t0.max(t); + } else { + t1 = t1.min(t); + } + } + } + if !keep || t0 > t1 { + if cur.len() > 1 { + parts.push(std::mem::take(&mut cur)); + } + cur.clear(); + continue; + } + let a = Coord::new(p.x + dx * t0, p.y + dy * t0); + let z = Coord::new(p.x + dx * t1, p.y + dy * t1); + if cur.is_empty() || t0 > 0.0 { + if cur.len() > 1 { + parts.push(std::mem::take(&mut cur)); + } + cur = vec![a]; + } + cur.push(z); + if t1 < 1.0 { + parts.push(std::mem::take(&mut cur)); + } + } + if cur.len() > 1 { + parts.push(cur); + } + parts +} + +/// A closed ring cut to `b`: whole (`Ok`) when it lies inside, else its open parts inside +/// (`Err`), the part through its first point joined across it so no cap lands inside the tile. +fn cut_ring(ring: &[Coord], b: &Extent) -> Result, Vec>> { + let inside = |c: &Coord| c.x >= b.min_x && c.x <= b.max_x && c.y >= b.min_y && c.y <= b.max_y; + if ring.iter().all(inside) { + return Ok(ring.to_vec()); + } + let (Some(&first), Some(&last)) = (ring.first(), ring.last()) else { return Err(Vec::new()) }; + let mut closed = ring.to_vec(); + if first != last { + closed.push(first); + } + let mut parts = clip_line(&closed, b); + // A ring starting inside the tile has its first part start, and its last end, at its first + // point: they are one stretch of the outline. + if inside(&first) && parts.len() > 1 { + let starts = parts.first().and_then(|p| p.first()).copied() == Some(first); + let ends = parts.last().and_then(|p| p.last()).copied() == Some(first); + if starts && ends { + let head = parts.remove(0); + if let Some(tail) = parts.last_mut() { + tail.extend(head.into_iter().skip(1)); + } + } + } + Err(parts) +} + +/// Appends one feature cut to the grown tile `b`, in the order `append_geometry` draws it. +fn append_cut( + v: &mut Vec, + i: &mut Vec, + f: &Feature<'_>, + b: &Extent, + origin: [f64; 2], + wireframe: bool, + ppp: f32, + map_per_px: f64, + limit: usize, +) -> Result<(), TessError> { + let s = &f.symbol; + let room = |v: &Vec| limit.saturating_sub(v.len()); + // Outlines: rings inside the tile stroked closed, the rest as open parts with no cap floor. + let outline = |v: &mut Vec, i: &mut Vec, polys: &[Vec>], color, width: f32| { + let (mut rings, mut parts) = (Vec::new(), Vec::new()); + for ring in polys.iter().flatten() { + for run in finite_runs(ring) { + match cut_ring(run, b) { + Ok(r) => rings.push(r), + Err(p) => parts.extend(p), + } + } + } + crate::mesh::extend_mesh(v, i, crate::mesh::stroke(&rings, origin, color, width, map_per_px, true, 3, room(v)))?; + crate::mesh::extend_mesh(v, i, crate::mesh::stroke(&parts, origin, color, width, map_per_px, false, 2, room(v))) + }; + match f.geometry { + Geometry::Point(_) | Geometry::MultiPoint(_) => {} + Geometry::Line(parts) => { + if s.stroke.a() > 0 && (s.stroke_width * ppp).is_finite() { + let cut: Vec> = parts.iter().flat_map(|p| finite_runs(p).flat_map(|r| clip_line(r, b))).collect(); + let color = crate::mesh::premul(s.stroke); + crate::mesh::extend_mesh(v, i, crate::mesh::stroke_lines(&cut, origin, color, s.stroke_width * ppp, map_per_px, room(v)))?; + } + } + Geometry::Polygon(polys) if wireframe => { + outline(v, i, polys, crate::mesh::premul(s.stroke.with_alpha(255)), s.stroke_width.max(1.0) * ppp)?; + } + Geometry::Polygon(polys) => { + if s.fill.a() > 0 { + let clipped: Vec>> = polys + .iter() + .map(|rings| rings.iter().flat_map(|r| finite_runs(r).map(|run| clip_ring(run, b))).filter(|r| !r.is_empty()).collect()) + .filter(|rings: &Vec>| !rings.is_empty()) + .collect(); + let color = crate::mesh::premul(s.fill); + crate::mesh::extend_mesh(v, i, crate::mesh::fill_polygon(&clipped, origin, color, map_per_px, room(v)))?; + } + if s.stroke_width > 0.0 && s.stroke.a() > 0 { + outline(v, i, polys, crate::mesh::premul(s.stroke), s.stroke_width * ppp)?; + } + } + } + Ok(()) +} + +/// One tile's mesh: its features in layer order, each whole or cut to the tile grown by its +/// reach. `Ok(None)` when nothing draws there. +fn tile_mesh( + features: &[Feature<'_>], + tile: Tile, + members: &[usize], + side: f64, + wireframe: bool, + ppp: f32, + map_per_px: f64, + limit: usize, + used: &AtomicUsize, +) -> Result, TessError> { + let origin = tile.corner(side); + let square = Extent::new(origin[0], origin[1], origin[0] + side, origin[1] + side); + let (mut v, mut i, mut no_points) = (Vec::new(), Vec::new(), Vec::new()); + for &k in members { + let Some(f) = features.get(k) else { continue }; + // The layer's room: what the tiles finished so far left, less this one's. + let room = limit.saturating_sub(used.load(Ordering::Relaxed)); + let r = f.reach; + let grown = Extent::new(square.min_x - r, square.min_y - r, square.max_x + r, square.max_y + r); + let e = &f.extent; + if e.min_x >= grown.min_x && e.max_x <= grown.max_x && e.min_y >= grown.min_y && e.max_y <= grown.max_y { + // Whole, it takes about its estimate; cut, only its part here, bounded as it's made. + if v.len().saturating_add(f.estimate) > room { + return Err(TessError::TooDense); + } + crate::mesh::append_geometry(&mut v, &mut i, &mut no_points, f.geometry, &f.symbol, origin, wireframe, ppp, map_per_px, room)?; + } else { + append_cut(&mut v, &mut i, f, &grown, origin, wireframe, ppp, map_per_px, room)?; + } + } + if i.is_empty() { + return Ok(None); + } + if used.fetch_add(v.len(), Ordering::Relaxed).saturating_add(v.len()) > limit { + return Err(TessError::TooDense); + } + let square = [0.0, 0.0, side as f32, side as f32]; + Ok(Some(DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i), square: Some(square) })) +} + +/// The layer's features (points left out: they aren't tiled) as tile meshes within `area`, +/// tessellated on several threads. `None` when the scale has no tiles or the area would take +/// too many (the caller makes one mesh); else the tiles' commands and their vertices, or why +/// the layer can't be meshed. +pub(crate) fn tile_meshes( + features: &[Feature<'_>], + area: &Extent, + wireframe: bool, + ppp: f32, + map_per_px: f64, + limit: usize, +) -> Option, usize), TessError>> { + tile_meshes_on(features, area, wireframe, ppp, map_per_px, limit, None) +} + +/// [`tile_meshes`] on `threads` threads, or as [`threads_for`] decides. +fn tile_meshes_on( + features: &[Feature<'_>], + area: &Extent, + wireframe: bool, + ppp: f32, + map_per_px: f64, + limit: usize, + threads: Option, +) -> Option, usize), TessError>> { + let side = tile_side(map_per_px)?; + let tiles = buckets(features, area, side)?; + let threads = threads.unwrap_or_else(|| threads_for(features, &tiles)); + // The vertices of the tiles made so far, which every tile checks against `limit` as it + // goes: the layer never holds much more than `limit` (by the tiles at work at once, each + // within the room left when it started a feature), not `limit` a tile. + let used = AtomicUsize::new(0); + let made = crate::tile_mesh::parallel_on(&tiles, threads, |(tile, members)| { + tile_mesh(features, *tile, members, side, wireframe, ppp, map_per_px, limit, &used) + }); + let mut cmds = Vec::with_capacity(made.len()); + let mut used = 0usize; + for m in made { + // A tile that panicked (hostile data) leaves the layer to the CPU, as lyon refusing it. + match m.unwrap_or(Err(TessError::Refused)) { + Ok(Some(cmd)) => { + if let DrawCmd::Mesh { vertices, .. } = &cmd { + used = used.saturating_add(vertices.len()); + } + cmds.push(cmd); + } + Ok(None) => {} + Err(e) => return Some(Err(e)), + } + if used > limit { + return Some(Err(TessError::TooDense)); + } + } + Some(Ok((cmds, used))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_tile_is_the_power_of_two_nearest_its_pixels() { + assert_eq!(tile_side(1.0), Some(512.0)); + assert_eq!(tile_side(0.75), Some(512.0)); + assert_eq!(tile_side(3.0), Some(2048.0)); + assert_eq!(tile_side(0.0), None); + assert_eq!(tile_side(f64::NAN), None); + } + + #[test] + fn a_ring_starting_inside_is_cut_into_parts_joined_through_its_first_point() { + let b = Extent::new(0.0, 0.0, 10.0, 10.0); + let ring = [Coord::new(5.0, 5.0), Coord::new(20.0, 5.0), Coord::new(20.0, 8.0), Coord::new(5.0, 8.0)]; + let Err(parts) = cut_ring(&ring, &b) else { panic!("cut") }; + assert_eq!(parts.len(), 1, "{parts:?}"); + assert_eq!(parts[0], vec![Coord::new(10.0, 8.0), Coord::new(5.0, 8.0), Coord::new(5.0, 5.0), Coord::new(10.0, 5.0)]); + assert_eq!(cut_ring(&ring[..1], &b), Ok(ring[..1].to_vec())); + } + + /// A symbol with a stroke `width` points wide in `stroke` and a fill in `fill`. + fn symbol(fill: rustgis_map::Rgba, width: f32) -> Symbol { + Symbol { + fill, + stroke: rustgis_map::Rgba::rgb(0, 0, 0), + stroke_width: width, + ..Symbol::default_for(rustgis_data::GeometryType::Polygon, 0) + } + } + + fn feature(g: &Geometry, s: Symbol) -> Feature<'_> { + // As the layer's features reach: half the stroke as tessellated and a pixel, none unstroked. + let reach = if s.stroke_width > 0.0 { f64::from(crate::mesh::tessellation_width(s.stroke_width, 1.0)) / 2.0 + 2.0 } else { 0.0 }; + let estimate = crate::mesh::estimate_vertices(g, &s, false); + Feature { geometry: g, symbol: s, estimate, extent: g.extent(), reach } + } + + /// Each tile's mesh, as (origin, its vertices' positions from the map's origin). + fn tiles(cmds: &[DrawCmd]) -> Vec<([f64; 2], Vec<[f64; 2]>)> { + cmds.iter() + .filter_map(|c| match c { + DrawCmd::Mesh { origin, vertices, square: Some(_), .. } => Some(( + *origin, + vertices.iter().map(|v| [origin[0] + f64::from(v.position[0]), origin[1] + f64::from(v.position[1])]).collect(), + )), + _ => None, + }) + .collect() + } + + /// Lines and polygons over many tiles, meshed on one thread and on eight: the same commands, + /// vertex for vertex, in the same order. + #[test] + fn a_layers_tiles_are_the_same_on_any_number_of_threads() { + let geoms: Vec = (0u32..40) + .map(|n| { + let k = f64::from(n); + if n.is_multiple_of(2) { + Geometry::Line(vec![vec![ + Coord::new(-900.0 + k * 13.0, -700.0), + Coord::new(800.0, 600.0 - k * 17.0), + Coord::new(-300.0, 900.0), + ]]) + } else { + let (x, y) = (-1000.0 + k * 40.0, -800.0 + k * 31.0); + Geometry::Polygon(vec![vec![vec![ + Coord::new(x, y), + Coord::new(x + 700.0, y + 50.0), + Coord::new(x + 600.0, y + 650.0), + Coord::new(x - 20.0, y + 500.0), + ]]]) + } + }) + .collect(); + let features: Vec> = geoms.iter().map(|g| feature(g, symbol(rustgis_map::Rgba::rgb(9, 99, 199), 3.0))).collect(); + let area = Extent::new(-2048.0, -2048.0, 2048.0, 2048.0); + let made = |threads| { + let (cmds, used) = tile_meshes_on(&features, &area, false, 1.0, 1.0, usize::MAX, Some(threads)).unwrap().unwrap(); + let bytes: Vec> = cmds + .iter() + .map(|c| match c { + DrawCmd::Mesh { origin, vertices, indices, square } => [ + bytemuck::cast_slice::<_, u8>(origin), + bytemuck::cast_slice(vertices.as_slice()), + bytemuck::cast_slice(indices.as_slice()), + bytemuck::cast_slice(square.as_slice()), + ] + .concat(), + _ => Vec::new(), + }) + .collect(); + (bytes, used) + }; + let one = made(1); + assert!(one.0.len() > 4, "many tiles: {}", one.0.len()); + assert_eq!(made(8), one); + } + + /// A long line over many tiles, its whole estimate past the layer's limit: each tile takes + /// only its part, so the layer meshes; the tiles together past the limit give the layer up. + #[test] + fn a_cut_feature_takes_only_its_part_and_the_layers_tiles_share_its_limit() { + let pts: Vec = (0..4000).map(|k| Coord::new(-2000.0 + f64::from(k), 30.0 + f64::from(k % 7))).collect(); + let line = Geometry::Line(vec![pts]); + let f = feature(&line, symbol(rustgis_map::Rgba::rgb(0, 0, 0), 2.0)); + let area = Extent::new(-1024.0, -1024.0, 1024.0, 1024.0); + let (all, used) = tile_meshes_on(std::slice::from_ref(&f), &area, false, 1.0, 1.0, usize::MAX, Some(1)).unwrap().unwrap(); + assert!(tiles(&all).len() >= 4, "{}", tiles(&all).len()); + assert!(used < f.estimate, "cut to the area: {used} of {}", f.estimate); + let biggest = tiles(&all).iter().map(|(_, v)| v.len()).max().unwrap_or(0); + // Room for the biggest tile but not the whole estimate: it meshes. + let room = used.max(biggest); + assert!(room < f.estimate); + assert!(tile_meshes_on(std::slice::from_ref(&f), &area, false, 1.0, 1.0, room, Some(1)).unwrap().is_ok()); + for threads in [1, 8] { + let short = tile_meshes_on(std::slice::from_ref(&f), &area, false, 1.0, 1.0, used - 1, Some(threads)).unwrap(); + assert!(matches!(short, Err(TessError::TooDense)), "{threads} threads"); + } + } + + /// A line just west of a tile's east edge, with a stroke wider than the gap: the next tile + /// east draws what spills over (its mesh reaches past its west edge), and a polygon larger + /// than the tiles is filled in each only within it. + #[test] + fn a_stroke_spills_into_the_next_tile_and_a_fill_keeps_to_its_own() { + let line = Geometry::Line(vec![vec![Coord::new(510.0, 100.0), Coord::new(510.0, 300.0)]]); + let wide = feature(&line, symbol(rustgis_map::Rgba::rgb(0, 0, 0), 8.0)); + let area = Extent::new(-2048.0, -2048.0, 2048.0, 2048.0); + let (cmds, _) = tile_meshes(std::slice::from_ref(&wide), &area, false, 1.0, 1.0, usize::MAX).unwrap().unwrap(); + let origins: Vec<[f64; 2]> = tiles(&cmds).into_iter().map(|(o, _)| o).collect(); + assert_eq!(origins, [[0.0, 0.0], [512.0, 0.0]], "its own tile and the next east"); + let square = Geometry::Polygon(vec![vec![vec![ + Coord::new(-300.0, -300.0), + Coord::new(900.0, -300.0), + Coord::new(900.0, 900.0), + Coord::new(-300.0, 900.0), + ]]]); + let filled = feature(&square, Symbol { stroke_width: 0.0, ..symbol(rustgis_map::Rgba::rgb(9, 99, 199), 0.0) }); + let (cmds, _) = tile_meshes(std::slice::from_ref(&filled), &area, false, 1.0, 1.0, usize::MAX).unwrap().unwrap(); + let tiled = tiles(&cmds); + assert_eq!(tiled.len(), 9, "the nine tiles it covers"); + for (origin, positions) in tiled { + for [x, y] in positions { + assert!(x >= origin[0] && x <= origin[0] + 512.0 && y >= origin[1] && y <= origin[1] + 512.0, "{x},{y} in {origin:?}"); + } + } + } + + #[test] + fn a_feature_reaches_the_tiles_its_stroke_reaches() { + let g = Geometry::Line(vec![vec![Coord::new(1.0, 1.0), Coord::new(511.0, 1.0)]]); + let f = |reach| Feature { + geometry: &g, + symbol: Symbol::default_for(rustgis_data::GeometryType::Polyline, 0), + estimate: 0, + extent: g.extent(), + reach, + }; + let area = Extent::new(-4096.0, -4096.0, 4096.0, 4096.0); + let tiles = |reach| buckets(&[f(reach)], &area, 512.0).unwrap().into_iter().map(|(t, _)| (t.column, t.row)).collect::>(); + assert_eq!(tiles(0.0), [(0, 0)]); + assert_eq!(tiles(2.0), [(-1, -1), (0, -1), (1, -1), (-1, 0), (0, 0), (1, 0)]); + } +} diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 2ddc79d82c..ffc9c8b2e8 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1427,25 +1427,27 @@ fn a_tilted_view_of_a_streamed_layer_too_dense_to_mesh_is_drawn_on_the_cpu() { assert!(gpu.pixmap.data() == cpu.pixmap.data(), "as the CPU backend draws it"); } -/// A streamed layer whose first batch is drawn on the CPU (reaching too far for f32) and whose -/// next one meshes, putting that picture in the scene: the GPU frame tried first for a tilted view -/// stops there, before the layer above (#2540), and the view is drawn as the CPU backend draws it. +/// A streamed layer whose first batch is drawn on the CPU (markers too far apart for f32) and +/// whose next one meshes, putting that picture in the scene: the GPU frame tried first for a turned +/// view stops there, before the layer above (#2540), and the view is drawn as the CPU backend draws +/// it. (A tilted view stands markers up, drawn otherwise.) #[test] -fn a_tilted_view_stops_trying_the_gpu_at_a_picture_already_in_the_scene() { +fn a_turned_view_stops_trying_the_gpu_at_a_picture_already_in_the_scene() { let square = |x: f64, y: f64, s: f64| { Some(Geometry::Polygon(vec![vec![vec![Coord::new(x, y), Coord::new(x + s, y), Coord::new(x + s, y + s), Coord::new(x, y + s)]]])) }; let mut map = Map::new("mixed"); map.basemap = rustgis_map::Basemap::Blank; - let mut ds = Dataset::new("mixed", GeometryType::Polygon, vec![]); - ds.push(square(1.0 - 0.025, 0.5 - 0.025, 0.05), vec![]); - ds.push(square(1.0, 0.5, 1e-7), vec![]); + let mut ds = Dataset::new("mixed", GeometryType::Point, vec![]); + // About 5 km apart, then one in the view. + ds.push(Some(Geometry::MultiPoint(vec![Coord::new(1.0 - 0.025, 0.5), Coord::new(1.0 + 0.025, 0.5)])), vec![]); + ds.push(Some(Geometry::Point(Coord::new(1.0, 0.5))), vec![]); map.add_dataset(ds); map.layers[0] = streamed(&map.layers[0], 1); let mut top = Dataset::new("top", GeometryType::Polygon, vec![]); top.push(square(1.0 + 2e-7, 0.5, 1e-7), vec![]); map.add_dataset(top); - let camera = Camera { center: lonlat_to_merc(Coord::new(1.0, 0.5)), res: rustgis_map::camera::MIN_RES, bearing: 0.0, pitch: 50.0 }; + let camera = Camera { center: lonlat_to_merc(Coord::new(1.0, 0.5)), res: rustgis_map::camera::MIN_RES, bearing: 30.0, pitch: 0.0 }; let view = View { width: 400.0, height: 400.0, pixels_per_point: 1.0, camera, sky: false }; crate::MESHED.with(|m| m.borrow_mut().clear()); let Some(RenderOutput::Cpu(gpu)) = render_backend(&mut map, &view, Backend::Gpu) else { panic!("drawn on the CPU") }; diff --git a/crates/render/src/tile_mesh.rs b/crates/render/src/tile_mesh.rs index 36493c9903..63a2340d66 100644 --- a/crates/render/src/tile_mesh.rs +++ b/crates/render/src/tile_mesh.rs @@ -513,9 +513,14 @@ pub fn meshes( /// browser a panic aborts (`wasm32-unknown-unknown` unwinds nothing): there a panic is caught /// nowhere, as everywhere else in the web app. fn parallel(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec> { + parallel_on(items, rustgis_data::threads::for_items(items.len()), f) +} + +/// [`parallel`] on at most `threads` threads. +pub(crate) fn parallel_on(items: &[T], threads: usize, f: impl Fn(&T) -> R + Sync) -> Vec> { #[cfg(not(target_arch = "wasm32"))] { - let threads = rustgis_data::threads::for_items(items.len()); + let threads = threads.min(items.len()); if threads > 1 { let next = std::sync::atomic::AtomicUsize::new(0); let out: Mutex>> = Mutex::new((0..items.len()).map(|_| None).collect()); @@ -540,6 +545,9 @@ fn parallel(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec) -> Self { + CmdUniforms { square: square.unwrap_or([0.0; 4]), ..self } + } } /// A vector tile mesh's uniforms (WGSL `TileMeshUniforms`): the command's, how far the camera's @@ -239,6 +247,9 @@ pub(crate) const PREMULTIPLIED_BLEND: wgpu::BlendState = wgpu::BlendState { /// must match its sample count, so the multisampling happens in our own pass. pub(crate) struct GpuMapRenderer { mesh_pipeline: wgpu::RenderPipeline, + /// A tiled layer mesh, drawn only where its square marked the stencil, and those squares. + mesh_in_square_pipeline: wgpu::RenderPipeline, + mesh_square_pipeline: wgpu::RenderPipeline, point_pipeline: wgpu::RenderPipeline, image_pipeline: wgpu::RenderPipeline, backdrop_pipeline: wgpu::RenderPipeline, @@ -512,6 +523,26 @@ impl GpuMapRenderer { ); let mesh_pipeline = pipeline("mapgpu_mesh", "vs_mesh", "fs_mesh", &mesh_buffers, &[&cmd_layout], scene_format, samples, flat.clone()); + let mesh_in_square_pipeline = pipeline( + "mapgpu_mesh_in_square", + "vs_mesh", + "fs_mesh", + &mesh_buffers, + &[&cmd_layout], + scene_format, + samples, + stencil(inside, 0), + ); + let mesh_square_pipeline = pipeline( + "mapgpu_mesh_square", + "vs_mesh_square", + "fs_tile_square", + &[], + &[&cmd_layout], + scene_format, + samples, + stencil(mark, 0xff), + ); let point_pipeline = pipeline("mapgpu_points", "vs_marker", "fs_marker", &point_buffers, &[&cmd_layout], scene_format, samples, flat.clone()); let tile_pipeline = pipeline( @@ -546,6 +577,8 @@ impl GpuMapRenderer { let blit_pipeline = pipeline("mapgpu_blit", "vs_blit", "fs_blit", &[], &[&image_layout, &blit_layout], rs.target_format, 1, None); GpuMapRenderer { mesh_pipeline, + mesh_in_square_pipeline, + mesh_square_pipeline, point_pipeline, image_pipeline, backdrop_pipeline, @@ -1123,6 +1156,8 @@ pub(crate) enum SceneDraw { bind: wgpu::BindGroup, origin: [f64; 2], clip: CmdClip, + /// A tile's square, which the mesh is drawn inside ([`DrawCmd::Mesh`]). + square: Option<[f32; 4]>, }, /// A layer's markers, shared as a mesh's buffers are. Points { @@ -1380,11 +1415,11 @@ impl SceneBuffers { for (i, cmd) in scene.cmds.iter().enumerate() { let clip = scene.clips.get(i).copied().unwrap_or(CmdClip::ALL); match cmd { - DrawCmd::Mesh { origin, vertices, indices } => { + DrawCmd::Mesh { origin, vertices, indices, square } => { if indices.is_empty() { continue; } - let uniforms = CmdUniforms::new(&camera, size, ppp, *origin, tilt, clip); + let uniforms = CmdUniforms::new(&camera, size, ppp, *origin, tilt, clip).in_square(*square); let uniforms = owned_buffer( device, &wgpu::util::BufferInitDescriptor { @@ -1409,6 +1444,7 @@ impl SceneBuffers { bind, origin: *origin, clip, + square: *square, }); } DrawCmd::Points { origin, instances } => { @@ -1620,11 +1656,11 @@ impl SceneBuffers { pub(crate) fn set_camera(&self, queue: &wgpu::Queue, cam: &Camera) { *self.shown.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = *cam; for d in &self.draws { - let (uniforms, origin, clip) = match d { - SceneDraw::Mesh { uniforms, origin, clip, .. } - | SceneDraw::Points { uniforms, origin, clip, .. } + let (uniforms, origin, clip, square) = match d { + SceneDraw::Mesh { uniforms, origin, clip, square, .. } => (uniforms, origin, clip, *square), + SceneDraw::Points { uniforms, origin, clip, .. } | SceneDraw::Extrusion { uniforms, origin, clip, .. } - | SceneDraw::Tiles { uniforms, origin, clip, .. } => (uniforms, origin, clip), + | SceneDraw::Tiles { uniforms, origin, clip, .. } => (uniforms, origin, clip, None), SceneDraw::Backdrop { uniforms, .. } => { if let Some(t) = &self.tilt { let u = BackdropUniforms::new(cam, self.size, self.ppp, self.clear, t); @@ -1642,7 +1678,7 @@ impl SceneBuffers { } SceneDraw::Image { .. } | SceneDraw::LiveTiles { .. } => continue, }; - let u = CmdUniforms::new(cam, self.size, self.ppp, *origin, self.tilt.as_ref(), *clip); + let u = CmdUniforms::new(cam, self.size, self.ppp, *origin, self.tilt.as_ref(), *clip).in_square(square); queue.write_buffer(uniforms, 0, bytemuck::bytes_of(&u)); } } @@ -1667,13 +1703,28 @@ pub(crate) struct SceneCallback { fn paint_draws(renderer: &GpuMapRenderer, draws: &[SceneDraw], rp: &mut wgpu::RenderPass<'_>) { for d in draws { match d { - SceneDraw::Mesh { vertices, indices, index_count, bind, .. } => { + SceneDraw::Mesh { vertices, indices, index_count, bind, square: None, .. } => { rp.set_pipeline(&renderer.mesh_pipeline); rp.set_bind_group(0, bind, &[]); rp.set_vertex_buffer(0, vertices.slice(..)); rp.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); rp.draw_indexed(0..*index_count, 0, 0..1); } + // A tile's mesh: its square marks the stencil, the mesh draws only there, and the + // square clears it again for what comes next. + SceneDraw::Mesh { vertices, indices, index_count, bind, square: Some(_), .. } => { + rp.set_bind_group(0, bind, &[]); + rp.set_pipeline(&renderer.mesh_square_pipeline); + rp.set_stencil_reference(1); + rp.draw(0..6, 0..1); + rp.set_pipeline(&renderer.mesh_in_square_pipeline); + rp.set_vertex_buffer(0, vertices.slice(..)); + rp.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + rp.draw_indexed(0..*index_count, 0, 0..1); + rp.set_pipeline(&renderer.mesh_square_pipeline); + rp.set_stencil_reference(0); + rp.draw(0..6, 0..1); + } SceneDraw::Points { instances, count, bind, .. } => { rp.set_pipeline(&renderer.point_pipeline); rp.set_bind_group(0, bind, &[]); @@ -1912,6 +1963,7 @@ mod tests { nv ]), indices: Arc::new(vec![0u32; ni]), + square: None, }; assert!(cmd_fits(&limits, &mesh(4, 6)), "small mesh fits"); assert!(!cmd_fits(&limits, &mesh(100, 6)), "a vertex buffer over max_buffer_size declines"); @@ -1985,6 +2037,7 @@ mod tests { origin: [0.0, 0.0], vertices: Arc::new(vec![v(0.0, 0.0), v(100.0, 0.0), v(0.0, 100.0)]), indices: Arc::new(vec![0, 1, 2]), + square: None, }, DrawCmd::Points { origin: [0.0, 0.0], @@ -2033,9 +2086,12 @@ mod tests { .cmds .iter() .filter_map(|c| match c { - DrawCmd::Mesh { origin, vertices, indices } => { - Some(DrawCmd::Mesh { origin: *origin, vertices: Arc::new(vertices.to_vec()), indices: Arc::new(indices.to_vec()) }) - } + DrawCmd::Mesh { origin, vertices, indices, square } => Some(DrawCmd::Mesh { + origin: *origin, + vertices: Arc::new(vertices.to_vec()), + indices: Arc::new(indices.to_vec()), + square: *square, + }), _ => share(c), }) .collect(), diff --git a/crates/ui-egui/src/mapgpu.wgsl b/crates/ui-egui/src/mapgpu.wgsl index 11ccaf0c75..efb7bb4f85 100644 --- a/crates/ui-egui/src/mapgpu.wgsl +++ b/crates/ui-egui/src/mapgpu.wgsl @@ -18,6 +18,8 @@ struct CmdUniforms { /// Extrusions: the light's direction (map units) and how far a shadow falls per map unit /// of height. light: vec4f, + /// A tiled layer mesh's square, from its origin: least x and y, greatest x and y. + square: vec4f, }; struct VOut { @@ -64,6 +66,15 @@ fn vs_mesh(in: MeshIn) -> VOut { return out; } +// A tiled layer mesh's square: marks the stencil (fs_tile_square draws nothing), so the tile's +// mesh draws only inside it. +@vertex +fn vs_mesh_square(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4f { + let s = u_mesh.square; + var corners = array(vec2f(s.x, s.y), vec2f(s.z, s.y), vec2f(s.z, s.w), vec2f(s.x, s.y), vec2f(s.z, s.w), vec2f(s.x, s.w)); + return u_mesh.view_proj * vec4f(corners[vi], 0.0, 1.0); +} + @fragment fn fs_mesh(in: VOut) -> @location(0) vec4f { if !kept(in.depth, u_mesh) { From 03f6096bc6b3564cadd42aa1754d489e61b15f83 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 27 Nov 2026 19:03:04 +0100 Subject: [PATCH 2/2] fix(render): tiles kept off tilted bands, one limit on any thread count, own stencil bit (#2541) --- crates/render/src/lib.rs | 14 ++++++++-- crates/render/src/mesh.rs | 4 ++- crates/render/src/mesh_tiles.rs | 45 +++++++++++++++++++++++---------- crates/ui-egui/src/mapgpu.rs | 22 +++++++++------- 4 files changed, 60 insertions(+), 25 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3e0eb317e5..22a90a707c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4734,8 +4734,11 @@ fn render_frame( // GPU meshes reach further (`GPU_CULL_MARGIN`), so the camera fast path can move them. let mesh_cull = cull_extent(view, GPU_CULL_MARGIN); // A tilted view widens a far stroke past a tile's reach (the shader scales it by depth), so - // it keeps one mesh a layer; a flat one cuts its layers into tiles of the cull. - let mesh_tiled = (view.camera.pitch == 0.0).then_some(&mesh_cull); + // it keeps one mesh a layer; a flat one cuts its layers into tiles of the cull. A tilted + // view's bands are drawn as flat views (their cameras look straight down) for the shader to + // tilt, so they're told apart by what their labels are for. + let tilted = view.camera.pitch != 0.0 || matches!(labels_to, Labels::Tilted(..) | Labels::Shared); + let mesh_tiled = (!tilted).then_some(&mesh_cull); let mesh_visible = |e: &Extent| match &globe { Some(g) => g.may_see(e), None => e.intersects(&mesh_cull), @@ -11683,6 +11686,13 @@ mod tests { let side = crate::mesh_tiles::tile_side(1_000.0).expect("tiles"); let reach = gpu_scene::reach(&scene.cmds); assert!(reach >= side && reach < side * 1.01, "reach {reach} vs a tile's side {side}"); + + // Tilted, its bands (each drawn as a flat view for the shader to tilt) keep one mesh a + // layer: a far stroke widens past a tile's reach. + let view = View { camera: Camera { pitch: 45.0, ..camera }, ..view }; + let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; + assert!(scene.tilt.is_some() && cmd_kinds(&scene).contains(&"mesh"), "a tilted scene: {:?}", cmd_kinds(&scene)); + assert!(scene.cmds.iter().all(|c| !matches!(c, gpu_scene::DrawCmd::Mesh { square: Some(_), .. })), "no tiles in a tilted view"); } #[test] diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index 8af436d1e9..402c090142 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -513,7 +513,9 @@ pub(crate) fn collect_layer( } let n = estimate_vertices(g, &s, wireframe); estimate = estimate.saturating_add(n); - if estimate > limit { + // One mesh takes every feature whole, so a layer estimated past the limit isn't started; + // tiles take only each feature's part in them, and keep to the limit as they're made. + if area.is_none() && estimate > limit { return Err(TessError::TooDense); } let reach = stroke_reach(g, &s, wireframe, ppp, map_per_px); diff --git a/crates/render/src/mesh_tiles.rs b/crates/render/src/mesh_tiles.rs index 3cfcf08b9d..95385c6585 100644 --- a/crates/render/src/mesh_tiles.rs +++ b/crates/render/src/mesh_tiles.rs @@ -21,6 +21,7 @@ //! layer is meshed on one thread, and the threads are no more than the memory set aside for //! drawing holds ([`threads_for`]). +use std::collections::BTreeMap; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -38,6 +39,10 @@ pub(crate) const TILE_PX: f64 = 512.0; /// one mesh, as before. const MAX_TILES: usize = 4096; +/// The most (tile, feature) pairs a layer's tiles list: past it (many features each over many +/// tiles), the layer is made one mesh, so the lists stay within 8 MB of indices. +const MAX_MEMBERS: usize = 1 << 20; + /// A layer estimated at fewer vertices than this is meshed on one thread: starting threads would /// cost more than they save. const THREADS_FROM_VERTICES: usize = 50_000; @@ -94,10 +99,12 @@ pub(crate) struct Feature<'a> { } /// The tiles of a layer's features within `area`, each with the features (by index) reaching -/// it, in grid order. `None` when they would be more than [`MAX_TILES`]. +/// it, in grid order. `None` when they would be more than [`MAX_TILES`], or list more than +/// [`MAX_MEMBERS`] features in all. fn buckets(features: &[Feature<'_>], area: &Extent, side: f64) -> Option)>> { let index = |v: f64| (v / side).floor() as i64; - let mut tiles: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + let mut tiles: BTreeMap> = BTreeMap::new(); + let mut members = 0usize; for (k, f) in features.iter().enumerate() { let r = f.reach; let grown = Extent::new(f.extent.min_x - r, f.extent.min_y - r, f.extent.max_x + r, f.extent.max_y + r); @@ -113,6 +120,10 @@ fn buckets(features: &[Feature<'_>], area: &Extent, side: f64) -> Option MAX_TILES) { return None; } + members = members.saturating_add(usize::try_from(count).unwrap_or(usize::MAX)); + if members > MAX_MEMBERS { + return None; + } for row in rows { for column in columns.clone() { tiles.entry(Tile { row, column }).or_default().push(k); @@ -325,19 +336,23 @@ fn tile_mesh( let (mut v, mut i, mut no_points) = (Vec::new(), Vec::new(), Vec::new()); for &k in members { let Some(f) = features.get(k) else { continue }; - // The layer's room: what the tiles finished so far left, less this one's. - let room = limit.saturating_sub(used.load(Ordering::Relaxed)); + // Tiles finished already past the limit: the layer is refused whatever this one holds, + // so it stops early. A tile's own room is the whole limit, so whether the layer meshes + // doesn't hang on which tiles finished first (the same on any number of threads). + if used.load(Ordering::Relaxed) > limit { + return Err(TessError::TooDense); + } let r = f.reach; let grown = Extent::new(square.min_x - r, square.min_y - r, square.max_x + r, square.max_y + r); let e = &f.extent; if e.min_x >= grown.min_x && e.max_x <= grown.max_x && e.min_y >= grown.min_y && e.max_y <= grown.max_y { // Whole, it takes about its estimate; cut, only its part here, bounded as it's made. - if v.len().saturating_add(f.estimate) > room { + if v.len().saturating_add(f.estimate) > limit { return Err(TessError::TooDense); } - crate::mesh::append_geometry(&mut v, &mut i, &mut no_points, f.geometry, &f.symbol, origin, wireframe, ppp, map_per_px, room)?; + crate::mesh::append_geometry(&mut v, &mut i, &mut no_points, f.geometry, &f.symbol, origin, wireframe, ppp, map_per_px, limit)?; } else { - append_cut(&mut v, &mut i, f, &grown, origin, wireframe, ppp, map_per_px, room)?; + append_cut(&mut v, &mut i, f, &grown, origin, wireframe, ppp, map_per_px, limit)?; } } if i.is_empty() { @@ -378,9 +393,9 @@ fn tile_meshes_on( let side = tile_side(map_per_px)?; let tiles = buckets(features, area, side)?; let threads = threads.unwrap_or_else(|| threads_for(features, &tiles)); - // The vertices of the tiles made so far, which every tile checks against `limit` as it - // goes: the layer never holds much more than `limit` (by the tiles at work at once, each - // within the room left when it started a feature), not `limit` a tile. + // The vertices of the tiles made so far: past `limit` the layer is refused, and the tiles + // still at work stop at their next feature, so it never holds much more than `limit` (by + // the tiles at work at once, each at most `limit`). let used = AtomicUsize::new(0); let made = crate::tile_mesh::parallel_on(&tiles, threads, |(tile, members)| { tile_mesh(features, *tile, members, side, wireframe, ppp, map_per_px, limit, &used) @@ -523,9 +538,13 @@ mod tests { let room = used.max(biggest); assert!(room < f.estimate); assert!(tile_meshes_on(std::slice::from_ref(&f), &area, false, 1.0, 1.0, room, Some(1)).unwrap().is_ok()); - for threads in [1, 8] { - let short = tile_meshes_on(std::slice::from_ref(&f), &area, false, 1.0, 1.0, used - 1, Some(threads)).unwrap(); - assert!(matches!(short, Err(TessError::TooDense)), "{threads} threads"); + // Past the limit by a vertex, or with room for each tile but not all: refused alike on + // any number of threads. + for limit in [used - 1, biggest.max(used / 2)] { + for threads in [1, 8] { + let short = tile_meshes_on(std::slice::from_ref(&f), &area, false, 1.0, 1.0, limit, Some(threads)).unwrap(); + assert!(matches!(short, Err(TessError::TooDense)), "limit {limit}, {threads} threads"); + } } } diff --git a/crates/ui-egui/src/mapgpu.rs b/crates/ui-egui/src/mapgpu.rs index a9d44e994a..e8aec069b3 100644 --- a/crates/ui-egui/src/mapgpu.rs +++ b/crates/ui-egui/src/mapgpu.rs @@ -104,7 +104,11 @@ fn marker_templates() -> [[f32; 4]; TEMPLATE_VERTS * SHAPES] { out } -/// Per-draw-call uniforms (WGSL `CmdUniforms`: 144 bytes). +/// The stencil bit a layer tile's square sets while its mesh draws (the shadows count in the +/// bits below it, and never as far as this one). +const MESH_SQUARE_BIT: u32 = 0x80; + +/// Per-draw-call uniforms (WGSL `CmdUniforms`: 160 bytes). #[repr(C)] #[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] struct CmdUniforms { @@ -488,12 +492,11 @@ impl GpuMapRenderer { ..d }); // A tile's square writes its number into the stencil; its mesh draws only where it is. - let stencil = |face: wgpu::StencilFaceState, write_mask: u32| { - flat.clone().map(|d| wgpu::DepthStencilState { - stencil: wgpu::StencilState { front: face, back: face, read_mask: 0xff, write_mask }, - ..d - }) + let stencil_in = |face: wgpu::StencilFaceState, read_mask: u32, write_mask: u32| { + flat.clone() + .map(|d| wgpu::DepthStencilState { stencil: wgpu::StencilState { front: face, back: face, read_mask, write_mask }, ..d }) }; + let stencil = |face: wgpu::StencilFaceState, write_mask: u32| stencil_in(face, 0xff, write_mask); let mark = wgpu::StencilFaceState { compare: wgpu::CompareFunction::Always, fail_op: wgpu::StencilOperation::Keep, @@ -531,8 +534,9 @@ impl GpuMapRenderer { &[&cmd_layout], scene_format, samples, - stencil(inside, 0), + stencil_in(inside, MESH_SQUARE_BIT, 0), ); + // A layer tile's square sets and clears its own bit, so the shadows' marks under it stay. let mesh_square_pipeline = pipeline( "mapgpu_mesh_square", "vs_mesh_square", @@ -541,7 +545,7 @@ impl GpuMapRenderer { &[&cmd_layout], scene_format, samples, - stencil(mark, 0xff), + stencil_in(mark, MESH_SQUARE_BIT, MESH_SQUARE_BIT), ); let point_pipeline = pipeline("mapgpu_points", "vs_marker", "fs_marker", &point_buffers, &[&cmd_layout], scene_format, samples, flat.clone()); @@ -1715,7 +1719,7 @@ fn paint_draws(renderer: &GpuMapRenderer, draws: &[SceneDraw], rp: &mut wgpu::Re SceneDraw::Mesh { vertices, indices, index_count, bind, square: Some(_), .. } => { rp.set_bind_group(0, bind, &[]); rp.set_pipeline(&renderer.mesh_square_pipeline); - rp.set_stencil_reference(1); + rp.set_stencil_reference(MESH_SQUARE_BIT); rp.draw(0..6, 0..1); rp.set_pipeline(&renderer.mesh_in_square_pipeline); rp.set_vertex_buffer(0, vertices.slice(..));