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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions crates/render/src/frame_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<GpuPart> {
Some(GpuPart { cmds: cmds.iter().map(DrawCmd::share).collect::<Option<_>>()?, 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<GpuPart> {
Some(GpuPart { cmds: cmds.iter().map(DrawCmd::share).collect::<Option<_>>()?, alone, runs, meshed })
}

/// Its commands, shared again for a scene starting from it.
Expand Down
34 changes: 24 additions & 10 deletions crates/render/src/layer_meshes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<DrawCmd>, look: &LayerLook, made: &Made, rows: &[bool]) -> Option<usize> {
/// 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<DrawCmd>, look: &LayerLook, made: &Made, rows: &[bool], room: usize) -> Option<usize> {
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)
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand Down
59 changes: 54 additions & 5 deletions crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// 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
Expand Down Expand Up @@ -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))));
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -5429,8 +5435,11 @@ fn render_frame(
};
let mut highlights: Vec<(usize, Geometry, Symbol, Vec<LineStroke>, 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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<usize> = 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::<usize>() > mesh::MAX_LAYER_VERTICES, "past a layer's own limit: {}", meshes.iter().sum::<usize>());
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.
Expand Down
66 changes: 57 additions & 9 deletions crates/render/src/mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This sizes the scene's mesh budget with memory::scaled (a share of the computer's total memory), not memory::planned. The AGENTS.md "Size for real data" rule says work that grows with its input sizes its limit with memory::planned and refuses past it with a way out. The doc comment gives a reason: planned reads what is free now, which is too often to ask while drawing, and thread_scratch makes the same choice. That is a reasonable argument, and thread_scratch is precedent. But the rule names no exception for drawing, and the reason is not written as one. Either call planned here (it is cheap enough to ask once per scene if that is what the budget is for), or record the exception in the PR's "Suggested AGENTS.md additions" so a maintainer can decide. The 16M-vertex ceiling (640 MB of GPU buffers) is what makes the choice matter on a machine with little free memory.

Category: agents-md

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;
Expand Down Expand Up @@ -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<DrawCmd>,
layer: &Layer,
Expand All @@ -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.
Expand Down Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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<Coord> {
vec![Coord::new(x, y), Coord::new(x + s, y), Coord::new(x + s, y + s), Coord::new(x, y + s)]
}
Expand Down
Loading
Loading