diff --git a/crates/render/src/frame_cache.rs b/crates/render/src/frame_cache.rs index 5b64f115d9..ce42f69a82 100644 --- a/crates/render/src/frame_cache.rs +++ b/crates/render/src/frame_cache.rs @@ -162,13 +162,16 @@ pub(crate) struct GpuPart { pub alone: usize, /// The pictures flushed so far, as the CPU fallback counts them. pub runs: crate::Runs, + /// The vertices its layers' meshes took of the scene's budget (`mesh::layer_room`). + pub meshed: usize, } impl GpuPart { - /// `cmds` shared, with `alone` layers drawn as pictures of their own and `runs`; `None` when - /// one can't be shared (an extrusion, which only a tilted view's scenes have). - pub(crate) fn of(cmds: &[DrawCmd], alone: usize, runs: crate::Runs) -> Option { - Some(GpuPart { cmds: cmds.iter().map(DrawCmd::share).collect::>()?, alone, runs }) + /// `cmds` shared, with `alone` layers drawn as pictures of their own, `runs`, and `meshed` + /// vertices of the layers' meshes; `None` when one can't be shared (an extrusion, which only + /// a tilted view's scenes have). + pub(crate) fn of(cmds: &[DrawCmd], alone: usize, runs: crate::Runs, meshed: usize) -> Option { + Some(GpuPart { cmds: cmds.iter().map(DrawCmd::share).collect::>()?, alone, runs, meshed }) } /// Its commands, shared again for a scene starting from it. diff --git a/crates/render/src/layer_meshes.rs b/crates/render/src/layer_meshes.rs index 16832de72e..051f70c5d6 100644 --- a/crates/render/src/layer_meshes.rs +++ b/crates/render/src/layer_meshes.rs @@ -34,8 +34,9 @@ use crate::mesh_tiles::MadeTile; /// The most bytes of meshes kept, with what each was made from ([`ENTRY_BYTES`] and its rows): /// about 3.3 million vertices on the desktop and 0.8 million in the browser. Past it, the meshes /// used longest ago go first, but never one a scene being drawn has used ([`Scene`]): when the -/// newest doesn't fit beside those, it isn't kept. A layer's mesh is at most -/// [`crate::mesh::MAX_LAYER_VERTICES`] vertices, 80 MB. +/// newest doesn't fit beside those, it isn't kept. A layer's meshes are mostly at most +/// [`crate::mesh::MAX_LAYER_VERTICES`] vertices, 80 MB; one cut into tiles may hold more, from the +/// scene's budget ([`crate::mesh::layer_room`]), and isn't kept past this. pub(crate) const MAX_BYTES: usize = if cfg!(target_arch = "wasm32") { 32 << 20 } else { 128 << 20 }; /// What a kept mesh is counted as holding beside its data and rows: its layer's look (the @@ -230,15 +231,16 @@ impl Drop for Scene { } /// The commands of the mesh kept for the layer that looks as `look`, made as `made` from `rows`, -/// pushed onto `cmds`, and its vertices; `None`, pushing nothing, when none is kept. -pub(crate) fn take(cmds: &mut Vec, look: &LayerLook, made: &Made, rows: &[bool]) -> Option { +/// pushed onto `cmds`, and its vertices; `None`, pushing nothing, when none is kept or the one +/// kept has more than `room` vertices (the layers below took more of the scene's budget). Not +/// counted as used then, so the mesh made in its place can be kept instead. +pub(crate) fn take(cmds: &mut Vec, look: &LayerLook, made: &Made, rows: &[bool], room: usize) -> Option { let vertices = with_meshes(|m| { m.clock += 1; let clock = m.clock; - let k = m - .kept - .iter_mut() - .find(|k| k.look.id() == look.id() && k.made.same(made) && k.look.change(look) == Change::Same && k.rows == rows)?; + let k = m.kept.iter_mut().find(|k| { + k.look.id() == look.id() && k.made.same(made) && k.look.change(look) == Change::Same && k.rows == rows && k.vertices <= room + })?; k.used = clock; cmds.extend(k.cmds.iter().filter_map(share)); Some(k.vertices) @@ -625,7 +627,7 @@ mod tests { .into_iter() .zip(sizes) .filter(|(id, n)| { - let taken = take(&mut Vec::new(), &look(m, *id), &made, &[true]).is_some(); + let taken = take(&mut Vec::new(), &look(m, *id), &made, &[true], usize::MAX).is_some(); if !taken { keep_within(max, live(m, *id), look(m, *id), made.clone(), &[true], &[mesh(*n)], Vec::new(), *n, 0); } @@ -693,7 +695,7 @@ mod tests { let keep_at = |l: &rustgis_map::Layer, dx: f64, n: usize| { keep_within(max, l.instance_id(), look(l), at(dx), &[true], &[mesh(n)], Vec::new(), n, 0) }; - let has = |l: &rustgis_map::Layer, dx: f64| take(&mut Vec::new(), &look(l), &at(dx), &[true]); + let has = |l: &rustgis_map::Layer, dx: f64| take(&mut Vec::new(), &look(l), &at(dx), &[true], usize::MAX); { let _old = Scene::begin(); keep_at(&la, 0.0, 500); @@ -718,6 +720,18 @@ mod tests { keep_at(&other, 0.0, 400); keep_at(&other, 1.0, 400); assert_eq!((has(&la, 0.0), has(&other, 0.0)), (Some(500), Some(400))); + drop(_scene); + // One past the room a scene has for the layer isn't taken, nor counted as used by it: the + // mesh made in its place within the room is kept instead. + clear(); + { + let _old = Scene::begin(); + keep_at(&la, 0.0, 500); + } + let _scene = Scene::begin(); + assert_eq!(take(&mut Vec::new(), &look(&la), &at(0.0), &[true], 499), None); + keep_at(&la, 0.0, 300); + assert_eq!(take(&mut Vec::new(), &look(&la), &at(0.0), &[true], 499), Some(300)); } /// A map closed lets go of its layers' meshes with the next frame drawn, of any map and on diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index d882334ae9..0aec4fe1c7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4840,6 +4840,10 @@ fn render_frame( } // Set when tiny-skia actually rasterizes into the accumulator. let mut cpu_dirty = false; + // The GPU scene's mesh vertices so far, against its budget: a layer may take more than its + // own limit only from what is left (`mesh::layer_room`). + let scene_budget = if backend.is_gpu() { mesh::scene_vertices() } else { 0 }; + let mut scene_meshed = 0usize; // The pictures flushed so far, as the CPU fallback counts them (see `Runs`). let mut runs = Runs::default(); // The see-through layers drawn as pictures of their own so far (see `GPU_ALONE`); none unless @@ -5095,6 +5099,8 @@ fn render_frame( cmds = g.cmds(); gpu_alone = g.alone; runs = g.runs; + // The layers below took their share of the scene's budget. + scene_meshed = g.meshed; cpu_dirty = c.pixels.is_some(); kept_pictures.extend(c.pixels.iter().map(|p| (cmds.len(), std::sync::Arc::clone(p)))); } @@ -5178,7 +5184,7 @@ fn render_frame( && complete(&tile_out) && let Some(gpu_part) = if gpu { share_kept_pictures(&mut cmds, &mut kept_pictures); - frame_cache::GpuPart::of(&cmds, gpu_alone, runs).map(Some) + frame_cache::GpuPart::of(&cmds, gpu_alone, runs, scene_meshed).map(Some) } else { Some(None) } @@ -5429,8 +5435,11 @@ fn render_frame( }; let mut highlights: Vec<(usize, Geometry, Symbol, Vec, f32)> = Vec::new(); // The GPU mesh vertices the layer has left: a streamed layer's batches share them, so - // one too dense to mesh goes to the CPU however it is split. - let mut mesh_room = mesh::MAX_LAYER_VERTICES; + // one too dense to mesh goes to the CPU however it is split. A layer cut into tiles, + // each within its own limit, may take more, from what the scene has left; not a streamed + // one, whose batches are tiled apart, nor one mesh (a tilted view). + let mut mesh_room = + if mesh_tiled.is_some() && !complete_source { mesh::layer_room(scene_budget, scene_meshed) } else { mesh::MAX_LAYER_VERTICES }; let mut extrusions = if complete_source && layer.geometry_type() == GeometryType::Polygon && layer.extrusion.is_some() @@ -5594,7 +5603,8 @@ 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, markers reaching too + // (past the room `mesh::layer_room` gives it, or past its own limit with a tile past + // `MAX_TILE_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 @@ -5627,7 +5637,10 @@ fn render_frame( Some((rustgis_map::look::LayerLook::of(layer)?, made)) }); let before = cmds.len(); - let collected = match keeping.as_ref().and_then(|(look, made)| layer_meshes::take(&mut cmds, look, made, &rows)) { + // A kept mesh past the layer's room now (the layers before it took more of the + // scene's budget) isn't taken: the layer is made again within it. + let taken = keeping.as_ref().and_then(|(look, made)| layer_meshes::take(&mut cmds, look, made, &rows, mesh_room)); + let collected = match taken { Some(used) => Ok(used), None => { // Panned since, the tiles still in the scene are taken as they were made. @@ -5659,6 +5672,9 @@ fn render_frame( }; // Once a batch is too dense, the layer's later ones fall back too (they get no // room); one lyon refused leaves the room to the batches after it. + if let Ok(used) = collected { + scene_meshed = scene_meshed.saturating_add(used); + } mesh_room = match collected { Ok(used) => mesh_room.saturating_sub(used), Err(mesh::TessError::TooDense) => 0, @@ -11486,6 +11502,39 @@ mod tests { } } + /// A layer past `MAX_LAYER_VERTICES` whose tiles each keep to `MAX_TILE_VERTICES` meshes, + /// from what the scene's budget has left, instead of being drawn on the CPU. + #[test] + fn gpu_backend_meshes_a_layer_past_its_own_limit_in_tiles_within_theirs() { + // 72,900 stroked triangles a few pixels across, over about 1,500 × 1,200 pixels. + let mut m = Map::new("Map"); + let mut d = Dataset::new("spread", GeometryType::Polygon, vec![]); + for i in 0..270 { + for j in 0..270 { + let (x, y) = (f64::from(i) * 0.05, f64::from(j) * 0.04); + let ring = vec![Coord::new(x, y), Coord::new(x + 0.03, y), Coord::new(x, y + 0.03)]; + d.push(Some(Geometry::Polygon(vec![vec![ring]])), vec![]); + } + } + m.add_dataset(d); + let camera = Camera { center: lonlat_to_merc(Coord::new(6.75, 5.4)), res: 1000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 1600.0, height: 1300.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(&"image"), "no CPU picture: {kinds:?}"); + let meshes: Vec = scene + .cmds + .iter() + .filter_map(|c| match c { + gpu_scene::DrawCmd::Mesh { vertices, .. } => Some(vertices.len()), + _ => None, + }) + .collect(); + assert!(meshes.len() > 4, "in tiles: {}", meshes.len()); + assert!(meshes.iter().sum::() > mesh::MAX_LAYER_VERTICES, "past a layer's own limit: {}", meshes.iter().sum::()); + assert!(meshes.iter().all(|v| *v <= mesh::MAX_TILE_VERTICES), "each tile within its own: {meshes:?}"); + } + /// A turned or tilted view with a layer too dense to mesh is drawn on the CPU, as the CPU /// backend draws it, and the GPU frame tried first stops at that layer: the one above it is /// never meshed (#2540). Without it, the view stays a GPU scene. diff --git a/crates/render/src/mesh.rs b/crates/render/src/mesh.rs index 5046789d36..a151850ab0 100644 --- a/crates/render/src/mesh.rs +++ b/crates/render/src/mesh.rs @@ -395,9 +395,43 @@ pub(crate) fn append_geometry( /// The most vertices one layer's mesh may take (40 bytes each: 80 MB, well inside the 256 MiB /// `max_buffer_size` devices and WebGL offer). A layer of a million tiny polygons (3D buildings /// as faces) would tessellate to tens of millions — seconds per frame, for a mesh the device -/// then refuses — while the CPU path splats its sub-pixel features in milliseconds. +/// then refuses — while the CPU path splats its sub-pixel features in milliseconds. A layer cut +/// into tiles may take more, from what the scene has left ([`layer_room`]), when each of its +/// tiles keeps to [`MAX_TILE_VERTICES`]. pub(crate) const MAX_LAYER_VERTICES: usize = 2_000_000; +/// The most vertices a tile's mesh may take for its layer to take more than +/// [`MAX_LAYER_VERTICES`]: 2^20, from two to eight a pixel of the tile (a power of two map units, +/// 362 to 724 pixels on a side). Denser, its features are mostly smaller than a pixel, which the +/// CPU splats quicker than lyon tessellates them: such a layer draws on the CPU. Within its own +/// limit, a layer's tiles may be as dense as one mesh of it. +pub(crate) const MAX_TILE_VERTICES: usize = 1 << 20; + +/// The vertices a GPU scene's layer meshes may take together past what each layer may always take +/// ([`MAX_LAYER_VERTICES`]): a sixteenth of the computer's memory at 40 bytes a vertex, from 6 +/// million (240 MB: the browser, a phone, a computer whose memory isn't known) to 16 million +/// (640 MB). Highlights, extrusions, the basemap and the graticule aren't counted: they are +/// bounded by their own data. A share of the memory (`memory::scaled`), not of what is free now +/// (`memory::planned`): it is asked once a scene, too often to ask the system what is free. +/// [`rustgis_data::memory::thread_scratch`], asked while drawing too, makes the same choice, and a +/// phone takes the floor, as it does there. +pub(crate) fn scene_vertices() -> usize { + const FLOOR: usize = 6_000_000; + const CEILING: usize = 16_000_000; + if rustgis_data::memory::on_phone() { + return FLOOR; + } + rustgis_data::memory::scaled(rustgis_data::memory::physical().map(|m| m / 4), FLOOR, CEILING, 40) +} + +/// The vertices the next layer's meshes may take when the scene's meshes hold `meshed` of a +/// budget of `scene` ([`scene_vertices`]): [`MAX_LAYER_VERTICES`], as every layer may, or what +/// the budget has left when that is more. So a layer that meshes on its own meshes in any +/// scene, and the scene passes its budget by no more than those layers do. +pub(crate) fn layer_room(scene: usize, meshed: usize) -> usize { + MAX_LAYER_VERTICES.max(scene.saturating_sub(meshed)) +} + /// The vertex limit of meshes that aren't a layer's (highlights, the basemap, the graticule, /// extrusion roofs): small or bounded by their own data. pub(crate) const NO_LIMIT: usize = usize::MAX; @@ -469,11 +503,13 @@ fn stroke_reach(g: &Geometry, s: &Symbol, wireframe: bool, ppp: f32, map_per_px: /// the rest meshed on several threads, or made one mesh when `tiling` is `None` (a tilted view, /// whose far strokes are wider than a tile's reach); its markers follow them as one command. /// Tiled, its lines and polygons are those within a tile of the cull's tiles -/// ([`crate::mesh_tiles::feature_area`]), which may be more than `visible` keeps, out of view. `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). +/// ([`crate::mesh_tiles::feature_area`]), which may be more than `visible` keeps, out of view. +/// `limit` is what is left of the layer's room ([`layer_room`]; its earlier batches took the +/// rest). One mesh, and each tile, keeps to [`MAX_LAYER_VERTICES`] of it; for the tiles to take +/// more than that together, each keeps to [`MAX_TILE_VERTICES`]. `Ok` with the mesh vertices pushed; `Err(Refused)` +/// when lyon refused a feature, `Err(TooDense)` when the meshes would pass those limits, +/// `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, @@ -495,6 +531,8 @@ pub(crate) fn collect_layer( let mut estimate = 0usize; let mut features = Vec::new(); let mut markers = Vec::new(); + // One mesh is one buffer: it keeps to a layer's own limit, whatever room the scene leaves. + let one = limit.min(MAX_LAYER_VERTICES); // Tiled, a tile's mesh takes every feature reaching it, wherever the cull's edge lies, so a // kept tile is the one meshing it again makes: lines and polygons are kept by the tiles' area // (a tile past them all round), markers by the cull. @@ -530,7 +568,7 @@ pub(crate) fn collect_layer( // tiles take only each feature's part in them, and keep to the limit as they're made. if tiling.is_none() { estimate = estimate.saturating_add(n); - if estimate > limit { + if estimate > one { return Err(TessError::TooDense); } } @@ -574,10 +612,10 @@ pub(crate) fn collect_layer( for f in shown { // 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 { + if v.len().saturating_add(f.estimate) > one { return Err(TessError::TooDense); } - append_geometry(&mut v, &mut i, &mut Vec::new(), f.geometry, &f.symbol, origin, wireframe, ppp, map_per_px, limit)?; + append_geometry(&mut v, &mut i, &mut Vec::new(), f.geometry, &f.symbol, origin, wireframe, ppp, map_per_px, one)?; } let used = v.len(); let mesh = (!i.is_empty()).then(|| DrawCmd::Mesh { origin, vertices: Arc::new(v), indices: Arc::new(i), square: None }); @@ -687,6 +725,16 @@ mod tests { use rustgis_data::GeometryType; use rustgis_map::Marker; + #[test] + fn a_layer_may_take_its_own_limit_or_what_the_scene_has_left() { + assert_eq!(layer_room(6_000_000, 0), 6_000_000); + assert_eq!(layer_room(6_000_000, 3_500_000), 2_500_000); + assert_eq!(layer_room(6_000_000, 5_000_000), MAX_LAYER_VERTICES, "its own, however full the scene"); + assert_eq!(layer_room(6_000_000, 9_000_000), MAX_LAYER_VERTICES); + let budget = scene_vertices(); + assert!((6_000_000..=16_000_000).contains(&budget), "{budget}"); + } + fn square(x: f64, y: f64, s: f64) -> Vec { vec![Coord::new(x, y), Coord::new(x + s, y), Coord::new(x + s, y + s), Coord::new(x, y + s)] } diff --git a/crates/render/src/mesh_tiles.rs b/crates/render/src/mesh_tiles.rs index 68e04ad69b..63ce1fd589 100644 --- a/crates/render/src/mesh_tiles.rs +++ b/crates/render/src/mesh_tiles.rs @@ -391,8 +391,20 @@ fn append_cut( Ok(()) } +/// The vertex limits a layer's tiles keep to beside the layer's room: each tile's mesh, one +/// buffer, at most `own`; for the layer to take more than `own` together, every tile at most +/// `dense` ([`crate::mesh::MAX_TILE_VERTICES`]). +#[derive(Clone, Copy)] +struct Caps { + own: usize, + dense: usize, +} + +/// The limits the scene's layers keep to. +const CAPS: Caps = Caps { own: crate::mesh::MAX_LAYER_VERTICES, dense: crate::mesh::MAX_TILE_VERTICES }; + /// 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. +/// reach, within `own` vertices. `Ok(None)` when nothing draws there. fn tile_mesh( features: &[Feature<'_>], tile: Tile, @@ -401,7 +413,7 @@ fn tile_mesh( wireframe: bool, ppp: f32, map_per_px: f64, - limit: usize, + (limit, own): (usize, usize), used: &AtomicUsize, ) -> Result { let origin = tile.corner(side); @@ -411,8 +423,7 @@ fn tile_mesh( for &k in members { let Some(f) = features.get(k) else { continue }; // 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). + // so it stops early. if used.load(Ordering::Relaxed) > limit { return Err(TessError::TooDense); } @@ -422,12 +433,12 @@ fn tile_mesh( 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. need = need.max(v.len().saturating_add(f.estimate)); - if need > limit { + if need > own { 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, limit)?; + crate::mesh::append_geometry(&mut v, &mut i, &mut no_points, f.geometry, &f.symbol, origin, wireframe, ppp, map_per_px, own)?; } else { - append_cut(&mut v, &mut i, f, &grown, origin, wireframe, ppp, map_per_px, limit)?; + append_cut(&mut v, &mut i, f, &grown, origin, wireframe, ppp, map_per_px, own)?; } } // Each part is refused once it passes the room left: it fits a limit as low as the vertices. @@ -456,11 +467,11 @@ pub(crate) fn tile_meshes( map_per_px: f64, limit: usize, ) -> Option, usize), TessError>> { - tile_meshes_on(features, area, kept, wireframe, ppp, map_per_px, limit, None) + tile_meshes_on(features, area, kept, wireframe, ppp, map_per_px, limit, CAPS, None) } -/// [`tile_meshes`] on `threads` threads, or as [`threads_for`] decides. -#[expect(clippy::too_many_arguments, reason = "the layer, the scene's area and scale, the tiles kept and the threads")] +/// [`tile_meshes`] within `caps`, on `threads` threads, or as [`threads_for`] decides. +#[expect(clippy::too_many_arguments, reason = "the layer, the scene's area and scale, the tiles kept, the limits and the threads")] fn tile_meshes_on( features: &[Feature<'_>], area: &Extent, @@ -469,6 +480,7 @@ fn tile_meshes_on( ppp: f32, map_per_px: f64, limit: usize, + caps: Caps, threads: Option, ) -> Option, usize), TessError>> { let side = tile_side(map_per_px)?; @@ -478,24 +490,29 @@ fn tile_meshes_on( tiles.iter().map(|(tile, _)| kept.binary_search_by(|k| k.tile.cmp(tile)).ok().and_then(|i| kept.get(i))).collect(); let to_make: Vec<&(Tile, Vec)> = tiles.iter().zip(&taken).filter(|(_, k)| k.is_none()).map(|(t, _)| t).collect(); let threads = threads.unwrap_or_else(|| threads_for(features, &to_make)); + // A tile's own room is the layer's limit, or one buffer's when that is less: not what the + // tiles finished first left, so whether the layer meshes doesn't hang on which those were + // (the same on any number of threads). + let own = limit.min(caps.own); // The vertices of the tiles made or taken 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`). + // (by the tiles at work at once, each at most `own`). let used = AtomicUsize::new(taken.iter().flatten().map(|k| k.vertices()).fold(0, usize::saturating_add)); if used.load(Ordering::Relaxed) > limit { return Some(Err(TessError::TooDense)); } let made = crate::tile_mesh::parallel_on(&to_make, threads, |(tile, members)| { - tile_mesh(features, *tile, members, side, wireframe, ppp, map_per_px, limit, &used) + tile_mesh(features, *tile, members, side, wireframe, ppp, map_per_px, (limit, own), &used) }); let mut made = made.into_iter(); let mut out = Vec::with_capacity(tiles.len()); let mut used = 0usize; + let mut densest = 0usize; for k in taken { let tile = match k { // One that wouldn't fit the limit would be refused again, and with it the layer, in // its place in grid order (an error in a tile before it is the layer's). - Some(k) if k.need > limit => return Some(Err(TessError::TooDense)), + Some(k) if k.need > own => return Some(Err(TessError::TooDense)), Some(k) => k.share(), // A tile that panicked (hostile data) leaves the layer to the CPU, as lyon refusing it. None => match made.next().flatten().unwrap_or(Err(TessError::Refused)) { @@ -507,8 +524,14 @@ fn tile_meshes_on( if used > limit { return Some(Err(TessError::TooDense)); } + densest = densest.max(tile.need); out.push(tile); } + // Past a layer's own limit only with every tile within a dense tile's: a denser one's + // features are mostly under a pixel, quicker splatted. Within it, as any layer may. + if used > caps.own && densest > caps.dense { + return Some(Err(TessError::TooDense)); + } Some(Ok((out, used))) } @@ -597,7 +620,7 @@ mod tests { 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 (cmds, used) = tile_meshes_on(&features, &area, &[], false, 1.0, 1.0, usize::MAX, CAPS, Some(threads)).unwrap().unwrap(); let cmds = commands(&cmds); let bytes: Vec> = cmds .iter() @@ -627,7 +650,8 @@ mod tests { 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(); + let (all, used) = + tile_meshes_on(std::slice::from_ref(&f), &area, &[], false, 1.0, 1.0, usize::MAX, CAPS, Some(1)).unwrap().unwrap(); let all = commands(&all); assert!(tiles(&all).len() >= 4, "{}", tiles(&all).len()); assert!(used < f.estimate, "cut to the area: {used} of {}", f.estimate); @@ -635,17 +659,48 @@ mod tests { // 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()); + assert!(tile_meshes_on(std::slice::from_ref(&f), &area, &[], false, 1.0, 1.0, room, CAPS, Some(1)).unwrap().is_ok()); // 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(); + let short = tile_meshes_on(std::slice::from_ref(&f), &area, &[], false, 1.0, 1.0, limit, CAPS, Some(threads)).unwrap(); assert!(matches!(short, Err(TessError::TooDense)), "limit {limit}, {threads} threads"); } } } + /// A layer takes more than its own limit only when each of its tiles keeps to a dense tile's: + /// a denser one's features are mostly under a pixel, quicker splatted on the CPU. Within its + /// own limit, a tile may be as dense as before. + #[test] + fn a_layer_past_its_own_limit_needs_every_tile_within_a_dense_ones() { + // Four lines alike, each in a tile of its own: a tile's need (its estimate, more than + // its vertices) is less than the four's vertices. + let line = |x: f64| { + Geometry::Line(vec![(0..120u32).map(|k| Coord::new(x + f64::from(k) * 3.0, 100.0 + f64::from(k % 2) * 40.0)).collect()]) + }; + let lines = [line(20.0), line(600.0), line(1100.0), line(1700.0)]; + let s = symbol(rustgis_map::Rgba::rgb(0, 0, 0), 1.0); + let features: Vec> = lines.iter().map(|l| feature(l, s)).collect(); + let area = Extent::new(10.0, 10.0, 2100.0, 500.0); + let made = + |caps: Caps, threads: usize| tile_meshes_on(&features, &area, &[], false, 1.0, 1.0, usize::MAX, caps, Some(threads)).unwrap(); + let Ok((tiles, used)) = made(CAPS, 1) else { panic!("meshed") }; + let needs: Vec = tiles.iter().filter(|t| t.cmd.is_some()).map(|t| t.need).collect(); + assert!(needs.len() >= 4, "{needs:?}"); + let densest = needs.iter().copied().max().unwrap_or(0); + assert!(densest < used, "{needs:?} of {used}"); + for threads in [1, 8] { + // Past its own limit, with a tile past a dense one's: refused. + assert!(matches!(made(Caps { own: used - 1, dense: densest - 1 }, threads), Err(TessError::TooDense)), "{threads} threads"); + // Every tile within: it meshes. + assert!(made(Caps { own: used - 1, dense: densest }, threads).is_ok(), "{threads} threads"); + // Within its own limit, however dense a tile. + assert!(made(Caps { own: used, dense: 1 }, threads).is_ok(), "{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. @@ -716,7 +771,7 @@ mod tests { let before = Extent::new(-1800.0, -1500.0, 700.0, 900.0); let after = Extent::new(-1000.0, -1100.0, 1535.0, 1300.0); let made = |area: &Extent, kept: &[MadeTile]| { - tile_meshes_on(&features, area, kept, false, 1.0, 1.0, usize::MAX, Some(1)).unwrap().unwrap() + tile_meshes_on(&features, area, kept, false, 1.0, 1.0, usize::MAX, CAPS, Some(1)).unwrap().unwrap() }; let (kept, _) = made(&before, &[]); let (fresh, fresh_used) = made(&after, &[]); @@ -742,7 +797,7 @@ mod tests { } fn made_within(features: &[Feature<'_>], area: &Extent, kept: &[MadeTile], limit: usize) -> Result<(Vec, usize), TessError> { - tile_meshes_on(features, area, kept, false, 1.0, 1.0, limit, Some(1)).unwrap() + tile_meshes_on(features, area, kept, false, 1.0, 1.0, limit, CAPS, Some(1)).unwrap() } #[test]