diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e5f987c71d0..e2c96625099 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -174,6 +174,7 @@ impl PhotocraftApp { perf: Default::default(), stroke_trace: stroke_trace::StrokeTrace::from_env(), render_path: Default::default(), + slow_frames: Default::default(), prefs_rt: Default::default(), updates_rt: Default::default(), discard: None, @@ -256,11 +257,9 @@ impl eframe::App for PhotocraftApp { if self.custom_titlebar { titlebar::release_after_os_resize(ctx, raw_input); } - if self.stroke_trace.enabled() { - // The OS's moves and the control channel's (injected just above). - let moves = raw_input.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(); - self.stroke_trace.begin_frame(frame_start, moves); - } + // The OS's moves and the control channel's (injected just above). + let moves = raw_input.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(); + self.perf.stage.start(frame_start, moves); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 9e7e986d695..8c99167b4c5 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -121,6 +121,7 @@ impl PhotocraftApp { self.sync_command_side_effects(id, &r, creates_active_mask, creates_active_vector_mask, creates_adjustment_or_fill, path_mask); self.perf.last_command = id.to_string(); self.perf.command_ms = gpu_canvas::now_ms() - t0; + self.perf.stage.command(id, self.perf.command_ms); match &r { Ok(_) => { if self.ui.status_error { diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 425742d5199..1032873c567 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -1,4 +1,4 @@ -use super::{ControlRequest, PhotocraftApp, Receiver}; +use super::{ControlRequest, PhotocraftApp, Receiver, gpu_canvas}; impl PhotocraftApp { /// Attach a control channel (requests arrive from a transport thread: TCP, stdin, tests). @@ -7,6 +7,19 @@ impl PhotocraftApp { self } + /// Close this frame's stage record (`frame_stages`): keep it if it was slow, and hand it to + /// the stroke trace. `ui_ms` is the UI build's time. + pub(crate) fn finish_frame(&mut self, ui_ms: f64) { + let mut stages = std::mem::take(&mut self.perf.stage); + stages.ui_ms = ui_ms; + let stages = self.slow_frames.finish(stages, gpu_canvas::now_ms(), self.perf.gpu, self.perf.gpu_ms); + let info = &self.perf.gpu_info; + self.stroke_trace.frame(&stages, self.live_stroke.is_some(), || { + let gpu = format!("{} {}", info.backend, info.adapter).trim().to_string(); + if info.present.is_empty() { gpu } else { format!("{gpu}, {}", info.present) } + }); + } + pub(crate) fn drain_control(&mut self, ctx: &egui::Context) { let Some(rx) = self.control_rx.take() else { return }; while let Ok(req) = rx.try_recv() { diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index d19eb31f7ac..d7b5a688c56 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -170,10 +170,9 @@ impl PhotocraftApp { return; } let t0 = gpu_canvas::now_ms(); - self.perf.frame_refresh_ms = 0.0; + self.perf.stage.ui_start(t0, frame.info().cpu_usage); // A software adapter or CPU mode chosen at startup is every document's reason. crate::render_path::frame(self); - self.stroke_trace.cpu_prev(frame.info().cpu_usage); // A text field's right-click menu, before any field is drawn (text_field_menu.rs). text_field_menu::show(&ctx); // The wheel goes to a focused value field before the canvas or a panel sees it (#5473). @@ -313,14 +312,7 @@ impl PhotocraftApp { self.perf.record_gpu(t); } self.perf.frame(ui_ms); - if self.stroke_trace.enabled() { - self.stroke_trace.canvas(self.perf.frame_refresh_ms); - let info = &self.perf.gpu_info; - self.stroke_trace.end_frame(ui_ms, self.live_stroke.is_some(), || { - let gpu = format!("{} {}", info.backend, info.adapter).trim().to_string(); - if info.present.is_empty() { gpu } else { format!("{gpu}, {}", info.present) } - }); - } + self.finish_frame(ui_ms); // This pass handled its input: the in-flight synthetic batch is delivered once and the // next step may be injected on the next frame. self.finish_synthetic_pass(); diff --git a/crates/ui-egui/src/canvas/gpu_canvas/perf.rs b/crates/ui-egui/src/canvas/gpu_canvas/perf.rs index b1fedc6a62d..58b12774b29 100644 --- a/crates/ui-egui/src/canvas/gpu_canvas/perf.rs +++ b/crates/ui-egui/src/canvas/gpu_canvas/perf.rs @@ -68,9 +68,9 @@ pub struct Perf { pub spans: std::collections::BTreeMap<&'static str, f64>, #[serde(skip)] max_decay: f64, - /// Composite and upload time of this frame's canvas refreshes, in ms (the stroke trace). + /// This frame's stages, gathered as it runs (see `frame_stages`). #[serde(skip)] - pub(crate) frame_refresh_ms: f64, + pub(crate) stage: crate::frame_stages::FrameStages, } /// What the app renders with and why (Help › System Info, Preferences › Performance, the `perf` @@ -214,7 +214,7 @@ pub fn backend_name(b: wgpu::Backend) -> &'static str { impl Perf { pub fn record(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) { - self.frame_refresh_ms += composite_ms + upload_ms; + self.stage.refresh(kind, px, composite_ms, upload_ms); self.last_refresh = kind; self.last_refresh_px = px; self.composite_ms = composite_ms; diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 11a288eb6ae..15aa741a829 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -406,7 +406,7 @@ pub(super) fn feed_live_stroke(app: &mut PhotocraftApp) { } } } - app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); + app.perf.stage.stroke_ms += crate::gpu_canvas::now_ms() - started; } /// The points the live retouching stroke has rendered. @@ -603,7 +603,7 @@ pub(super) fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) { } let started = crate::gpu_canvas::now_ms(); let result = app.run(stroke_command(app, d.tool), p); - app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started); + app.perf.stage.stroke_ms += crate::gpu_canvas::now_ms() - started; app.session.clear_live_stroke(); let Ok(r) = result else { return }; let after = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| (st.revision, st.doc.clone())); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index f213a67d9de..1114bee6898 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -175,15 +175,15 @@ fn inline_filter_preview_is_composited_and_recorded_once() { app.background_jobs = false; app.run("file.new", json!({"width": 320, "height": 240})).unwrap(); crate::filter_dialog::open(&mut app, "filter.stylize.solarize").unwrap(); - app.perf.frame_refresh_ms = 0.0; + app.perf.stage = Default::default(); let (_, _, size) = ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("a preview"); assert_eq!(size, [320, 240]); assert_eq!(app.perf.last_refresh, "filter-preview"); assert_eq!(app.perf.last_refresh_px, 320 * 240); - assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms, "one record per preview"); + assert_eq!(app.perf.stage.composite_ms + app.perf.stage.upload_ms, app.perf.composite_ms + app.perf.upload_ms, "one record per preview"); // Unchanged request: nothing is recomputed or recorded again. ensure_filter_preview(&mut app, 0, &egui::Context::default()).expect("the same preview"); - assert_eq!(app.perf.frame_refresh_ms, app.perf.composite_ms + app.perf.upload_ms); + assert_eq!(app.perf.stage.composite_ms + app.perf.stage.upload_ms, app.perf.composite_ms + app.perf.upload_ms); } /// #6326: a filter's live preview is never coarser than the screen. On a document big enough diff --git a/crates/ui-egui/src/canvas/textures.rs b/crates/ui-egui/src/canvas/textures.rs index 99f9e770968..f11c4338e9d 100644 --- a/crates/ui-egui/src/canvas/textures.rs +++ b/crates/ui-egui/src/canvas/textures.rs @@ -466,10 +466,12 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz // The texture is shared by every display: only what it stores counts, not the monitor. let display_key = texture_key(display.as_deref()); let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key)); + let damage_start = crate::gpu_canvas::now_ms(); let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage)); if let Some(region) = damage { damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, blend_visible)); } + app.perf.stage.damage_ms += crate::gpu_canvas::now_ms() - damage_start; // To an adjustment dialog's preview: only what the view shows now (the rest as it moves there). if damage.is_some() && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::switch_region(app, id, revision, s.1 ^ display_key, raw_key)) @@ -551,7 +553,9 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz return false; } let partial = present && damage.is_some(); + let budget_start = crate::gpu_canvas::now_ms(); gpu_budget(app, &gpu, idx, partial, visible); + app.perf.stage.damage_ms += crate::gpu_canvas::now_ms() - budget_start; let defer = crate::background_redraw::enabled(app); let r = gpu.refresh_with(id.0, &doc, if partial { damage } else { None }, display.as_deref(), defer); app.perf.gpu_layer_fit = gpu.layer_fit(); diff --git a/crates/ui-egui/src/frame_stages.rs b/crates/ui-egui/src/frame_stages.rs new file mode 100644 index 00000000000..c2b4fc5fb9a --- /dev/null +++ b/crates/ui-egui/src/frame_stages.rs @@ -0,0 +1,323 @@ +//! Where each frame's time goes (#9328), gathered every frame, and the slow ones kept. +//! +//! [`FrameStages`] is one frame's record. Each stage has one writer: the raw input hook starts +//! the frame, `App::run` adds commands, the GPU canvas path adds damage tracking and budgeting, +//! [`crate::gpu_canvas::Perf::record`] adds composites and uploads, and the canvas adds stroke +//! rendering. `App::ui` closes it ([`SlowFrames::finish`]). A frame over [`SLOW_FRAME_MS`] goes +//! into [`SlowFrames`], the last [`SLOW_FRAMES`] of them, which the control channel's `perf` +//! output lists as `slowFrames`; one `info` log line per second names them. The stroke trace +//! (`stroke_trace`) reads the same record, so the app times a frame in one place. +//! +//! On the web `now_ms()` is 0, so no frame is ever slow and the ring stays empty. + +use std::collections::VecDeque; + +/// A frame slower than this (ms) is kept and logged. +pub const SLOW_FRAME_MS: f64 = 50.0; +/// How many slow frames are kept. +pub const SLOW_FRAMES: usize = 64; +/// At most one slow-frame log line per this many ms. +const LOG_EVERY_MS: f64 = 1000.0; + +/// One frame's stages. Times in ms. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FrameStages { + /// Frame start (the raw input hook), from [`crate::gpu_canvas::now_ms`]. + pub t: f64, + /// The whole frame: from its start until its UI is built. Never less than the stages below + /// (a command run between frames counts toward the next one). + pub frame_ms: f64, + /// From the raw input hook to the start of the UI build (input handling, minus commands). + pub input_ms: f64, + /// Commands run through the app since the previous frame ended. + pub command_ms: f64, + /// The last of those commands ("" for none). + pub command: String, + /// Damage tracking and GPU memory budgeting on the GPU canvas path. + pub damage_ms: f64, + /// Canvas composites, CPU side (on the GPU path: encoding and submitting them). + pub composite_ms: f64, + /// Canvas conversions and uploads. + pub upload_ms: f64, + /// The GPU's own time for a recent composite, when the canvas is on the GPU and it reports one. + pub gpu_ms: Option, + /// eframe's CPU time for the previous frame minus that frame's UI build: tessellation and + /// GPU submission (the previous frame's, so it isn't part of `frame_ms`). + pub present_ms: Option, + /// The last canvas refresh's kind ("full", "rect", "gpu-full", …; "" for none). + pub refresh: &'static str, + /// Pixels the frame's canvas refreshes covered. + pub refresh_px: u64, + /// "gpu" or "cpu": who drew the canvas. + pub path: &'static str, + /// Building the UI (`App::ui`), the canvas refresh included. + #[serde(skip)] + pub ui_ms: f64, + /// Rendering stroke points (the stroke trace's `stroke`). + #[serde(skip)] + pub stroke_ms: f64, + /// Pointer moves the frame delivered. + #[serde(skip)] + pub moves: usize, + /// eframe's CPU time for the previous frame. + #[serde(skip)] + pub cpu_prev_ms: Option, + /// The raw input hook ran for this frame. + #[serde(skip)] + started: bool, +} + +impl FrameStages { + /// The raw input hook: the frame starts at `now` with `moves` pointer moves. + pub fn start(&mut self, now: f64, moves: usize) { + self.t = now; + self.moves = moves; + self.started = true; + } + + /// The UI build starts at `now`; `cpu_prev` is eframe's CPU time for the previous frame, in s. + pub fn ui_start(&mut self, now: f64, cpu_prev: Option) { + if !self.started { + self.start(now, 0); + } + self.input_ms = (now - self.t - self.command_ms).max(0.0); + self.cpu_prev_ms = cpu_prev.map(|s| f64::from(s) * 1000.0); + } + + /// A command `id` ran for `ms`. + pub fn command(&mut self, id: &str, ms: f64) { + self.command_ms += ms; + id.clone_into(&mut self.command); + } + + /// A canvas refresh of kind `kind` and `px` pixels. + pub fn refresh(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) { + self.composite_ms += composite_ms; + self.upload_ms += upload_ms; + self.refresh = kind; + self.refresh_px += px; + } + + /// The stages that make up `frame_ms` (`present_ms` belongs to the previous frame). + pub fn stage_ms(&self) -> f64 { + self.input_ms + self.command_ms + self.damage_ms + self.composite_ms + self.upload_ms + } + + /// The frame ends at `now`. + fn end(&mut self, now: f64) { + if !self.started { + self.t = now; + } + self.frame_ms = (now - self.t).max(self.stage_ms()); + } + + /// One line for the log. + pub fn line(&self) -> String { + let opt = |v: Option| v.map_or("-".to_string(), |v| format!("{v:.1}")); + let command = if self.command.is_empty() { String::new() } else { format!(" ({})", self.command) }; + format!( + "slow frame: {:.1} ms on the {} path: input {:.1}, command {:.1}{command}, damage {:.1}, composite {:.1}, upload {:.1}, gpu {}, present {}; refresh {} {} px", + self.frame_ms, + self.path, + self.input_ms, + self.command_ms, + self.damage_ms, + self.composite_ms, + self.upload_ms, + opt(self.gpu_ms), + opt(self.present_ms), + if self.refresh.is_empty() { "none" } else { self.refresh }, + self.refresh_px, + ) + } +} + +/// The last [`SLOW_FRAMES`] frames over the threshold. +#[derive(Debug)] +pub struct SlowFrames { + frames: VecDeque, + threshold_ms: f64, + /// The previous frame's UI build (for its `present_ms`). + prev_ui_ms: Option, + /// When the last log line went out, and the slow frames since that weren't logged. + logged_at: Option, + unlogged: usize, +} + +impl Default for SlowFrames { + fn default() -> Self { + Self { frames: VecDeque::with_capacity(SLOW_FRAMES), threshold_ms: SLOW_FRAME_MS, prev_ui_ms: None, logged_at: None, unlogged: 0 } + } +} + +impl SlowFrames { + /// The kept frames, oldest first. + pub fn frames(&self) -> impl DoubleEndedIterator { + self.frames.iter() + } + + /// Keep frames slower than `ms` instead of [`SLOW_FRAME_MS`] (tests). + #[cfg(test)] + pub(crate) fn set_threshold_ms(&mut self, ms: f64) { + self.threshold_ms = ms; + } + + /// Close frame `s` at `now`: `gpu` says the canvas is on the GPU, `gpu_ms` is the GPU's + /// latest composite time. A slow frame is kept, and logged at most once a second. + pub fn finish(&mut self, mut s: FrameStages, now: f64, gpu: bool, gpu_ms: Option) -> FrameStages { + s.end(now); + let on_gpu = if s.refresh.is_empty() { gpu } else { s.refresh.starts_with("gpu") }; + s.path = if on_gpu { "gpu" } else { "cpu" }; + s.gpu_ms = gpu_ms.filter(|_| on_gpu); + s.present_ms = s.cpu_prev_ms.zip(self.prev_ui_ms).map(|(cpu, ui)| (cpu - ui).max(0.0)); + self.prev_ui_ms = Some(s.ui_ms); + if let Some(line) = self.push(&s) { + log::info!("{line}"); + } + s + } + + /// Keep `s` if it's slow; the log line to write, if one is due. + fn push(&mut self, s: &FrameStages) -> Option { + if s.frame_ms.is_nan() || s.frame_ms <= self.threshold_ms { + return None; + } + if self.frames.len() == SLOW_FRAMES { + self.frames.pop_front(); + } + self.frames.push_back(s.clone()); + if self.logged_at.is_some_and(|at| s.t - at < LOG_EVERY_MS) { + self.unlogged += 1; + return None; + } + let mut line = s.line(); + if self.unlogged > 0 { + line.push_str(&format!(" ({} more slow frames)", self.unlogged)); + } + self.logged_at = Some(s.t); + self.unlogged = 0; + Some(line) + } +} + +impl serde::Serialize for SlowFrames { + fn serialize(&self, ser: S) -> Result { + ser.collect_seq(self.frames.iter()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn frame(t: f64, ms: f64) -> FrameStages { + let mut s = FrameStages::default(); + s.start(t, 0); + s.ui_start(t + 1.0, None); + s.refresh("full", 100, ms / 2.0, 1.0); + s + } + + #[test] + fn slow_frames_keep_the_last_64_over_the_threshold() { + let mut r = SlowFrames::default(); + for k in 0..100 { + let t = f64::from(k) * 100.0; + r.finish(frame(t, 0.0), t + 60.0 + f64::from(k), false, None); + } + assert_eq!(r.frames().count(), SLOW_FRAMES); + let first = r.frames().next().unwrap(); + assert_eq!(first.t, 3600.0, "the oldest are dropped"); + assert_eq!(r.frames().last().unwrap().frame_ms, 159.0); + assert!(r.frames().all(|f| f.path == "cpu" && f.refresh_px == 100)); + let json = serde_json::to_value(&r).unwrap(); + assert_eq!(json.as_array().map(Vec::len), Some(SLOW_FRAMES)); + assert_eq!(json[0]["frameMs"], 96.0); + } + + #[test] + fn a_fast_frame_is_not_recorded() { + let mut r = SlowFrames::default(); + let s = r.finish(frame(0.0, 0.0), 49.0, true, Some(3.0)); + assert_eq!(s.frame_ms, 49.0); + assert_eq!(s.path, "cpu", "the refresh says who drew it"); + assert_eq!(s.gpu_ms, None, "no GPU time for a CPU refresh"); + r.finish(frame(100.0, 0.0), 150.0, false, None); + assert_eq!(r.frames().count(), 0, "exactly 50 ms isn't over"); + } + + #[test] + fn stages_never_exceed_the_frame() { + let mut r = SlowFrames::default(); + // A command run between frames (before the hook) makes the stages longer than the clock. + let mut s = FrameStages::default(); + s.command("layer.setProps", 80.0); + s.start(1000.0, 2); + s.ui_start(1005.0, Some(0.004)); + s.damage_ms = 2.0; + s.refresh("gpu-full", 12, 30.0, 10.0); + s.ui_ms = 40.0; + let s = r.finish(s, 1050.0, true, Some(7.0)); + assert!(s.stage_ms() <= s.frame_ms, "{s:?}"); + assert_eq!((s.input_ms, s.frame_ms, s.path, s.gpu_ms), (0.0, 122.0, "gpu", Some(7.0))); + assert_eq!(s.present_ms, None, "no previous frame"); + let mut next = frame(1100.0, 4.0); + next.cpu_prev_ms = Some(45.0); + let next = r.finish(next, 1110.0, true, None); + assert_eq!(next.present_ms, Some(5.0), "the previous frame's CPU time minus its UI build"); + assert!(next.stage_ms() <= next.frame_ms); + } + + #[test] + fn slow_frame_log_is_rate_limited() { + let mut r = SlowFrames::default(); + let lines: Vec = (0..10) + .filter_map(|k| { + let mut s = frame(f64::from(k) * 100.0, 0.0); + s.end(s.t + 60.0); + r.push(&s) + }) + .collect(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].starts_with("slow frame: 60.0 ms") && !lines[0].contains("more"), "{}", lines[0]); + let mut s = frame(1000.0, 0.0); + s.end(1070.0); + let line = r.push(&s).expect("a second later, the next line"); + assert!(line.ends_with("(9 more slow frames)"), "{line}"); + assert_eq!(r.frames().count(), 11); + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod app_tests { + use serde_json::json; + + use crate::PhotocraftApp; + + #[test] + fn an_app_frame_with_a_full_refresh_records_its_stages() { + let (w, h) = (4000u64, 3000u64); + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": w, "height": h, "background": "white"})).unwrap(); + let layer = s.active().and_then(|d| d.active_layer).expect("the background").0; + let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1440.0, 900.0)).with_max_steps(4).build_eframe(move |cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + PhotocraftApp::new(s, crate::Services::default()) + }); + harness.run_steps(6); + // Every frame counts as slow, so the test doesn't depend on the machine's speed. + harness.state_mut().slow_frames.set_threshold_ms(0.0); + harness.state_mut().run("layer.setProps", json!({"layer": layer, "visible": false})).unwrap(); + harness.step(); + let app = harness.state(); + let f = app.slow_frames.frames().rev().find(|f| f.command == "layer.setProps").expect("the toggle's frame is kept").clone(); + // The CPU canvas (kittest has no wgpu) redraws the whole document. A damage refresh counts + // reduced texels times the factor squared, which can fall a few rows short (see P80). + assert_eq!(f.path, "cpu", "{f:?}"); + assert!(matches!(f.refresh, "full" | "rect"), "{f:?}"); + assert!(f.refresh_px * 100 >= w * h * 95 && f.refresh_px <= w * h, "{f:?}"); + assert!(f.composite_ms > 0.0 && f.command_ms > 0.0, "{f:?}"); + assert!(f.stage_ms() <= f.frame_ms, "{f:?}"); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 67b54ef73e1..fdac209ca4d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -19,6 +19,7 @@ pub mod dialogs; pub mod dock; pub mod file_dialog; pub mod file_open; +pub mod frame_stages; pub mod gpu_status; pub mod i18n; mod icon_data; @@ -618,6 +619,8 @@ pub struct PhotocraftApp { pub stroke_trace: stroke_trace::StrokeTrace, /// Why each document's view is drawn on the CPU, and the history of changes (`render_path`). pub render_path: render_path::RenderPath, + /// The last slow frames and their stages (`perf.slowFrames`, see `frame_stages`). + pub slow_frames: frame_stages::SlowFrames, /// Preferences, autosave and snapping runtime state (see `prefs_ui`, `snap_ui`). pub(crate) prefs_rt: prefs_ui::Runtime, pub(crate) updates_rt: updates_ui::Runtime, diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index ac88a6c899f..ed59943faef 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -387,11 +387,10 @@ fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() { } let t0 = crate::gpu_canvas::now_ms(); let moves = ctx.input(|i| i.raw.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count()); - app.stroke_trace.begin_frame(t0, moves); - app.stroke_trace.cpu_prev(Some(0.004)); + app.perf.stage.start(t0, moves); + app.perf.stage.ui_start(t0, Some(0.004)); egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); - let stroking = app.live_stroke.is_some(); - app.stroke_trace.end_frame(crate::gpu_canvas::now_ms() - t0, stroking, || "test".into()); + app.finish_frame(crate::gpu_canvas::now_ms() - t0); }, app, ); @@ -409,7 +408,7 @@ fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() { assert!(s.frames >= 6, "{s:?}"); assert!(s.stroke[1] > 0.0 && s.ui[0] >= s.stroke[0], "{s:?}"); assert_eq!(s.moves[1], 1.0, "one move per test frame: {s:?}"); - assert_eq!(s.backend, "test"); + assert_eq!(s.backend, "", "the app's adapter (none in a test)"); } /// A Clone Stamp stroke through the canvas renders the points its commit gets (position and diff --git a/crates/ui-egui/src/tools/stroke_trace.rs b/crates/ui-egui/src/tools/stroke_trace.rs index 809414ed49a..8bbd1c887a4 100644 --- a/crates/ui-egui/src/tools/stroke_trace.rs +++ b/crates/ui-egui/src/tools/stroke_trace.rs @@ -11,9 +11,14 @@ //! submission, without the vsync wait). What the app can't see (the OS input queue before a frame //! starts, frames queued for the display, the compositor) is the rest of the input-to-photon time; //! the summary names the GPU backend because GL ignores the frame-latency setting. +//! +//! The trace keeps no clock of its own: each row is the frame's `frame_stages::FrameStages`, +//! which the app gathers every frame (the slow-frame ring reads the same record). use std::fmt::Write as _; +use crate::frame_stages::FrameStages; + /// One frame of a stroke. Times in ms. #[derive(Clone, Debug, Default, PartialEq)] pub(crate) struct Row { @@ -33,6 +38,13 @@ pub(crate) struct Row { pub cpu_prev: Option, } +impl Row { + /// The trace's row for a frame's stages. + pub(crate) fn from_stages(s: &FrameStages, interval: f64) -> Self { + Self { t: s.t, interval, moves: s.moves, stroke: s.stroke_ms, canvas: s.composite_ms + s.upload_ms, ui: s.ui_ms, cpu_prev: s.cpu_prev_ms } + } +} + /// Percentiles of a stroke's frames, for the summary line and the control channel. #[derive(Clone, Debug, Default, PartialEq, serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -86,8 +98,6 @@ pub(crate) enum Output { #[derive(Debug, Default)] pub struct StrokeTrace { pub(crate) output: Output, - /// The frame being built (started by `begin_frame`). - frame: Option, last_start: Option, /// The current stroke's frames. rows: Vec, @@ -143,49 +153,20 @@ impl StrokeTrace { self.output != Output::Off } - /// A frame starts (the raw input hook) with `moves` pointer moves. - pub fn begin_frame(&mut self, now: f64, moves: usize) { + /// A frame ended, with the stages the app gathered for it (`frame_stages`; the trace keeps + /// no clock of its own). `stroking`: a stroke is being drawn (a frame that rendered stroke + /// points counts too, such as the release's commit). A stroke's frames are kept until the + /// first frame without one, which ends it. + pub fn frame(&mut self, s: &FrameStages, stroking: bool, backend: impl FnOnce() -> String) { if !self.enabled() { return; } - let interval = self.last_start.map_or(0.0, |t| now - t); - self.last_start = Some(now); - self.frame = Some(Row { t: now, interval, moves, ..Default::default() }); - } - - /// eframe's CPU time for the previous frame, in seconds (`Frame::info().cpu_usage`). - pub fn cpu_prev(&mut self, secs: Option) { - if let Some(f) = self.frame.as_mut() { - f.cpu_prev = secs.map(|s| f64::from(s) * 1000.0); - } - } - - /// Time spent rendering stroke points this frame. - pub fn stroke(&mut self, ms: f64) { - if let Some(f) = self.frame.as_mut() { - f.stroke += ms; - } - } - - /// Time spent refreshing the canvas this frame. - pub fn canvas(&mut self, ms: f64) { - if let Some(f) = self.frame.as_mut() { - f.canvas += ms; - } - } - - /// The frame's UI is built (`ui` ms). `stroking`: a stroke is being drawn (a frame that - /// rendered stroke points counts too, such as the release's commit). A stroke's frames are - /// kept until the first frame without one, which ends it. - pub fn end_frame(&mut self, ui: f64, stroking: bool, backend: impl FnOnce() -> String) { - let Some(mut f) = self.frame.take() else { return }; - if stroking || f.stroke > 0.0 { - f.ui = ui; + let interval = self.last_start.map_or(0.0, |t| s.t - t); + self.last_start = Some(s.t); + if stroking || s.stroke_ms > 0.0 { // The first frame of a stroke doesn't follow a stroke frame: its interval is idle time. - if self.rows.is_empty() { - f.interval = 0.0; - } - self.rows.push(f); + let interval = if self.rows.is_empty() { 0.0 } else { interval }; + self.rows.push(Row::from_stages(s, interval)); } else if !self.rows.is_empty() { self.finish(backend()); } @@ -251,14 +232,38 @@ mod tests { StrokeTrace { output: Output::Stderr, ..Default::default() } } - fn frame(t: &mut StrokeTrace, now: f64, cpu: f32, stroking: bool) { - t.begin_frame(now, 3); - t.cpu_prev(Some(cpu / 1000.0)); + fn stages(now: f64, cpu: f32, stroking: bool) -> FrameStages { + let mut s = FrameStages::default(); + s.start(now, 3); + s.ui_start(now, Some(cpu / 1000.0)); if stroking { - t.stroke(1.0); - t.canvas(2.0); + s.stroke_ms = 1.0; + s.refresh("rect", 10, 1.5, 0.5); } - t.end_frame(4.0, stroking, || "vulkan Test GPU".into()); + s.ui_ms = 4.0; + s + } + + fn frame(t: &mut StrokeTrace, now: f64, cpu: f32, stroking: bool) { + t.frame(&stages(now, cpu, stroking), stroking, || "vulkan Test GPU".into()); + } + + #[test] + fn stroke_trace_reads_the_shared_frame_stages() { + let mut t = on(); + let mut ring = crate::frame_stages::SlowFrames::default(); + let mut last = None; + for (k, now) in [100.0, 116.0, 132.0].into_iter().enumerate() { + let s = ring.finish(stages(now, 6.0, true), now + 5.0, false, None); + t.frame(&s, true, || "test".into()); + let interval = if k == 0 { 0.0 } else { 16.0 }; + let row = t.rows.last().expect("a stroke frame").clone(); + assert_eq!((row.t, row.interval, row.moves, row.stroke, row.canvas, row.ui), (s.t, interval, 3, 1.0, 2.0, 4.0)); + assert_eq!(row.cpu_prev, s.cpu_prev_ms); + assert_eq!(t.rows.last(), Some(&Row::from_stages(&s, interval)), "the row is the frame's stages"); + last = Some(s); + } + assert_eq!(last.map(|s| s.composite_ms + s.upload_ms), Some(2.0)); } #[test]