diff --git a/crates/render/src/cancel.rs b/crates/render/src/cancel.rs new file mode 100644 index 0000000000..dfb1707bda --- /dev/null +++ b/crates/render/src/cancel.rs @@ -0,0 +1,100 @@ +//! Stopping a frame no longer wanted (#1750). The desktop app draws a settled flat map's frame on a +//! worker; when the map moves again before it is done, the frame is out of date. The worker +//! installs a flag on its thread ([`install`]) and sets it to stop: the renderer looks at it between +//! layers, between a tilted view's bands, before each chunk of a streamed layer and every +//! [`EVERY`] features or [`EVERY_VERTICES`] vertices of a layer, and a frame stopped that way comes +//! back as `None`, without its tiles, labels or effects worked out. +//! With none installed (an export, the CLI, the browser) frames always finish. The flag is the +//! thread's own: threads the renderer starts for a part of the frame (a raster's rows) don't look +//! at it, and finish their part. A long step without a look (projecting or thinning a layer's +//! geometry for the first time, a raster, a single feature's path) runs to its end. + +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// How many features of a layer are drawn between looks at the flag. +pub(crate) const EVERY: usize = 2048; + +/// How many vertices of a layer are drawn between looks at the flag, so a layer of a few heavy +/// features (a detailed coastline) stops part-way too. +pub(crate) const EVERY_VERTICES: usize = 65_536; + +thread_local! { + static FLAG: RefCell>> = const { RefCell::new(None) }; +} + +/// Makes `flag` stop the frames drawn on this thread until the guard is dropped, which puts back +/// the one before. +pub fn install(flag: Arc) -> Installed { + Installed(FLAG.with(|f| f.replace(Some(flag)))) +} + +/// Puts back the flag before when dropped (see [`install`]). +pub struct Installed(Option>); + +impl Drop for Installed { + fn drop(&mut self) { + let before = self.0.take(); + let _ = FLAG.try_with(|f| f.replace(before)); + } +} + +/// Whether the frame being drawn on this thread was asked to stop. +pub(crate) fn requested() -> bool { + // Never during the thread's teardown: no frame is drawn that late. + FLAG.try_with(|f| f.borrow().as_ref().is_some_and(|flag| flag.load(Ordering::Relaxed))).unwrap_or(false) +} + +#[cfg(test)] +thread_local! { + /// Features drawn on this test thread, to see a stopped frame stop drawing. + pub(crate) static DRAWN: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_flag_stops_frames_on_its_thread_only_while_installed() { + let flag = Arc::new(AtomicBool::new(false)); + assert!(!requested()); + { + let _guard = install(flag.clone()); + assert!(!requested()); + flag.store(true, Ordering::Relaxed); + assert!(requested()); + // Another thread draws on. + assert!(!std::thread::spawn(requested).join().unwrap_or(true)); + } + assert!(!requested()); + } + + #[test] + fn a_stopped_frame_is_no_frame() { + let mut map = rustgis_map::Map::new("m"); + if let Some(d) = crate::world_dataset("Countries", crate::sample_data::COUNTRIES) { + map.add_dataset(d); + } + let view = crate::View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: rustgis_map::Camera::world(), sky: false }; + let flag = Arc::new(AtomicBool::new(false)); + let _guard = install(flag.clone()); + DRAWN.set(0); + assert!(crate::render(&mut map, &view).is_some()); + assert!(DRAWN.get() > 100, "{} countries drawn", DRAWN.get()); + // Stopped, it draws no feature at all, not just hands back nothing. + flag.store(true, Ordering::Relaxed); + DRAWN.set(0); + assert!(crate::render(&mut map, &view).is_none()); + assert_eq!(DRAWN.get(), 0); + // So does a tilted one, drawn band by band. + let tilted = crate::View { camera: rustgis_map::Camera { pitch: 60.0, ..rustgis_map::Camera::world() }, ..view }; + DRAWN.set(0); + assert!(crate::render(&mut map, &tilted).is_none()); + assert_eq!(DRAWN.get(), 0); + flag.store(false, Ordering::Relaxed); + assert!(crate::render(&mut map, &tilted).is_some()); + assert!(DRAWN.get() > 0); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2ac527b24f..4eea27c9af 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6,6 +6,7 @@ //! the labels too, for export and the command line. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod cancel; mod canvas; mod diagrams; mod effects; @@ -2090,6 +2091,10 @@ fn render_with_backend(map: &mut Map, view: &View, full_res_rasters: bool, backe fn render_any(map: &mut Map, view: &View, full_res_rasters: bool, backend: Backend, record: bool) -> Option { let revisions = archive_revisions([&*map]); let output = render_pass(map, view, full_res_rasters, backend, record); + // A frame stopped part-way (see `cancel`) is no frame. + if cancel::requested() { + return None; + } revisions.current([&*map]).then_some(output).flatten() } @@ -2462,6 +2467,11 @@ fn render_tilted(map: &mut Map, view: &View, full_res_rasters: bool, sources_rea let (mut attribution, mut tiles_pending, mut tile_errors) = (Vec::::new(), false, Vec::::new()); let (mut partial, mut pending_in_place) = (Vec::::new(), Vec::::new()); for (i, b) in bands_of.into_iter().enumerate() { + // A stopped frame (see `cancel`) draws no further band, nor its drape or warp. + if cancel::requested() { + map.label_lock = lock; + return None; + } let v = band_view(view, &b); let Some(RenderOutput::Cpu(r)) = render_frame(map, &v, full_res_rasters, Backend::Cpu, Labels::Tilted(view, &mut candidates), false) @@ -2517,6 +2527,10 @@ fn render_tilted(map: &mut Map, view: &View, full_res_rasters: bool, sources_rea } } map.label_lock = lock; + // A frame stopped during its last band goes no further (see `cancel`). + if cancel::requested() { + return None; + } match &ground { Some(g) => { drape_terrain(pm.pixels(), view, map, &kept, g); @@ -2741,10 +2755,19 @@ fn gpu_turned(map: &mut Map, view: &View, full_res_rasters: bool, sources_ready: let mut plain = true; let last = bands.len().saturating_sub(1); for (i, b) in bands.iter().enumerate() { + // A stopped frame (see `cancel`) draws no further band, nor falls back to the CPU. + if cancel::requested() { + map.label_lock = lock; + return None; + } let v = band_view(view, b); let Some(RenderOutput::Gpu(scene)) = render_frame(map, &v, full_res_rasters, Backend::Gpu, Labels::Tilted(view, &mut candidates), false) else { + if cancel::requested() { + map.label_lock = lock; + return None; + } plain = false; break; }; @@ -2800,6 +2823,10 @@ fn gpu_turned(map: &mut Map, view: &View, full_res_rasters: bool, sources_ready: cmds.extend(scene.cmds); } map.label_lock = lock; + // A frame stopped during its last band goes no further (see `cancel`). + if cancel::requested() { + return None; + } if !plain { return None; } @@ -3926,6 +3953,10 @@ fn render_frame( // The layer drawn last, whose tile layers go over it before the next. let mut below: Option = None; for li in order { + // A frame no longer wanted stops between layers (see `cancel`). + if cancel::requested() { + break; + } if let Some(id) = below.take() { draw_tiles!(Some(id)); } @@ -4101,6 +4132,10 @@ fn render_frame( // polygons. let mut extruded_charts: Option = None; let mut draw_chunk = |layer: &mut rustgis_map::Layer| -> rustgis_data::Result<()> { + // A stopped frame draws no more of a layer or a streamed chunk (see `cancel`). + if cancel::requested() { + return Ok(()); + } // The definition query and the display filters that apply at this scale (a feature draws // only if it matches all of them). let mut rows = layer.drawn_rows(scale); @@ -4316,8 +4351,20 @@ fn render_frame( // Polygons with stacked fills (patterns) draw them in place of their single fill. let has_fills = layer.has_fills(); let mut stacked: Vec<(&[Vec], Symbol, &[LineStroke])> = Vec::new(); + // Vertices drawn since the stop was last looked at (see `cancel`). + let mut since_look = 0usize; for (row, g) in drawn.iter().enumerate() { + // And every few thousand features, or vertices, of a large layer. + if (row % cancel::EVERY == 0 && row > 0 || since_look >= cancel::EVERY_VERTICES) && cancel::requested() { + break; + } + if since_look >= cancel::EVERY_VERTICES { + since_look = 0; + } + #[cfg(test)] + cancel::DRAWN.set(cancel::DRAWN.get() + 1); let Some(g) = g else { continue }; + since_look += rustgis_map::lod::vertices(g); let e = extents.get(row).copied().unwrap_or_else(|| g.extent()); // A point's marks, shifted from it, may show while the point is off the view. let marked_in = || { @@ -4514,6 +4561,10 @@ fn render_frame( } else { Vec::new() }; + // A stopped frame places no labels for the rest of the layer (see `cancel`). + if cancel::requested() { + return Ok(()); + } if label_fields.iter().any(Option::is_some) { let label_factor = layer.size_factor(label_scale); // Each class's font, where it is installed. An export (`full_res_rasters`: see @@ -4917,6 +4968,10 @@ fn render_frame( // All coordinates are read here: filtering only to the viewport can change labels, // shadows and screen-space effects whose geometry lies beyond its boundary. let result = visit_complete(source.as_ref(), &mut |features| { + // A frame no longer wanted reads no further (see `cancel`). + if cancel::requested() { + return Err(rustgis_data::DataError::Cancelled); + } chunk.clear_cache(); chunk.selection = features.iter().enumerate().filter_map(|(r, f)| selected_order.contains_key(&f.id).then_some(r)).collect(); @@ -4928,6 +4983,10 @@ fn render_frame( Ok(()) }); if let Err(e) = result { + // Stopped, not failed: the source is fine. + if cancel::requested() { + return None; + } if let Some(s) = &mut layer.source { s.error = Some(e.to_string()); } @@ -4970,6 +5029,11 @@ fn render_frame( cpu_dirty = true; } } + // A frame stopped part-way (see `cancel`) is no frame: its tiles, labels and effects aren't + // worth working out. + if cancel::requested() { + return None; + } if let Some(id) = below { draw_tiles!(Some(id)); } diff --git a/crates/render/src/stream_tests.rs b/crates/render/src/stream_tests.rs index 7135971cef..516bc8ec52 100644 --- a/crates/render/src/stream_tests.rs +++ b/crates/render/src/stream_tests.rs @@ -1436,3 +1436,75 @@ fn streamed_extrusions_keep_their_charts_on_top() { assert!(n * 10 >= whole * 9, "chunks of {size}: {n} chart px, {whole} resident"); } } + +/// A frame stopped while a streamed layer is read reads no further chunk (#1750), and the stop +/// isn't taken for a failure of the source. +#[test] +fn a_stopped_frame_reads_no_further_chunk_and_leaves_its_source_unfailed() { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + /// Chunks that set the frame's stop flag once the first is drawn. + struct StopAfterFirst { + chunks: Chunks, + stop: Arc, + } + impl FeatureSource for StopAfterFirst { + fn info(&self) -> &SourceInfo { + self.chunks.info() + } + fn read(&self, r: &Request) -> rustgis_data::Result { + self.chunks.read(r) + } + fn streams_chunks(&self) -> bool { + true + } + fn visit_chunks( + &self, + e: Option, + n: usize, + visit: &mut dyn FnMut(Vec) -> rustgis_data::Result<()>, + ) -> rustgis_data::Result { + self.chunks.visit_chunks(e, n, &mut |chunk| { + let r = visit(chunk); + self.stop.store(true, Ordering::Relaxed); + r + }) + } + } + let mut m = Map::new("m"); + if let Some(d) = world_dataset("Countries", sample_data::COUNTRIES) { + m.add_dataset(d); + } + let ds = m.layers[0].dataset.clone(); + assert!(ds.features.len() > 100); + let info = SourceInfo { + name: ds.name.clone(), + format: "test", + geometry_type: ds.geometry_type, + fields: ds.fields.clone(), + extent: ds.extent(), + count: Some(ds.features.len() as u64), + crs: "EPSG:4326".into(), + indexed: true, + notes: Vec::new(), + zm_dropped: false, + }; + let stop = Arc::new(AtomicBool::new(false)); + let mut layer = m.layers[0].clone(); + layer.dataset.features = ds.features.iter().take(1).cloned().collect::>().into(); + layer.source = Some(SourceLayer::from_path( + "test.shp", + None, + Box::new(StopAfterFirst { chunks: Chunks { info, ds, size: 20 }, stop: stop.clone() }), + )); + m.layers[0] = layer; + let view = View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: Camera::world(), sky: false }; + settle(&mut m, &view); + stop.store(false, Ordering::Relaxed); + let _guard = crate::cancel::install(stop.clone()); + crate::cancel::DRAWN.set(0); + assert!(render(&mut m, &view).is_none(), "a stopped frame is no frame"); + let drawn = crate::cancel::DRAWN.get(); + assert!(drawn <= 20, "{drawn} features drawn: the read went on past the first chunk"); + assert!(m.layers[0].source.as_ref().is_some_and(|s| s.error.is_none()), "a stop isn't a source error"); +} diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 6106eeba5e..f22a24ba10 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -943,12 +943,32 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { app.map.callout_lonlat.clear(); app.map.callout_map.clear(); } - let settling = (tilted || globe_view || tiled_flat) && !moving && app.ws.playing.is_none() && !hold; + // A flat, north-up map's exact frame after a pan or zoom is drawn off the UI thread too + // (#1750): its last frame, shifted and scaled, stays on screen until the new one arrives, and + // moving again stops it. A change to the map itself (an edit, a layer shown or hidden, a + // resize) is still drawn at once, so it shows without waiting. The browser has one thread: there + // the worker draws it at once, as before. + let flat_settle = cfg!(not(target_arch = "wasm32")) + && !globe_view + && cam.bearing == 0.0 + && cam.pitch == 0.0 + && app.session.map().tiles.is_empty() + && (app.map.texture.is_some() || app.map.gpu_frame.is_some()) + && app.map.key.is_some_and(|k| k.rev == key.rev && k.size == key.size && k.sources == key.sources && (k.cam != key.cam || k.draft)) + // A frame the worker couldn't draw (it panicked, or the system refused its thread) is + // drawn on the UI thread, as before: a refused thread costs smoothness, not the frame. + && !app.map.tilt_settle.failed(key); + let settling = (tilted || globe_view || tiled_flat || flat_settle) && !moving && app.ws.playing.is_none() && !hold; let mut tilt_draped = tilt_draped; // A frame finishing during a new gesture is obsolete. Drain it now so it neither holds - // the worker slot nor keeps screenshot/idle waiters waiting for a frame we will not show. - if !settling && let Some((_, done)) = app.map.tilt_settle.take() { - app.session.map_mut().adopt_caches(&done.map); + // the worker slot nor keeps screenshot/idle waiters waiting for a frame we will not show; + // one still being drawn is stopped, so the worker is free once the map rests again. + if !settling { + if let Some((_, done)) = app.map.tilt_settle.take() { + app.session.map_mut().adopt_caches(&done.map); + } else if app.map.tilt_settle.busy() { + app.map.tilt_settle.cancel(); + } } // A GPU scene that re-projects (no pictures) of this map, at this size: a camera move needs // no picture drawn on the CPU meanwhile. One whose tile layers are all live, without labels @@ -977,7 +997,8 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { if let Some((k, done)) = app.map.tilt_settle.take() { app.session.map_mut().adopt_caches(&done.map); // A frame of this view that couldn't be drawn isn't tried again: nothing is to fill. - if same_view(k, key) && done.rendered.is_none() && done.archives.current([&done.map]) { + // (One stopped part-way just wasn't wanted any more.) + if same_view(k, key) && done.rendered.is_none() && !done.cancelled && done.archives.current([&done.map]) { app.map.filling = false; } // One drawn before tiles or data arrived still shows; the next follows. So does one @@ -1017,6 +1038,10 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } let backend = if gpu_ok { rustgis_engine::render::Backend::GpuLive } else { rustgis_engine::render::Backend::Cpu }; app.map.tilt_settle.start_backend(ui.ctx(), key, app.session.map().clone(), view, backend); + // A worker the system refused wakes no frame: the next draws it here. + if flat_settle && app.map.tilt_settle.failed(key) { + ui.ctx().request_repaint(); + } } let shown = (app.map.texture.is_some() || app.map.gpu_frame.is_some()) && app.map.key.is_some_and(|k| same_view(Key { draft: false, ..k }, key)); @@ -1027,7 +1052,12 @@ fn main_view(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { draped = app.map.drape.prepare(ui.ctx(), app.session.map_mut(), drape_key, tiles, w, h, ppp, time); } else if tilted { tilt_draped = app.map.tilt_drape.prepare(ui.ctx(), app.session.map_mut(), drape_key, tiles, w, h, ppp, time); - } else if app.map.preview_attempt != Some(key) && !reprojects && !(keep_frame && app.map.tilt_settle.busy()) { + } else if app.map.preview_attempt != Some(key) + && !reprojects + // The last frame, shifted, stands in while the worker draws; if it couldn't, a preview. + && !(flat_settle && app.map.tilt_settle.busy()) + && !(keep_frame && app.map.tilt_settle.busy()) + { // A kept frame waits for the exact one; if that couldn't be drawn, a preview. // A small preview shows a visibility change immediately. The exact frame is // already on its way. Even a failed preview is attempted only once per key. @@ -5149,6 +5179,69 @@ mod tests { assert_ne!(shown_layers(&app.session), before, "a layer hidden"); } + /// A flat map's exact frame after a pan or zoom is drawn off the UI thread (#1750): its last + /// frame stays on screen (no preview) while the worker draws, moving again stops the worker, + /// and the frame for where the map rests arrives. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_flat_maps_settled_frame_is_drawn_off_the_ui_thread() { + let _turn = crate::fetching::turn(); + let app = RustGisApp::with_sample(); + let mut h = + egui_kittest::Harness::builder().with_size(vec2(900.0, 550.0)).with_step_dt(0.000_05).with_max_steps(10_000).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + let cam_of = |st: &RustGisApp| { + let c = st.session.map().camera; + ((c.center.x * 100.0) as i64, (c.center.y * 100.0) as i64) + }; + let exact = |h: &mut egui_kittest::Harness<'_, RustGisApp>, what: &str| { + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + h.step(); + let st = h.state(); + if st.map.key.is_some_and(|k| k.rev == st.session.revision && !k.draft && (k.cam.0, k.cam.1) == cam_of(st)) + && !st.map.tilt_settle.busy() + { + break; + } + assert!(std::time::Instant::now() < end, "{what}"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + }; + exact(&mut h, "the first frame did not arrive"); + assert!(h.state().session.map().tiles.is_empty(), "the sample has no tile layers"); + // A pan (the camera moved as a drag moves it, not by a command, which changes the map's + // revision) come to rest: the frame is drawn on the worker, the last one stays meanwhile. + let before = h.state().map.key.expect("a frame"); + let shift = |h: &mut egui_kittest::Harness<'_, RustGisApp>, px: f64| { + let cam = &mut h.state_mut().session.map_mut().camera; + cam.center.x += cam.res * px; + }; + shift(&mut h, 200.0); + h.step(); + assert!(h.state().map.tilt_settle.busy(), "the pan's frame is drawn on the worker"); + assert_eq!(h.state().map.key, Some(before), "the last frame stays on screen, no preview"); + // Moving again stops it; once the map rests, the frame for where it is arrives. + h.state_mut().map.last_interaction = f64::MAX; + shift(&mut h, 150.0); + h.step(); + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + while h.state().map.tilt_settle.busy() { + assert!(std::time::Instant::now() < end, "the stopped frame never came back"); + std::thread::sleep(std::time::Duration::from_millis(2)); + h.step(); + } + h.state_mut().map.last_interaction = -10.0; + exact(&mut h, "the frame of the resting map did not arrive"); + assert_eq!(h.state().map.key.map(|k| k.rev), Some(before.rev)); + } + /// #1051: changing a layer's transparency over a tiled basemap kept the exact frame on /// screen until the next one arrived; it showed a coarse preview of the whole map, basemap /// included, so every step of a slider drag made the map flicker. diff --git a/crates/ui-egui/src/tilt_settle.rs b/crates/ui-egui/src/tilt_settle.rs index d65f5fbb11..61788d4440 100644 --- a/crates/ui-egui/src/tilt_settle.rs +++ b/crates/ui-egui/src/tilt_settle.rs @@ -1,6 +1,7 @@ -//! Exact globe, tilted and tiled flat frames, composed off the UI thread. Such a frame takes a few -//! hundred milliseconds for a large view; composed on the UI thread it froze the map just as it came -//! to rest. A copy of the map is drawn on a worker instead (the copy shares its features and +//! Exact globe, tilted and tiled flat frames, and a flat map's frame after a pan or zoom (#1750), +//! composed off the UI thread. Such a frame takes a few hundred milliseconds for a large view; +//! composed on the UI thread it froze the map just as it came to rest. A frame that goes out of +//! date while it is drawn (the map moves again) is stopped ([`TiltSettle::cancel`]). A copy of the map is drawn on a worker instead (the copy shares its features and //! caches, so it costs pointers), while the drape (see `tilt_drape`) stays on screen until the //! frame is ready. GPU scenes are composed here too, then uploaded on the UI thread. In the //! browser there are no threads: the frame is drawn at once, its tile pictures a frame's worth at @@ -21,13 +22,15 @@ pub(crate) struct Done { pub ms: u64, /// Tile pictures stand in for others, or are still to be drawn: it is drawn again. pub incomplete: bool, + /// It was stopped part-way ([`TiltSettle::cancel`]): no frame, but nothing wrong with it. + pub cancelled: bool, pub archives: render::ArchiveRevision, } /// The frame being drawn (at most one at a time), and what it is for. pub(crate) struct TiltSettle { #[cfg(not(target_arch = "wasm32"))] - job: Option<(K, std::sync::mpsc::Receiver)>, + job: Option<(K, std::sync::mpsc::Receiver, Stop)>, #[cfg(target_arch = "wasm32")] ready: Option<(K, Done)>, /// The last frame that couldn't be drawn (the renderer panicked): it isn't tried again. @@ -46,8 +49,12 @@ impl Default for TiltSettle { } } -fn draw(mut map: Map, view: View, backend: Backend) -> Done { +/// A job's stop flag (see `render::cancel`). +type Stop = std::sync::Arc; + +fn draw(mut map: Map, view: View, backend: Backend, stop: Stop) -> Done { let t0 = web_time::Instant::now(); + let _stop = render::cancel::install(stop.clone()); let archives = render::archive_revisions([&map]); // On the UI thread in the browser, a frame's worth of tile pictures at a time; on a worker // natively, all of them. @@ -59,7 +66,10 @@ fn draw(mut map: Map, view: View, backend: Backend) -> Done { }; #[cfg(not(target_arch = "wasm32"))] let (rendered, incomplete) = (render::render_backend(&mut map, &view, backend), false); - Done { rendered, view, map, ms: t0.elapsed().as_millis() as u64, incomplete, archives } + // Stopped only if it came back without a picture: a stop after the renderer's last look + // leaves a finished frame. + let cancelled = rendered.is_none() && stop.load(std::sync::atomic::Ordering::Relaxed); + Done { rendered, view, map, ms: t0.elapsed().as_millis() as u64, incomplete, cancelled, archives } } impl TiltSettle { @@ -71,10 +81,16 @@ impl TiltSettle { return self.ready.is_some(); } + /// Whether the frame keyed `key` couldn't be drawn here (the worker panicked, or the system + /// refused its thread): it isn't tried again, so the caller draws it another way. + pub fn failed(&self, key: K) -> bool { + self.failed == Some(key) + } + /// The key of the frame being drawn (or drawn and not yet taken). pub fn key(&self) -> Option { #[cfg(not(target_arch = "wasm32"))] - return self.job.as_ref().map(|(k, _)| *k); + return self.job.as_ref().map(|(k, ..)| *k); #[cfg(target_arch = "wasm32")] return self.ready.as_ref().map(|(k, _)| *k); } @@ -88,12 +104,27 @@ impl TiltSettle { /// Builds a CPU frame or GPU scene on the worker; GPU resources are uploaded by the UI. pub fn start_backend(&mut self, ctx: &egui::Context, key: K, map: Map, view: View, backend: Backend) { - self.start_with(ctx, key, move || draw(map, view, backend)); + let stop = Stop::default(); + let flag = stop.clone(); + self.start_with(ctx, key, stop, move || draw(map, view, backend, flag)); + } + + /// Asks the frame being drawn to stop (it is out of date): the renderer looks between layers, + /// before each chunk of a streamed layer, every 2048 features or 65,536 vertices and between + /// a tilted view's bands (see `render::cancel`), so + /// the worker is free again soon. The stopped frame is + /// still handed back by [`TiltSettle::take`], with no picture and `cancelled` set, and its key + /// may be drawn again. In the browser frames are drawn at once: there is nothing to stop. + pub fn cancel(&mut self) { + #[cfg(not(target_arch = "wasm32"))] + if let Some((.., stop)) = &self.job { + stop.store(true, std::sync::atomic::Ordering::Relaxed); + } } /// Starts `work` drawing the frame keyed `key` (see [`TiltSettle::start`]). A panic in it /// gives no frame, and the key isn't tried again. - fn start_with(&mut self, ctx: &egui::Context, key: K, work: impl FnOnce() -> Done + Send + 'static) { + fn start_with(&mut self, ctx: &egui::Context, key: K, stop: Stop, work: impl FnOnce() -> Done + Send + 'static) { if self.busy() || self.failed == Some(key) { return; } @@ -114,12 +145,14 @@ impl TiltSettle { ctx.request_repaint(); }); match spawned { - Ok(_) => self.job = Some((key, rx)), + Ok(_) => self.job = Some((key, rx, stop)), Err(_) => self.failed = Some(key), } } #[cfg(target_arch = "wasm32")] { + // Drawn at once: nothing is left to stop. + let _ = stop; match std::panic::catch_unwind(work) { Ok(done) => self.ready = Some((key, done)), Err(_) => self.failed = Some(key), @@ -132,13 +165,13 @@ impl TiltSettle { pub fn take(&mut self) -> Option<(K, Done)> { #[cfg(not(target_arch = "wasm32"))] let done = { - let (_, rx) = self.job.as_ref()?; + let (_, rx, _) = self.job.as_ref()?; match rx.try_recv() { - Ok(done) => self.job.take().map(|(k, _)| (k, done)), + Ok(done) => self.job.take().map(|(k, ..)| (k, done)), Err(std::sync::mpsc::TryRecvError::Empty) => None, // The worker ended without an answer. Err(std::sync::mpsc::TryRecvError::Disconnected) => { - self.failed = self.job.take().map(|(k, _)| k); + self.failed = self.job.take().map(|(k, ..)| k); None } } @@ -147,6 +180,7 @@ impl TiltSettle { let done = self.ready.take(); if let Some((k, d)) = &done && d.rendered.is_none() + && !d.cancelled && d.archives.current([&d.map]) { self.failed = Some(*k); @@ -186,19 +220,58 @@ mod tests { assert!(s.take().is_none()); } + /// A frame stopped part-way comes back without a picture, isn't taken for one that failed, + /// and frees the worker for the next. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_stopped_frame_comes_back_cancelled_and_can_be_drawn_again() { + let ctx = egui::Context::default(); + let map = Map::new("m"); + let view = View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: map.camera, sky: true }; + let mut s = TiltSettle::default(); + // The work waits until it is stopped, as a long frame would still be drawing. + let stop = Stop::default(); + let seen = stop.clone(); + let (m, v) = (map.clone(), view); + s.start_with(&ctx, 3u8, stop, move || { + while !seen.load(std::sync::atomic::Ordering::Relaxed) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + draw(m, v, Backend::Cpu, seen) + }); + assert!(s.busy()); + s.cancel(); + let end = std::time::Instant::now() + std::time::Duration::from_secs(30); + let done = loop { + if let Some(d) = s.take() { + break d; + } + assert!(std::time::Instant::now() < end, "the stopped frame never came back"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(done.0, 3); + assert!(done.1.cancelled && done.1.rendered.is_none()); + assert!(!s.busy()); + // The same frame is drawn when asked again. + s.start(&ctx, 3u8, map, view); + assert!(s.busy(), "a stopped frame was taken for one that couldn't be drawn"); + s.cancel(); + } + #[test] fn a_frame_that_cant_be_drawn_isnt_tried_again() { let ctx = egui::Context::default(); let map = Map::new("m"); let view = View { width: 64.0, height: 48.0, pixels_per_point: 1.0, camera: Camera { pitch: 60.0, ..Camera::world() }, sky: true }; let mut s = TiltSettle::default(); - s.start_with(&ctx, 1u8, || panic!("the renderer failed")); + s.start_with(&ctx, 1u8, Stop::default(), || panic!("the renderer failed")); let end = std::time::Instant::now() + std::time::Duration::from_secs(30); while s.busy() { assert!(s.take().is_none()); assert!(std::time::Instant::now() < end, "the worker never ended"); std::thread::sleep(std::time::Duration::from_millis(5)); } + assert!(s.failed(1u8) && !s.failed(2u8)); s.start(&ctx, 1u8, map.clone(), view); assert!(!s.busy(), "the same frame was tried again"); s.start(&ctx, 2u8, map, view); @@ -224,7 +297,7 @@ mod tests { } }); let mut s = TiltSettle::default(); - s.start_with(&ctx, 1u8, || panic!("the renderer failed")); + s.start_with(&ctx, 1u8, Stop::default(), || panic!("the renderer failed")); assert!(wake.recv_timeout(std::time::Duration::from_secs(30)).is_ok(), "never woken"); assert!(s.take().is_none()); assert!(!s.busy(), "the woken frame found the job still running");