From d5d9a1a4fbc892b5f4e641baebf64773c2aff569 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Mon, 23 Nov 2026 17:30:57 -0700 Subject: [PATCH] fix(stage): a zoom gesture draws once it rests, and tiles of states and zooms no longer shown go (M8) The stage tells the render service which picture set is on screen, drops the textures of other sets when the view is whole, asks for nothing while the zoom is changing, and in the browser draws for at most 8 ms of a frame while moving around. ADR 0132, changelog, roadmap. #314, #477, P-004. --- CHANGELOG.md | 22 +++ crates/engine/tests/wasm.rs | 60 +++++++ .../0132-memory-and-frame-time-stay-flat.md | 145 +++++++++++++++ docs/architecture.md | 8 +- docs/roadmap.md | 2 +- src/main.rs | 2 + src/stage.rs | 62 ++++++- src/stage_budget_tests.rs | 165 ++++++++++++++++++ 8 files changed, 459 insertions(+), 7 deletions(-) create mode 100644 docs/adr/0132-memory-and-frame-time-stay-flat.md create mode 100644 src/stage_budget_tests.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 29fba4bf..5d7e0210 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ ## Unreleased +* **Memory and frame time stay flat** (M8, P-004, ADR 0132; + [#314](https://github.com/storytold/anicraft/issues/314), + [#477](https://github.com/storytold/anicraft/issues/477)). + * **Memory follows what is on screen, not how long you have been editing.** Dragging + something made a new picture of the stage on every pointer move, and each one stayed in + memory until hundreds of megabytes were in use (the "900 MB for a 24-frame move" of #314). + AniCraft now keeps the pictures of the document as it is and as it was one step ago, at + the zoom on screen and the one before, plus the frames you have played; a long drag or a + long zoom ends with the memory it started with. + * **Zooming with Ctrl+wheel or a pinch no longer redraws the stage for every step of the + zoom.** The picture on screen is scaled while the zoom changes and drawn sharp once it + rests. In the web version, which draws on the interface's own thread, this was the + stutter of #477; there, moving around the stage now also draws for at most 8 ms of a + frame and fills in the rest over the next frames. + * **Zoomed far into a large drawing, a stage tile no longer goes through the whole + drawing.** The parts of a filled shape above, below and to the right of the tile are left + out before drawing. The pictures are the same to the last bit (tests compare them). + * **What is on screen is drawn before look-ahead.** A visible tile used to wait for up to + 31 tiles being drawn ahead around the view or along the timeline. + * One step further back in the undo history is redrawn when you return to it (a few + milliseconds) instead of being found in memory. + * **A long Brush stroke no longer freezes the window** (M8, ADR 0129, #519, backlog P-003). * A stroke drawn for a long time, over itself again and again, took longer to turn into a shape the longer it was, and a part of it selected over the rest cost seconds on every diff --git a/crates/engine/tests/wasm.rs b/crates/engine/tests/wasm.rs index ee0e7fbe..7be51aae 100644 --- a/crates/engine/tests/wasm.rs +++ b/crates/engine/tests/wasm.rs @@ -133,3 +133,63 @@ fn exports_and_reimports_svg_and_lottie_in_memory() { assert!(lottie["layers"].as_array().is_some_and(|l| !l.is_empty())); assert!(lottie_bytes.windows(5).any(|w| w == b"\"a\":1")); } + +/// Pages of this module's memory, which only ever grows: what a browser tab is charged for. +fn memory_mb() -> f64 { + core::arch::wasm32::memory_size(0) as f64 * 65536.0 / 1048576.0 +} + +/// #314 in the browser itself (P-004, ADR 0132): a long drag is a new document state on every +/// pointer move. The stage says which state it shows, so the pictures of the states before go +/// and the module's memory stops growing after the first moves; before, every state's pictures +/// stayed until the cache's whole budget was in use. A view also fills in a step at a time +/// when it is asked for within a budget, since there is no thread to draw it. +#[wasm_bindgen_test] +fn a_long_drag_does_not_grow_the_memory() { + use anicraft_engine::geom::Affine; + use anicraft_engine::render::View; + let mut s = Session::new(anicraft_engine::doc::sample::demo()); + s.execute("edit.select_all", &json!({})).unwrap(); + let svc = RenderService::new(256 << 20, None); + assert!(!svc.has_thread()); + // A 1024 × 512 view of the stage in two tiles, as the stage cuts it. + let tiles = |s: &Session| -> Vec<_> { + (0..2).map(|tx| svc.job(s.state, &s.doc, 0, View { transform: Affine::translate(-512.0 * tx as f32, 0.0), width: 512, height: 512, background: Some(s.doc.stage.background) }, None)).collect() + }; + let mut drag = |s: &mut Session, moves: u32, show: bool| { + let started = web_time::Instant::now(); + for i in 0..moves { + s.execute("element.translate", &json!({"dx": if i % 2 == 0 { 2 } else { -2 }, "dy": 0})).unwrap(); + let jobs = tiles(s); + if show { + svc.show(jobs[0].set); + } + assert!(svc.request_batch(jobs).iter().all(Option::is_some)); + } + started.elapsed().as_secs_f64() * 1000.0 / f64::from(moves) + }; + let start = memory_mb(); + drag(&mut s, 12, true); + let early = memory_mb(); + let ms = drag(&mut s, 120, true); + let late = memory_mb(); + wasm_bindgen_test::console_log!("drag, the shown state kept: {start:.0} MB at the start, {early:.0} MB after 12 moves, {late:.0} MB after 132; {ms:.1} ms a move; cache {:.0} MB", svc.cache_stats().1 as f64 / 1048576.0); + assert!(late <= early + 8.0, "memory grew from {early} MB to {late} MB over 120 more moves"); + assert!(svc.cache_stats().0 <= 4, "two states of two tiles"); + // Fills in a step at a time within a budget. + s.execute("element.translate", &json!({"dx": 1, "dy": 0})).unwrap(); + let jobs = tiles(&s); + let first = svc.request_batch_within(jobs.clone(), std::time::Duration::ZERO); + assert_eq!(first.iter().filter(|i| i.is_some()).count(), 1); + assert!(svc.request_batch_within(jobs, std::time::Duration::ZERO).iter().all(Option::is_some)); + // As it was before (every state's pictures kept): the same drag again without saying + // what is shown. Printed for docs/performance.md, not checked. + let svc_before = RenderService::new(256 << 20, None); + let before = memory_mb(); + for i in 0..120 { + s.execute("element.translate", &json!({"dx": if i % 2 == 0 { 2 } else { -2 }, "dy": 0})).unwrap(); + let jobs: Vec<_> = (0..2).map(|tx| svc_before.job(s.state, &s.doc, 0, View { transform: Affine::translate(-512.0 * tx as f32, 0.0), width: 512, height: 512, background: Some(s.doc.stage.background) }, None)).collect(); + svc_before.request_batch(jobs); + } + wasm_bindgen_test::console_log!("drag, every state kept (before): {before:.0} MB to {:.0} MB over 120 moves; cache {:.0} MB", memory_mb(), svc_before.cache_stats().1 as f64 / 1048576.0); +} diff --git a/docs/adr/0132-memory-and-frame-time-stay-flat.md b/docs/adr/0132-memory-and-frame-time-stay-flat.md new file mode 100644 index 00000000..91d49a53 --- /dev/null +++ b/docs/adr/0132-memory-and-frame-time-stay-flat.md @@ -0,0 +1,145 @@ +# ADR 0132: Memory and frame time stay flat: picture sets, a zoom at rest, and edges nobody sees + +* Status: accepted (2026-11-23) +* Relates to: backlog item P-004 (`docs/roadmap.md`), issues + [#314](https://github.com/storytold/anicraft/issues/314) and + [#477](https://github.com/storytold/anicraft/issues/477), ADR 0002 (the render thread), + ADR 0006 (latency or throughput), ADR 0007 (stage tiles), ADR 0029 (pictures kept on the + GPU), ADR 0036 (the web build), ADR 0112 (several documents), `docs/performance.md` + +## Context + +Two reports: "a single symbol that moves across the screen with 24 frames takes up 900 MB" +in the web version (#314), and "the app stutters and lags when I try to zoom in very closely" +after drawing with the Brush (#477). An earlier fix cut the web build's picture cache from +768 MB to 256 MB, which lowered the ceiling without changing why it was reached. + +We measured before changing anything (`docs/performance.md` has the tables): + +* **Drawing a stage tile costs the same at every zoom.** A 1600 × 900 view takes 8 to 10 ms on + the CPU oracle from 100 % to 6400 %, also for a drawing of 64 merged brush strokes. The + cost is the pixels. So "re-tessellation at deep zoom" was not the stutter on a fast machine. +* **But the work per tile grew with the zoom and with the whole drawing.** A tile prepared + every edge of every item that touched it: 42,000 edges for the view at 100 %, 306,000 at + 3200 %, all but a few off the tile. For a drawing of hundreds of strokes that term overtakes + the pixels. +* **The cache filled with pictures nobody could ask for again.** A drag makes a new document + state on every pointer move; each state's tiles were kept until the least recently used + fell out of a 768 MB budget (384 MB more on the GPU, 192 tile textures in the shell). A + zoom gesture did the same with zoom levels: 136 MB after 84 frames of Ctrl+wheel. That is + #314: the memory followed how long you had been editing, not what was on screen. +* **Every frame of a zoom gesture asked for a whole view** at a zoom level the next frame no + longer wanted. With a render thread the answers arrived too late to be shown; in the + browser, which has no thread (ADR 0036), they were drawn inside the frame. +* **A visible tile waited for look-ahead.** The render thread took up to 32 jobs a pass, the + urgent ones topped up with look-ahead, and put the pictures in the cache when the whole + pass was done. + +## Decision + +### 1. Picture sets: the cache keeps what is on screen + +Every picture belongs to a **picture set**: one document state at one scale +(`render_service::set_key`, in every `FrameJob` and `FrameImage`). The stage tells the render +service which set it shows (`RenderService::show`, each frame, cheap when nothing changed). +The cache keeps that set and the one shown before it (`KEEP_SETS = 2`) and drops the pictures +of every other set at once. A picture that finishes for a set that has gone is not kept, and +the render thread doesn't start one. + +Two, not one, so that undo then redo, or 100 % and back, finds its pictures. Not more: a +third state back is one redraw away (a few milliseconds), and each kept set is a view's worth +of memory. The frames of a movie played at one zoom are one set, so playback caching is as it +was, under the same byte budgets. A cache nobody has told what is shown (tests, tools) keeps +everything, as before. + +The shell does the same with its tile textures: when the view is whole, the textures of +other sets, which were only standing in for it, go. + +**Considered:** lowering the budgets (it moves the ceiling, as the earlier fix did); +keying tiles by their content so a drag only redraws the tiles the dragged thing touches (the +right next step for the browser, where a drag still redraws the view on the interface thread; +a much larger change, listed under P-004 as not yet). + +### 2. A zoom that is changing draws nothing + +While this frame's device scale differs from the last frame's, the stage asks for no tiles +and no look-ahead and paints the pictures it has, scaled (ADR 0007 already draws stale tiles +under missing ones). The first frame at rest asks once. No timer: egui smooths a wheel notch +over several frames, and each of those has a different zoom. + +### 3. What the screen needs is drawn first and alone + +The render thread takes urgent jobs in passes of their own. Look-ahead goes in passes of one +job per thread (`lookahead_batch`), so an urgent request arriving meanwhile waits about one +tile's time, not 32 tiles'. + +### 4. Without a render thread, moving around the stage has a time budget + +`RenderService::request_batch_within(jobs, budget)` draws, with no render thread, until the +budget is spent (at least one picture) and leaves the rest for the next call. The stage uses +it (8 ms) when the document state and frame are the ones on screen, that is for a pan or a +zoom come to rest: the tiles then agree with each other whatever order they arrive in. An +edit or another frame of the movie is still drawn whole in one call, because half of one +state beside half of another is worse than a late frame. + +### 5. Edges that add nothing are left out, and the pictures are the same to the last bit + +The oracle's rasterizer accumulates signed area per row. Reading its code: + +* an edge wholly above or below the rows being filled is skipped; +* an edge wholly at or right of the row's end deposits into cells past the last pixel, which + no pixel reads; +* an edge to the **left** does count: it carries the winding into the row. + +So `render::prepare` now + +* drops from each fill polygon every point whose two neighbours and itself are all above, all + below, or all right of the surface (`drop_unseen`; one place at a time, since a chord from + "above" to "right" can cross the surface). The two edges at such a point add nothing and + neither does the one that replaces them, and the edges that do add are walked in the same + order; +* flattens a curve whose control points are all in one of those places to its chord + (`Path::flatten_with`), with a margin below and right for the rounding of the curve's + points. Only for a fill alone (a stroke's dashes and width follow the length along the + whole line, and a hairline is not a filled polygon), and only when the path's segment ends + already reach all four sides of the surface, so that the fill's pixel bounds, which place + the coverage buffer, are the whole surface either way. + +The left side is deliberately not cut: a chord there has the same area mathematically, but +the sum of many small heights and one large one can differ in the last bit of a float, and +the oracle's output must not change (`docs/performance.md`). `cut_tests` draws a set of +scenes cut and whole at five zooms and fourteen tile positions each and compares the float +pixmaps for equality. The GPU stage starts from the same prepared fills (ADR 0019), so it +bins fewer edges too; its parity tests are unchanged. + +What is left is linear in the path per tile (transforming each segment and testing its hull), +about a tenth of the old cost at deep zoom. A spatial index over a path's segments would make +it follow the visible part alone; not yet. + +## Consequences + +* Editing, zooming or playing for a long time holds what a short session holds: a drag of 300 + moves ends with two views of pictures instead of the whole budget; the web build's memory + stops growing after the first moves of a drag (measured in Node, `tests/wasm.rs`). +* A tile deep inside a large drawing walks fewer edges than the whole drawing has at 100 %. +* Undo further back than one step redraws the view (it was a cache hit while the budget + lasted). +* A zoom gesture shows the old pictures scaled until it rests; it used to show the same on + the desktop (the answers came too late) and to stutter in the browser. +* `FrameJob` and `FrameImage` have a `set` field; `RenderService` gains `show`, `has_thread`, + `without_thread` and `request_batch_within`. + +## Tests (relations, not timings) + +* `render::cut_tests`: cut and whole pictures are equal bit for bit, masks too; a tile deep in + a drawing walks fewer edges than the stage at 100 %, where whole it walked more with every + zoom. +* `engine::render_budget_tests`: a drag of 120 states holds what it held after 10, and so + does a zoom of 80 levels; four laps of a movie hold what one lap held, with a budget above + and below the movie's size; urgent pictures come within one look-ahead pass; without a + thread a view fills in one picture a call and matches the oracle; the deepest zoom walks + fewer edges than 100 % through the stage's own tiles. +* `stage_budget_tests` (the shell, frame by frame): a zoom gesture asks for nothing until it + rests and then holds one view of textures; 40 edits hold what 5 held. +* `tests/wasm.rs` (in Node): the WebAssembly memory after 132 moves of a drag is what it was + after 12. diff --git a/docs/architecture.md b/docs/architecture.md index cb401883..8a30e8c7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -240,7 +240,9 @@ engine itself never depends on the GPU. state makes the document clean. See [ADR 0001](adr/0001-undo-persistent-snapshots.md). * `RenderService` renders frames on a worker thread with an LRU frame cache keyed by `(state, frame, view)`, and prefetches during playback. See - [ADR 0002](adr/0002-render-pipeline.md). + [ADR 0002](adr/0002-render-pipeline.md). The cache keeps the pictures of the document state + and zoom on screen and of the one before, within its byte budgets, and draws what the + screen needs before look-ahead ([ADR 0132](adr/0132-memory-and-frame-time-stay-flat.md)). * `CommandSpec { id, label, menu, shortcut, params, run }`. `run(&mut Session, &Value) -> Result`. The registry (`commands()`) is the single list the shell, CLI and agents read. `Session::execute(id, params)` handles undo snapshots for mutating commands. @@ -293,7 +295,9 @@ another language. The stage is drawn in tiles by the engine's `RenderService`: on the graphics card by default (section 4, "GPU stage"), and by the CPU renderer when there is no usable card, in the web -build, and for anything the GPU can't draw. Tiles are cached per `(state, frame, view)`. +build, and for anything the GPU can't draw. Tiles are cached per `(state, frame, view)`; a +zoom that is still changing scales the tiles on screen and draws new ones when it rests +([ADR 0132](adr/0132-memory-and-frame-time-stay-flat.md)). Overlays (selection boxes, drag previews, the stage frame) are drawn with the egui painter in screen space. diff --git a/docs/roadmap.md b/docs/roadmap.md index 352eb1a7..2c61edd0 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -46,7 +46,7 @@ the changelog. | P-001 | AniCraft starts on every supported machine: the launch failures on Windows and Linux graphics drivers ([#164](https://github.com/storytold/anicraft/issues/164), [#158](https://github.com/storytold/anicraft/issues/158), [#207](https://github.com/storytold/anicraft/issues/207), [#268](https://github.com/storytold/anicraft/issues/268), [#421](https://github.com/storytold/anicraft/issues/421), [#342](https://github.com/storytold/anicraft/issues/342); duplicates [#488](https://github.com/storytold/anicraft/issues/488), [#448](https://github.com/storytold/anicraft/issues/448), [#412](https://github.com/storytold/anicraft/issues/412), [#313](https://github.com/storytold/anicraft/issues/313), [#286](https://github.com/storytold/anicraft/issues/286), [#285](https://github.com/storytold/anicraft/issues/285)) each end in a window or a message that says what to do | Preferences, platforms | M | reports' logs | platform | | P-002 | Nested symbols can't exhaust memory or hang: a work budget on evaluation and bounds (outside PR [#13](https://github.com/storytold/anicraft/issues/13)) | Symbols | S | | doc | | P-003 | What is left of "a long Brush stroke never freezes the app" ([#519](https://github.com/storytold/anicraft/issues/519)) after [ADR 0129](adr/0129-a-long-brush-stroke-never-holds-the-window.md) bounded the trace, took it off the window's thread and fixed the selection overlay: on one raw shape of ten thousand points and more, the Subselection tool's click (seconds, once), the Paint Bucket in a gap (about a second) and the shape tools' snapping (slow frames); and the merge of such a shape (75 to 220 ms) still runs on the window's thread | Tools | S each | | stage | -| P-004 | Memory and frame time stay flat: 900 MB for a 24-frame move in the web build ([#314](https://github.com/storytold/anicraft/issues/314)), stutter when zoomed in ([#477](https://github.com/storytold/anicraft/issues/477)); a budget test for each | Workspace | M | | render | +| P-004 | Memory and frame time stay flat, what is left ([ADR 0132](adr/0132-memory-and-frame-time-stay-flat.md) did the picture cache, zoom gestures, look-ahead order and off-tile edges for [#314](https://github.com/storytold/anicraft/issues/314) and [#477](https://github.com/storytold/anicraft/issues/477), each with a budget test): in the web build a drag still redraws the whole view on every pointer move (key tiles by what they show, so only the tiles the dragged thing touches are drawn again); a tile's preparation still visits every segment of a path it touches (a spatial index); deep-zoom timings of the GPU stage on more graphics cards | Workspace | M | | render | | P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), which did not reproduce on Windows 10 (the curved pointer shows outside a corner in the real window; the headless press-and-drag tests pass) and needs the reporter's build number and steps. Done: handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117), tested end to end), and [#193](https://github.com/storytold/anicraft/issues/193) decided by [ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md) with the rule in the guide | Tools | S | the reporter's answer | stage | | P-006 | Animate files open right: lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)), a `.fla` refused on macOS ([#347](https://github.com/storytold/anicraft/issues/347)); each fixed file joins the corpus | Import | M | the reporters' files | xfl | | P-007 | The web build is usable: import, export and save ([#55](https://github.com/storytold/anicraft/issues/55)), preferences kept ([#56](https://github.com/storytold/anicraft/issues/56)), a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210)), a run in a real browser in CI | Preferences, platforms | M | | platform | diff --git a/src/main.rs b/src/main.rs index 119d22a5..76b284f6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -529,3 +529,5 @@ mod long_stroke_tests; mod ink; #[cfg(test)] mod zoom_tests; +#[cfg(test)] +mod stage_budget_tests; diff --git a/src/stage.rs b/src/stage.rs index 0a8d079c..fd72a699 100644 --- a/src/stage.rs +++ b/src/stage.rs @@ -5,6 +5,13 @@ //! frame asks for the visible tiles as one batch (plus a one-tile margin as look-ahead), keeps //! finished tiles as textures, and draws any older tiles that cover a gap (previous zoom or //! state, scaled) underneath, so panning and zooming never reveal an empty stage. +//! +//! Memory and frame time stay flat (ADR 0132). The pictures of a document state and zoom that +//! are no longer on screen go as soon as the view is drawn again, here and in the render +//! service. While the zoom is changing (a pinch, Ctrl+wheel) nothing new is drawn: every frame +//! of it is a zoom level nobody will look at, so the pictures on screen are scaled until the +//! zoom rests. With no render thread (the browser) moving around the stage draws for at most +//! `INLINE_BUDGET` of a frame. use crate::app::{App, Drag, Tool, XfKind}; use crate::prefs::RenderMode; @@ -27,10 +34,15 @@ const IMMEDIATE_BUDGET_MS: f32 = 12.0; pub const TILE: u32 = 512; /// Tile textures kept on the GPU (≈ 1 MB each); least recently used ones are dropped. const MAX_TILE_TEXTURES: usize = 192; +/// With no render thread (the browser): the most of one frame spent drawing tiles while +/// moving around the stage. The rest of the view arrives over the next frames. +const INLINE_BUDGET: std::time::Duration = std::time::Duration::from_millis(8); /// A finished tile on the GPU. struct TileTex { key: u64, + /// The picture set it is of (a document state at a zoom, ADR 0132). + set: u64, /// Stage-space rectangle `[x0, y0, x1, y1]` this tile covers. rect: [f32; 4], tex: TileImage, @@ -65,6 +77,11 @@ pub struct Cache { pub service: Option, /// Document state of the picture on screen (an edit makes it differ). pub shown_state: Option, + /// Movie frame of the picture on screen (playing or scrubbing makes it differ). + shown_frame: Option, + /// The device scale the stage was laid out at last frame: while it differs from this + /// frame's the zoom is still changing, and no tiles are asked for. + last_scale: Option, /// The GPU stage (ADR 0019), when this build has it and Preferences ask for it. pub gpu: crate::gpu_stage::GpuStage, /// Who drew the newest visible tiles: the GPU, or the CPU and why (status bar). @@ -75,7 +92,7 @@ pub struct Cache { impl Default for Cache { fn default() -> Self { - Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), laid_out: false, service: None, shown_state: None, gpu: Default::default(), drawn_by: None, pattern: None } + Cache { tiles: Vec::new(), tick: 0, ms: 0.0, ready: (0, 0), canvas: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)), laid_out: false, service: None, shown_state: None, shown_frame: None, last_scale: None, gpu: Default::default(), drawn_by: None, pattern: None } } } @@ -95,6 +112,8 @@ impl Cache { pub fn forget_document(&mut self) { self.tiles.clear(); self.shown_state = None; + self.shown_frame = None; + self.last_scale = None; self.ready = (0, 0); if let Some(s) = &self.service { s.forget_pictures(); @@ -139,7 +158,7 @@ impl Cache { } }; self.tick += 1; - self.tiles.push(TileTex { key: img.key, rect, tex, used: self.tick }); + self.tiles.push(TileTex { key: img.key, set: img.set, rect, tex, used: self.tick }); // Evict least recently used tiles that are not on screen. while self.tiles.len() > MAX_TILE_TEXTURES { let victim = self.tiles.iter().enumerate().filter(|(_, t)| !keep.contains(&t.key)).min_by_key(|(_, t)| t.used).map(|(i, _)| i); @@ -1051,8 +1070,24 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { let jobs: Vec<(TileSpec, FrameJob)> = visible.into_iter().map(|t| { let j = make_job_for(raster, state, &pic.doc, pic.frame, t.view, onion).through_camera(preview).inside(pic.front.clone()).with_reference(reference.clone()); (t, j) }).collect(); let keys: Vec = jobs.iter().map(|(_, j)| j.key).collect(); let missing: Vec = (0..jobs.len()).filter(|&i| !app.stage_cache.has(keys[i])).collect(); + let set = jobs.first().map(|(_, j)| j.set); + // A zoom that is still changing draws nothing new: this frame's zoom level is gone by + // the next, so its tiles would never be looked at (and in the browser they would be + // drawn inside this frame). The pictures on screen are scaled until the zoom rests, + // one frame from now at the soonest. + let zooming = app.stage_cache.last_scale.is_some_and(|was| was != z); + app.stage_cache.last_scale = Some(z); + if zooming { + ui.ctx().request_repaint(); + } else if let (Some(set), Some(svc)) = (set, &app.stage_cache.service) { + // The picture set on screen (this state at this zoom): the render service keeps it + // and the one before, and lets the pictures of every other go (ADR 0132). A zoom + // level passed through on the way is not one of them. + svc.show(set); + } if !missing.is_empty() + && !zooming && let Some(svc) = &app.stage_cache.service { // Latency vs throughput (ADR 0006): an edit (the document changed under the picture @@ -1069,8 +1104,18 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { RenderMode::Auto => app.stage_cache.ms <= IMMEDIATE_BUDGET_MS, }; let batch: Vec = missing.iter().map(|&i| jobs[i].1.clone()).collect(); + // Moving around the picture already on screen (a pan, a zoom come to rest): with + // no render thread the tiles come a few a frame, nearest the centre first, so the + // frame stays short. An edit or another frame is one whole picture, drawn at once. + let moving = app.stage_cache.shown_state == Some(state) && app.stage_cache.shown_frame == Some(pic.frame); let started = web_time::Instant::now(); - let results: Vec>> = if immediate { svc.render_now_batch(batch).into_iter().map(Some).collect() } else { svc.request_batch(batch) }; + let results: Vec>> = if immediate { + svc.render_now_batch(batch).into_iter().map(Some).collect() + } else if moving { + svc.request_batch_within(batch, INLINE_BUDGET) + } else { + svc.request_batch(batch) + }; let wall = started.elapsed().as_secs_f32() * 1000.0; let mut ms = 0.0f32; let mut error = None; @@ -1103,11 +1148,20 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) { app.stage_cache.ready = (ready, keys.len()); if ready == keys.len() { app.stage_cache.shown_state = Some(state); + app.stage_cache.shown_frame = Some(pic.frame); + // The view is whole: tiles of other states and zooms were only standing in for + // it, so their textures go now instead of when 192 newer ones have pushed them out. + if let Some(set) = set { + app.stage_cache.tiles.retain(|t| t.set == set); + } + } else if !zooming && app.stage_cache.service.as_ref().is_some_and(|s| !s.has_thread()) { + // No render thread tells us when the rest is ready: it is drawn next frame. + ui.ctx().request_repaint(); } // Look-ahead: the ring of tiles around the view (a pan reveals them instantly) and, // during playback, the next frames' visible tiles. - if let Some(svc) = &app.stage_cache.service { + if let Some(svc) = app.stage_cache.service.as_ref().filter(|_| !zooming) { let mut ahead: Vec = Vec::new(); if app.playing && !editing { let n = app.s.frame_count().max(1); diff --git a/src/stage_budget_tests.rs b/src/stage_budget_tests.rs new file mode 100644 index 00000000..717ac897 --- /dev/null +++ b/src/stage_budget_tests.rs @@ -0,0 +1,165 @@ +//! The stage keeps memory and frame time flat (P-004, ADR 0132; #314, #477), driven frame by +//! frame through the real app: a zoom gesture draws nothing until it rests, and editing or +//! zooming for a long time holds no more pictures than the view on screen needs. +//! `stage_memory_and_frame_times` prints the numbers. + +use crate::app::App; +use egui::{Event, Pos2, Rect, vec2}; +use serde_json::json; + +fn frame(ctx: &egui::Context, app: &mut App, time: f64, events: Vec) -> f64 { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(time), events, ..Default::default() }; + let t = std::time::Instant::now(); + ctx.run_ui(input, |ui| app.frame(ui)).textures_delta.clear(); + t.elapsed().as_secs_f64() * 1000.0 +} + +/// The app showing the sample, the pointer over the stage, the view drawn. +fn sample_app(ctx: &egui::Context) -> (App, f64) { + let session = anicraft_engine::Session::new(anicraft_engine::doc::sample::demo()); + let mut app = App::with_context(ctx, session, Some(std::path::PathBuf::from("unused.png"))); + let mut t = 0.0; + for _ in 0..3 { + t += 0.016; + frame(ctx, &mut app, t, vec![]); + } + let at = app.stage_cache.canvas.center(); + frame(ctx, &mut app, t, vec![Event::PointerMoved(at)]); + assert!(drawn(ctx, &mut app, &mut t), "the first view was drawn"); + (app, t) +} + +/// Frames until every tile of the view is on screen and the render thread has nothing left to +/// draw (the look-ahead ring around the view too); whether that happened. +fn drawn(ctx: &egui::Context, app: &mut App, t: &mut f64) -> bool { + for _ in 0..30_000 { + *t += 0.016; + frame(ctx, app, *t, vec![]); + let (ready, needed) = app.stage_cache.ready; + if needed > 0 && ready == needed && app.stage_cache.service.as_ref().is_some_and(|s| !s.busy()) { + return true; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + false +} + +/// `(pictures, bytes, pictures asked for and not found)` of the render service's cache. +fn cache(app: &App) -> (usize, usize, u64) { + let (n, bytes, _, misses) = app.stage_cache.service.as_ref().map(|s| s.cache_stats()).unwrap_or_default(); + (n, bytes, misses) +} + +/// #477: every frame of a Ctrl+wheel or pinch zoom is a zoom level of its own. Each one's +/// tiles used to be asked for, drawn (in the browser, inside the frame) and kept, though the +/// next frame no longer wanted them. Now nothing is asked for until the zoom rests; then the +/// view is drawn once and the stand-in tiles of the old zoom go. +#[test] +fn a_zoom_gesture_draws_nothing_until_it_rests() { + let ctx = egui::Context::default(); + let (mut app, mut t) = sample_app(&ctx); + let (zoom, before) = (app.view.zoom, cache(&app)); + for _ in 0..40 { + t += 0.016; + frame(&ctx, &mut app, t, vec![Event::Zoom(1.05)]); + assert!(app.stage_cache.tile_count() > 0, "the pictures of the old zoom stand in"); + } + assert!(app.view.zoom > zoom * 4.0, "the view zoomed in: {} to {}", zoom, app.view.zoom); + assert_eq!(cache(&app), before, "nothing was asked for or drawn while the zoom was changing"); + // At rest: drawn, and only this view's tiles are held. + assert!(drawn(&ctx, &mut app, &mut t)); + let needed = app.stage_cache.ready.1; + assert!(cache(&app).2 > before.2, "the view at the new zoom was asked for"); + assert_eq!(app.stage_cache.tile_count(), needed, "the old zoom's textures are gone"); +} + +/// #314: a long drag is hundreds of document states. The textures and cached pictures after +/// many moves are what they were after a few: the view on screen and the state before it. +#[test] +fn editing_for_long_holds_no_more_pictures_than_editing_briefly() { + let ctx = egui::Context::default(); + let (mut app, mut t) = sample_app(&ctx); + app.run("edit.select_all", json!({})); + let mut held = Vec::new(); + for step in 0..40 { + assert!(app.run("element.translate", json!({"dx": 3, "dy": if step % 2 == 0 { 2 } else { -2 }})).is_some()); + assert!(drawn(&ctx, &mut app, &mut t), "move {step} was drawn"); + let needed = app.stage_cache.ready.1; + assert_eq!(app.stage_cache.tile_count(), needed, "move {step}: one view of textures"); + held.push(cache(&app).1); + } + // The view and the ring around it, for this state and the one before: reached after two + // moves, and never more however many follow. + let (early, late) = (held.iter().take(5).max(), held.iter().skip(5).max()); + assert!(late <= early, "the cache held {early:?} bytes within 5 moves and {late:?} after 40"); +} + +/// This process's memory in use (MB), where the system says (Windows, Linux). +fn resident_mb() -> Option { + let pid = std::process::id(); + if cfg!(windows) { + let out = std::process::Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/FO", "CSV", "/NH"]).output().ok()?; + let text = String::from_utf8_lossy(&out.stdout).to_string(); + let kb: String = text.trim().rsplit('"').nth(1)?.chars().filter(char::is_ascii_digit).collect(); + Some(kb.parse::().ok()? / 1024.0) + } else { + let text = std::fs::read_to_string("/proc/self/statm").ok()?; + Some(text.split_whitespace().nth(1)?.parse::().ok()? * 4096.0 / 1048576.0) + } +} + +/// Memory and frame times over a long session, on the CPU stage: +/// `cargo test --release --bin anicraft stage_memory_and_frame_times -- --ignored --nocapture`. +#[test] +#[ignore = "a measurement, not a check"] +fn stage_memory_and_frame_times() { + let ctx = egui::Context::default(); + let (mut app, mut t) = sample_app(&ctx); + let report = |what: &str, app: &App, ms: f64, worst: f64| { + let (n, bytes, _) = cache(app); + println!("{what:<34} {ms:>6.2} ms a frame (worst {worst:>6.2}) cache {n:>4} pictures {:>7.1} MB textures {:>3} process {:>7.1} MB", bytes as f64 / 1048576.0, app.stage_cache.tile_count(), resident_mb().unwrap_or(0.0)); + }; + report("at rest", &app, 0.0, 0.0); + // A drag of 300 pointer moves. + app.run("edit.select_all", json!({})); + let (mut sum, mut worst) = (0.0f64, 0.0f64); + for step in 0..300 { + app.run("element.translate", json!({"dx": if step % 2 == 0 { 2 } else { -2 }, "dy": 0})); + t += 0.016; + let ms = frame(&ctx, &mut app, t, vec![]); + sum += ms; + worst = worst.max(ms); + } + report("a drag of 300 moves", &app, sum / 300.0, worst); + // Playing the movie five times over. + app.run("edit.deselect", json!({})); + let frames = app.s.frame_count().max(1); + let (mut sum, mut worst, mut n) = (0.0f64, 0.0f64, 0u32); + for lap in 0..5 { + for f in 0..frames { + app.s.set_frame(f); + t += 0.016; + let ms = frame(&ctx, &mut app, t, vec![]); + if lap == 0 { + drawn(&ctx, &mut app, &mut t); + } else { + sum += ms; + worst = worst.max(ms); + n += 1; + } + } + report(&format!("played {} frames, lap {}", frames, lap + 1), &app, sum / f64::from(n.max(1)), worst); + } + // Zooming in to the limit, a notch a frame, resting every 12 frames. + while app.view.zoom < 63.0 { + let (mut sum, mut worst) = (0.0f64, 0.0f64); + for _ in 0..12 { + t += 0.016; + let ms = frame(&ctx, &mut app, t, vec![Event::Zoom(1.06)]); + sum += ms; + worst = worst.max(ms); + } + drawn(&ctx, &mut app, &mut t); + report(&format!("zoomed to {:.0} %", app.view.zoom * 100.0), &app, sum / 12.0, worst); + } +}