Render path: one place records why a view left the GPU, typed, logged once per change and shown in the status bar (#9328)

render_path::note is the single entry point for every GPU exit (over budget, canvas too large,
compositor build failure, device loss, unsupported layers, clipped adjustment preview, flipped
view, software adapter or CPU mode at startup). It replaces the four direct writes of
perf.gpu_fallback and the three ad-hoc log lines, stops the over-budget log from repeating after
each brush dab, gives the over-budget reason its numbers, and records the exits that were silent.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Brennan StehlingandClaude Opus 5.5 committed 2026-10-27 02:07:25 -07:00
1 parent 7ac7b8b106
commit dfdfb50339
20 files changed
+574 -53

No files matched your search

+1 -1
View File
@@ -175,7 +175,7 @@ fn refresh(g: &GpuCanvas, rs: &RenderState, doc: &Document, damage: Option<Rect>
let r = g.refresh(doc.id.0, doc, damage, None);
let _ = rs.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: None });
let kind = if r.kind.starts_with("gpu") { format!("{}, {} tiles up", r.kind, r.uploads) } else { r.kind.to_string() };
(kind, r.fallback)
(kind, r.fallback.map(|f| f.to_string()))
}
fn main() {
+1
View File
@@ -165,6 +165,7 @@ impl PhotocraftApp {
started: None,
perf: Default::default(),
stroke_trace: stroke_trace::StrokeTrace::from_env(),
render_path: Default::default(),
prefs_rt: Default::default(),
updates_rt: Default::default(),
discard: None,
+2
View File
@@ -165,6 +165,8 @@ impl PhotocraftApp {
}
let t0 = gpu_canvas::now_ms();
self.perf.frame_refresh_ms = 0.0;
// A software adapter or CPU mode chosen at startup is every document's reason.
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);
+7
View File
@@ -332,6 +332,13 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// A flipped or pixel-aspect-corrected view draws through the CPU path (the GPU canvas shader
// has no mirroring or non-square pixels). Rotation stays on the GPU: it is a view uniform.
let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation, aspect);
if app.gpu.is_some() {
if gpu_ok {
crate::render_path::view_ok(app, doc.id.0);
} else {
crate::render_path::note(app, doc.id.0, crate::render_path::Path::Cpu(crate::render_path::CpuReason::ViewTransform));
}
}
if app.gpu.is_some()
&& gpu_ok
&& let Some((k, key, preview_size)) = ensure_adjust_proxy(app, idx, render_zoom)
@@ -110,7 +110,7 @@ pub(crate) struct Redraw {
rx: Receiver<Piece>,
stop: Arc<AtomicBool>,
started_ms: f64,
fallback: Option<String>,
fallback: Option<crate::render_path::CpuReason>,
/// The state the blocks are drawn from, and what the texels depend on besides it.
doc: Arc<Document>,
display: u64,
@@ -285,7 +285,7 @@ pub(crate) fn start(
display: Option<Arc<CanvasDisplay>>,
visible: Rect,
region: Rect,
fallback: Option<String>,
fallback: Option<crate::render_path::CpuReason>,
) {
let all = blocks(doc.bounds());
let display_key = display.as_deref().map_or(0, |d| d.texture_key);
@@ -384,7 +384,7 @@ pub(crate) fn poll(app: &mut PhotocraftApp, gpu: &GpuCanvas, doc: DocId) {
}
let ms = crate::gpu_canvas::now_ms() - r.started_ms;
app.perf.record("background", r.drawn, ms, 0.0);
crate::notices::slow_cpu_refresh(app, doc.0, ms, r.fallback.as_deref());
crate::notices::slow_cpu_refresh(app, doc.0, ms, r.fallback.as_ref());
}
/// Keep uploaded block `p` for [`Kept`], unless the composite would pass the cap.
@@ -454,7 +454,7 @@ struct Spawn {
pending: Vec<bool>,
/// When it started and the pixels uploaded so far.
since: (f64, u64),
fallback: Option<String>,
fallback: Option<crate::render_path::CpuReason>,
/// Blocks collected for [`Kept`], their bytes, and the cap.
keep: (Vec<Option<Vec<u8>>>, u64, u64),
}
@@ -523,6 +523,99 @@ fn hiding_a_large_layer_over_the_gpu_budget_redraws_in_the_background() {
assert!(g.harness.state().redraws.contains_key(&doc), "not composited inline: {}", g.harness.state().perf.last_refresh);
settle(&mut g);
assert_eq!(g.harness.state().perf.last_refresh, "background");
assert_eq!(g.harness.state().perf.gpu_fallback.as_deref(), Some(crate::gpu_canvas::OVER_BUDGET));
let app = g.harness.state();
assert!(matches!(app.render_path.current(doc.0), Some(crate::render_path::CpuReason::OverBudget { .. })), "{:?}", app.perf.gpu_fallback);
assert_matches_synchronous(&mut g, doc);
}
/// The active document's render path: its reason's kind and the status bar's label.
fn render_path_of(g: &Gpu) -> (Option<&'static str>, Option<&'static str>) {
let app = g.harness.state();
let doc = app.session.active().expect("document").doc.id.0;
(app.render_path.current(doc).map(crate::render_path::CpuReason::kind), crate::chrome_ui::render_path_label(app).map(|l| l.0))
}
#[test]
fn advanced_blending_fallback_is_shown_in_the_status_bar() {
use egui_kittest::kittest::Queryable;
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut g) = gpu_app() else { return };
cpu_only_document(g.harness.state_mut(), 800, 600);
g.harness.step();
settle(&mut g);
g.harness.run_steps(2);
assert_eq!(render_path_of(&g), (Some("unsupported"), Some("CPU Rendering")));
assert!(g.harness.query_by_label("CPU Rendering").is_some(), "the status bar says so");
let tip = crate::chrome_ui::render_path_label(g.harness.state()).map(|l| l.1).unwrap_or_default();
assert!(tip.contains("Advanced Blending"), "{tip}");
}
#[test]
fn over_budget_fallback_shows_working_set_and_budget() {
use egui_kittest::kittest::Queryable;
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut g) = gpu_app() else { return };
// As in `hiding_a_large_layer_over_the_gpu_budget_redraws_in_the_background`: a large damage
// rect over a budget the whole width's pages don't fit.
let app = g.harness.state_mut();
app.run("file.new", json!({"width": 5000, "height": 2000, "background": "#336699"})).expect("new");
app.run("layer.new.layer", json!({})).expect("layer");
app.run("select.rect", json!({"x": 0, "y": 0, "width": 4800, "height": 1800})).expect("select");
app.run("edit.fill", json!({"color": "#cc8844"})).expect("fill");
app.run("select.deselect", json!({})).expect("deselect");
let layer = app.session.active().expect("document").active_layer.expect("layer");
settle(&mut g);
assert_eq!(render_path_of(&g).0, None, "the document fits the GPU");
g.observer.set_memory_budget(48 << 20);
g.harness.state_mut().run("layer.setProps", json!({"layer": layer.0, "visible": false})).expect("hide");
g.harness.step();
settle(&mut g);
g.harness.run_steps(2);
assert_eq!(render_path_of(&g), (Some("overBudget"), Some("GPU Memory Full")));
assert!(g.harness.query_by_label("GPU Memory Full").is_some());
let text = g.harness.state().perf.gpu_fallback.clone().unwrap_or_default();
assert!(text.contains("of GPU memory, budget") && text.contains('M'), "{text}");
}
#[test]
fn a_compositor_build_failure_shows_its_reason() {
use egui_kittest::kittest::Queryable;
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut g) = gpu_app() else { return };
// The DX12 FXC failure of #8733, which no Mac reproduces.
g.observer.fail_compositor("Shader compilation failed: error X3507: not all control paths return a value");
g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new");
g.harness.step();
settle(&mut g);
g.harness.run_steps(2);
assert_eq!(render_path_of(&g), (Some("compositorBuild"), Some("CPU Rendering")));
assert!(g.harness.query_by_label("CPU Rendering").is_some());
assert!(g.harness.state().perf.gpu_fallback.as_deref().is_some_and(|f| f.contains("X3507")));
}
#[test]
fn a_canvas_over_the_texture_budget_records_its_reason() {
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut g) = gpu_app() else { return };
// The app's canvas, not the observer: each `GpuCanvas::new` shares a new budget.
g.harness.state().gpu.as_ref().expect("gpu canvas").set_canvas_budget(1);
g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new");
g.harness.run_steps(3);
assert_eq!(render_path_of(&g), (Some("canvasTooLarge"), Some("CPU Rendering")));
assert_eq!(g.harness.state().render_path.history().count(), 1, "once, not every frame");
}
#[test]
fn a_flipped_view_records_why_it_draws_on_the_cpu() {
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut g) = gpu_app() else { return };
g.harness.state_mut().run("file.new", json!({"width": 400, "height": 300, "background": "#336699"})).expect("new");
g.harness.run_steps(3);
assert_eq!(render_path_of(&g).0, None);
g.harness.state_mut().ui.view.flip_horizontal = true;
g.harness.run_steps(3);
assert_eq!(render_path_of(&g), (Some("viewTransform"), Some("CPU Rendering")));
g.harness.state_mut().ui.view.flip_horizontal = false;
g.harness.run_steps(3);
assert_eq!(render_path_of(&g).0, None, "back on the GPU");
}
+51 -5
View File
@@ -32,6 +32,8 @@ use std::sync::atomic::Ordering;
use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, RenderState, ScreenDescriptor};
use eframe::wgpu;
use crate::render_path::CpuReason;
pub use photocraft_gpu::{DeviceHealth, Fault};
mod budget;
@@ -351,10 +353,53 @@ impl GpuCanvas {
/// Whether `doc`'s display textures fit [`canvas_budget`]; when they don't, nothing is
/// created for it and it is drawn on the CPU canvas.
pub fn fits_canvas(&self, doc: &photocraft_doc::Document) -> bool {
self.canvas_fit(doc).is_some_and(|(bytes, budget)| bytes <= budget)
}
/// The bytes `doc`'s display textures would take and [`canvas_budget`] (`None` without a GPU
/// canvas): the numbers of a [`CpuReason::CanvasTooLarge`].
pub fn canvas_fit(&self, doc: &photocraft_doc::Document) -> Option<(u64, u64)> {
let size = [doc.size.width, doc.size.height];
let bytes = canvas_texture_bytes(size, self.tile, texel_bytes(self.format_for(doc.depth, size)));
let r = self.rs.renderer.read();
r.callback_resources.get::<Resources>().is_some_and(|res| bytes <= res.canvas_budget.load(Ordering::Relaxed))
r.callback_resources.get::<Resources>().map(|res| (bytes, res.canvas_budget.load(Ordering::Relaxed)))
}
/// Act as if the driver couldn't build the compositor's pipelines (the DX12 FXC X3507 case,
/// #8733): every later refresh goes to the CPU compositor with `msg` as the reason.
#[cfg(test)]
pub(crate) fn fail_compositor(&self, msg: &str) {
let mut r = self.rs.renderer.write();
if let Some(res) = r.callback_resources.get_mut::<Resources>() {
res.compositor = None;
res.compositor_failed = Some(photocraft_gpu::Unsupported(msg.into()));
}
}
/// Why the compositor couldn't be built, once it couldn't (see [`GpuCanvas::composite`]).
fn compositor_failed(&self) -> Option<String> {
let r = self.rs.renderer.read();
r.callback_resources.get::<Resources>()?.compositor_failed.as_ref().map(|e| e.0.clone())
}
/// A [`photocraft_gpu::Unsupported`] from [`GpuCanvas::composite`] as a typed reason, with
/// the numbers of the budget it names.
fn reason(&self, doc: &photocraft_doc::Document, e: photocraft_gpu::Unsupported) -> CpuReason {
if let Some(f) = self.fault() {
return CpuReason::from_fault(&f);
}
if e.0 == OVER_BUDGET {
let fit = self.layer_fit();
return CpuReason::OverBudget { needed: fit.map_or(0, |f| f.needed), budget: fit.map_or(0, |f| f.budget) };
}
if e.0 == OVER_CANVAS_BUDGET {
let (bytes, budget) = self.canvas_fit(doc).unwrap_or_default();
return CpuReason::CanvasTooLarge { bytes, budget };
}
if self.compositor_failed().is_some_and(|f| f == e.0) {
return CpuReason::CompositorBuild(e.0);
}
CpuReason::Unsupported(e.0)
}
/// Cap lower-stack composite reuse; zero disables it for profiling the uncached path.
@@ -557,7 +602,7 @@ impl GpuCanvas {
None => match photocraft_gpu::Compositor::try_new_with_format(device, photocraft_gpu::Compositor::preferred_acc_format(&self.rs.adapter)) {
Ok(c) => c,
Err(e) => {
log::warn!("{e}; using the CPU compositor");
// `render_path::note` logs it, once, as this document's reason.
res.compositor_failed = Some(e.clone());
return Err(e);
}
@@ -703,7 +748,7 @@ impl GpuCanvas {
) -> Refresh {
if let Some(f) = self.fault() {
// Nothing reaches the GPU any more; the app switches to the CPU canvas.
return Refresh { kind: "lost", fallback: Some(f.to_string()), ..Default::default() };
return Refresh { kind: "lost", fallback: Some(CpuReason::from_fault(&f)), ..Default::default() };
}
if !self.fits_canvas(doc) {
// Neither compositor can fill textures that are never created: the CPU canvas draws
@@ -711,7 +756,8 @@ impl GpuCanvas {
if let Some(res) = self.rs.renderer.write().callback_resources.get_mut::<Resources>() {
res.docs.remove(&key);
}
return Refresh { kind: REFRESH_OVER_BUDGET, fallback: Some(OVER_CANVAS_BUDGET.into()), ..Default::default() };
let (bytes, budget) = self.canvas_fit(doc).unwrap_or_default();
return Refresh { kind: REFRESH_OVER_BUDGET, fallback: Some(CpuReason::CanvasTooLarge { bytes, budget }), ..Default::default() };
}
let bounds = doc.bounds();
let size = [doc.size.width, doc.size.height];
@@ -737,7 +783,7 @@ impl GpuCanvas {
out.gpu = stats.gpu_time;
return out;
}
Err(e) => out.fallback = Some(e.0),
Err(e) => out.fallback = Some(self.reason(doc, e)),
}
let px = region.width() as u64 * region.height() as u64;
if defer && px >= DEFER_PX && self.prepare_texture(key, doc).is_some() {
+2 -3
View File
@@ -46,7 +46,8 @@ pub struct Perf {
/// Pixels of the refresh `gpu_ms` measured, which is a frame or two behind
/// `last_refresh_px` and may be a different size.
pub gpu_ms_px: u64,
/// Why the last refresh fell back to the CPU compositor (None = GPU composited).
/// Why the active view is drawn on the CPU (None = GPU composited): the current
/// [`crate::render_path`] reason as text, written only by `render_path`.
pub gpu_fallback: Option<String>,
/// Adapter, backend, driver and fallback state (Help › System Info).
pub gpu_info: GpuInfo,
@@ -224,8 +225,6 @@ impl Perf {
// refresh's would be read as this refresh's.
self.gpu_ms = None;
self.gpu_ms_px = 0;
} else {
self.gpu_fallback = None;
}
}
@@ -43,7 +43,7 @@ pub struct Refresh {
/// document under-reports by more than the few per cent of a warm one.
pub gpu: Option<photocraft_gpu::GpuTiming>,
/// Why the wgpu compositor wasn't used.
pub fallback: Option<String>,
pub fallback: Option<CpuReason>,
}
/// How the app creates its wgpu device: egui's defaults clamped to the adapter's supported limits,
+10 -7
View File
@@ -546,6 +546,8 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz
if app.perf.gpu_layer_fit.is_some_and(|f| f.doc == id.0) {
app.perf.gpu_layer_fit = None;
}
let (bytes, budget) = gpu.canvas_fit(&doc).unwrap_or_default();
crate::render_path::note(app, id.0, crate::render_path::Path::Cpu(crate::render_path::CpuReason::CanvasTooLarge { bytes, budget }));
return false;
}
let partial = present && damage.is_some();
@@ -557,6 +559,9 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz
// The device is gone (`gpu_status` then drops the GPU canvas) or the canvas is over the
// texture budget: draw this frame on the CPU path.
crate::background_redraw::cancel(app, id);
if let Some(reason) = r.fallback {
crate::render_path::note(app, id.0, crate::render_path::Path::Cpu(reason));
}
return false;
}
if r.kind == crate::gpu_canvas::REFRESH_DEFERRED {
@@ -569,21 +574,19 @@ pub(super) fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz
} else {
crate::background_redraw::cancel(app, id);
}
if let Some(e) = &r.fallback
&& app.perf.gpu_fallback.as_deref() != Some(e.as_str())
{
log::info!("{e}; using the CPU compositor");
match &r.fallback {
Some(reason) => crate::render_path::note(app, id.0, crate::render_path::Path::Cpu(reason.clone())),
None if r.kind.starts_with("gpu") => crate::render_path::note(app, id.0, crate::render_path::Path::Gpu { full: r.kind == "gpu-full" }),
None => {}
}
if r.kind != crate::gpu_canvas::REFRESH_DEFERRED {
app.perf.record_refresh(&r);
}
if r.kind == "full" {
crate::notices::slow_cpu_refresh(app, id.0, r.composite_ms + r.upload_ms, r.fallback.as_deref());
crate::notices::slow_cpu_refresh(app, id.0, r.composite_ms + r.upload_ms, r.fallback.as_ref());
}
if r.kind.starts_with("gpu") {
app.perf.gpu_uploads = r.uploads;
} else {
app.perf.gpu_fallback = r.fallback;
}
let Some(cache) = app.canvases.get_mut(&(id, GPU_OUTPUT)) else { return true };
cache.revision = revision;
+1 -1
View File
@@ -88,7 +88,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
"frame": app.frame,
"session": photocraft_engine::inspect::session(&app.session),
"document": app.session.active().map(photocraft_engine::inspect::document),
"perf": {"fps": app.fps, "timings": app.perf, "strokeTrace": app.stroke_trace.last},
"perf": {"fps": app.fps, "timings": app.perf, "strokeTrace": app.stroke_trace.last, "renderPath": crate::render_path::inspect(app)},
"brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity},
"distort": app.distort.describe(),
"jobs": crate::jobs_ui::inspect(app),
@@ -236,6 +236,10 @@ fn update(app: &mut PhotocraftApp, idx: usize) -> Option<&AdjustPreview> {
}
if app.adjust_preview.as_ref().is_none_or(|p| (p.doc, p.session) != (doc_id, session)) {
let doc = st.doc.clone();
// A target the layer path can't preview falls to the CPU proxy: say why (#7487).
if !channel_target && let Some(why) = unsupported(&doc, target) {
crate::render_path::note(app, doc_id.0, crate::render_path::Path::Cpu(crate::render_path::CpuReason::AdjustPreview(why)));
}
let base = if channel_target { None } else { base_document(&doc, target).ok().filter(|b| cheap(app, b)).map(Arc::new) };
let region = if base.is_some() { region(&doc, target) } else { Rect::EMPTY };
app.adjust_preview = Some(AdjustPreview {
@@ -300,6 +300,25 @@ fn ineligible_dialogs_keep_the_proxy_preview() {
assert!(!on_layer(&mut app, 0));
}
/// The proxy preview of a clipped target records why it doesn't preview through the layer
/// instead of dropping the reason (#7487).
#[test]
fn a_clipped_adjustment_preview_records_why_it_uses_the_proxy() {
let (doc, _) = document(ColorMode::Rgb, SampleType::U8, false);
let clipped = doc.layers[2].id;
let mut app = app_with(doc, clipped);
crate::adjust_dialog::open(&mut app, "image.adjustments.curves").unwrap();
assert!(!on_layer(&mut app, 0));
let doc = app.session.active().unwrap().doc.id.0;
assert_eq!(app.render_path.current(doc), Some(&crate::render_path::CpuReason::AdjustPreview("the target is clipped")));
let path = crate::render_path::inspect(&app);
assert_eq!(path["current"]["kind"], "adjustPreview");
assert!(path["current"]["detail"].as_str().is_some_and(|d| d.contains("the target is clipped")), "{path}");
// Asked again with nothing changed: no new entry.
assert!(!on_layer(&mut app, 0));
assert_eq!(app.render_path.history().count(), 1);
}
#[test]
fn proxy_factor_follows_the_zoom() {
assert_eq!(proxy_factor(1.0), 1);
+4 -3
View File
@@ -148,7 +148,8 @@ fn save_for_recovery(app: &mut PhotocraftApp) -> Result<(), String> {
/// path, record why, and tell the user. Documents are untouched.
pub fn fall_back(app: &mut PhotocraftApp, fault: &photocraft_gpu::Fault) {
let Some(gpu) = app.gpu.take() else { return };
log::error!("{fault}; using the CPU renderer");
// The GPU canvas is gone (that's this error); the switch to the CPU is `render_path`'s line.
log::error!("{fault}; GPU canvas dropped");
gpu.release();
app.gpu_fault = Some(fault.clone());
// Canvas caches pointed at GPU textures: rebuild them as egui textures.
@@ -156,7 +157,7 @@ pub fn fall_back(app: &mut PhotocraftApp, fault: &photocraft_gpu::Fault) {
app.proxy_uploaded = None;
app.prefs_rt.gpu_style = None;
app.perf.gpu = false;
app.perf.gpu_fallback = Some(fault.to_string());
crate::render_path::note_app(app, Some(crate::render_path::CpuReason::from_fault(fault)));
// The CPU canvas has no GPU memory budget: GPU Memory Full no longer applies.
app.perf.gpu_layer_fit = None;
app.perf.gpu_info.canvas = "cpu".into();
@@ -221,7 +222,7 @@ fn retry_now(app: &mut PhotocraftApp) -> bool {
// The CPU canvas's egui textures: rebuild every view on the GPU.
app.canvases.clear();
app.proxy_uploaded = None;
app.perf.gpu_fallback = None;
crate::render_path::note_app(app, None);
app.perf.gpu_info.lost = None;
app.ui.status = tl!("GPU acceleration resumed.").to_string();
app.ui.status_error = false;
+3
View File
@@ -33,6 +33,7 @@ pub mod notices;
pub mod panels;
pub mod preset_files_ui;
pub mod proxy;
pub mod render_path;
pub mod screenshot;
pub mod state;
pub mod texel_guard;
@@ -612,6 +613,8 @@ pub struct PhotocraftApp {
pub perf: gpu_canvas::Perf,
/// Per-frame stroke timings for latency reports (`PHOTOCRAFT_STROKE_TRACE`, see `stroke_trace`).
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,
/// 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,
+11 -11
View File
@@ -119,7 +119,7 @@ pub fn clipboard_unreadable(app: &mut PhotocraftApp) {
/// A full refresh of document `doc` fell back to the CPU compositor (`reason`, the GPU's) and took
/// `ms`. The canvas doesn't respond while it runs, so once per document say why it was slow and
/// which edits will do it again (#1015).
pub fn slow_cpu_refresh(app: &mut PhotocraftApp, doc: u64, ms: f64, reason: Option<&str>) {
pub fn slow_cpu_refresh(app: &mut PhotocraftApp, doc: u64, ms: f64, reason: Option<&crate::render_path::CpuReason>) {
if ms.is_nan() || ms < SLOW_CPU_REFRESH_MS || app.ui.slow_refresh_noticed.contains(&doc) {
return;
}
@@ -129,11 +129,11 @@ pub fn slow_cpu_refresh(app: &mut PhotocraftApp, doc: u64, ms: f64, reason: Opti
crate::i18n::fmt(tl!("This redraw took {seconds} s on the CPU."), &[("seconds", &seconds)]),
tl!("Edits that change the whole document, such as a layer's blend mode, opacity or visibility, redraw all of it.").into(),
];
if reason == Some(crate::gpu_canvas::OVER_BUDGET) {
if let Some(fit) = app.perf.gpu_layer_fit.filter(|f| f.doc == doc && !f.fits()) {
if let Some(&crate::render_path::CpuReason::OverBudget { needed, budget }) = reason {
if needed > budget {
lines.push(crate::i18n::fmt(
tl!("Its layers need {needed} of GPU memory; the budget leaves them {budget}."),
&[("needed", &crate::chrome_ui::fmt_bytes(fit.needed)), ("budget", &crate::chrome_ui::fmt_bytes(fit.budget))],
&[("needed", &crate::chrome_ui::fmt_bytes(needed)), ("budget", &crate::chrome_ui::fmt_bytes(budget))],
));
}
lines.push(
@@ -141,7 +141,7 @@ pub fn slow_cpu_refresh(app: &mut PhotocraftApp, doc: u64, ms: f64, reason: Opti
.into(),
);
} else if let Some(r) = reason {
lines.push(crate::i18n::fmt(tl!("The GPU compositor wasn't used: {reason}"), &[("reason", r)]));
lines.push(crate::i18n::fmt(tl!("The GPU compositor wasn't used: {reason}"), &[("reason", &r.to_string())]));
}
post(app, tl!("Large document: redrawing on the CPU"), lines, false, None);
}
@@ -405,13 +405,13 @@ mod tests {
#[test]
fn a_slow_cpu_refresh_is_explained_once_per_document() {
let mut app = PhotocraftApp::new(Session::new(), Services::default());
slow_cpu_refresh(&mut app, 1, 400.0, Some(crate::gpu_canvas::OVER_BUDGET));
slow_cpu_refresh(&mut app, 1, f64::NAN, Some(crate::gpu_canvas::OVER_BUDGET));
let over = crate::render_path::CpuReason::OverBudget { needed: 3600 << 20, budget: 3400 << 20 };
slow_cpu_refresh(&mut app, 1, 400.0, Some(&over));
slow_cpu_refresh(&mut app, 1, f64::NAN, Some(&over));
assert!(app.ui.notices.is_empty(), "a quick refresh needs no explanation");
// The layers of document 1 need 3.6 GB and may hold 3.4 GB: the notice says so.
app.perf.gpu_layer_fit = Some(crate::gpu_canvas::LayerFit { doc: 1, needed: 3600 << 20, budget: 3400 << 20 });
slow_cpu_refresh(&mut app, 1, 55_000.0, Some(crate::gpu_canvas::OVER_BUDGET));
slow_cpu_refresh(&mut app, 1, 55_000.0, Some(&over));
assert_eq!(app.ui.notices.len(), 1);
let text = app.ui.notices[0].lines.join(" ");
assert!(text.contains("55.0 s"), "{text}");
@@ -420,10 +420,10 @@ mod tests {
assert!(text.contains("GPU Memory in Preferences › Performance"), "{text}");
assert!(!app.ui.notices[0].error);
slow_cpu_refresh(&mut app, 1, 55_000.0, Some(crate::gpu_canvas::OVER_BUDGET));
slow_cpu_refresh(&mut app, 1, 55_000.0, Some(&over));
assert_eq!(app.ui.notices.len(), 1, "once per document");
slow_cpu_refresh(&mut app, 2, 3_000.0, Some("Blend If on `Overlay` (composited on the CPU)"));
slow_cpu_refresh(&mut app, 2, 3_000.0, Some(&crate::render_path::CpuReason::Unsupported("Blend If on `Overlay` (composited on the CPU)".into())));
assert_eq!(app.ui.notices.len(), 2);
let text = app.ui.notices[1].lines.join(" ");
assert!(text.contains("Blend If on `Overlay`"), "{text}");
+35 -13
View File
@@ -5,6 +5,7 @@ use egui::{RichText, Sense, Stroke, vec2};
use photocraft_doc::{Document, LayerContent};
use serde::{Deserialize, Serialize};
use crate::render_path::CpuReason;
use crate::theme::Tokens;
use crate::{PhotocraftApp, icons, widgets};
@@ -188,21 +189,42 @@ pub fn status_bar_pro(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
status_message(app, ui, &t);
}
/// The active document's layers don't fit the GPU memory budget (`perf.gpuLayerFit`): edits that
/// redraw the whole document do it on the CPU, so say so in the status bar until they fit again.
/// Clicking it opens Preferences › Performance, where GPU Memory raises the budget.
pub fn gpu_memory_status(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let Some(doc) = app.session.active().map(|st| st.doc.id.0) else { return };
let Some(fit) = app.perf.gpu_layer_fit.filter(|f| f.doc == doc && !f.fits()) else { return };
/// What the status bar says about the active document's render path: its label, tooltip and
/// the command a click runs, or None on the GPU.
pub(crate) fn render_path_label(app: &PhotocraftApp) -> Option<(&'static str, String, &'static str)> {
let doc = app.session.active().map(|st| st.doc.id.0)?;
let reason = app.render_path.current(doc);
// The measured fit (also on a switch to a document whose canvas is current) or the reason
// of the last full refresh: edits that redraw the whole document do it on the CPU, so say
// so until they fit again; GPU Memory in Preferences › Performance raises the budget.
let fit = app.perf.gpu_layer_fit.filter(|f| f.doc == doc && !f.fits()).map(|f| (f.needed, f.budget));
let over = match reason {
Some(&CpuReason::OverBudget { needed, budget }) => fit.or(Some((needed, budget))),
_ => fit,
};
if let Some((needed, budget)) = over {
let tip = crate::i18n::fmt(
tl!(
"The layers need {needed} of GPU memory and may hold {budget}, so edits that redraw the whole document do it on the CPU. Click to set GPU Memory."
),
&[("needed", &fmt_bytes(needed)), ("budget", &fmt_bytes(budget))],
);
return Some((tl!("GPU Memory Full"), tip, "edit.preferences.performance"));
}
let reason = reason?;
let tip = crate::i18n::fmt(tl!("Drawn on the CPU: {reason}. Click for System Info."), &[("reason", &reason.to_string())]);
Some((tl!("CPU Rendering"), tip, "help.systemInfo"))
}
/// The active document is drawn on the CPU (`render_path`): say so in the status bar, with the
/// reason in the tooltip. "GPU Memory Full" opens Preferences › Performance; any other reason,
/// "CPU Rendering", opens Help › System Info.
pub fn render_path_status(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let Some((label, tip, command)) = render_path_label(app) else { return };
let t = Tokens::get(ui.ctx());
let resp = ui
.add(egui::Label::new(RichText::new(tl!("GPU Memory Full")).color(t.warning).size(12.0)).sense(Sense::click()))
.on_hover_text(crate::i18n::fmt(
tl!("The layers need {needed} of GPU memory and may hold {budget}, so edits that redraw the whole document do it on the CPU. Click to set GPU Memory."),
&[("needed", &fmt_bytes(fit.needed)), ("budget", &fmt_bytes(fit.budget))],
));
let resp = ui.add(egui::Label::new(RichText::new(label).color(t.warning).size(12.0)).sense(Sense::click())).on_hover_text(tip);
if resp.clicked() {
crate::shortcut_dispatch::dispatch(app, ui.ctx(), "edit.preferences.performance");
crate::shortcut_dispatch::dispatch(app, ui.ctx(), command);
}
}
+2 -2
View File
@@ -23,7 +23,7 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
ui.with_layout(crate::direction::trailing(), |ui| {
crate::jobs_ui::status_progress(app, ui);
crate::background_redraw::status(app, ui);
crate::chrome_ui::gpu_memory_status(app, ui);
crate::chrome_ui::render_path_status(app, ui);
});
return;
}
@@ -67,7 +67,7 @@ pub fn status_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::jobs_ui::status_progress(app, ui);
}
crate::background_redraw::status(app, ui);
crate::chrome_ui::gpu_memory_status(app, ui);
crate::chrome_ui::render_path_status(app, ui);
});
});
});
+321
View File
@@ -0,0 +1,321 @@
//! Why a view left the GPU (#9328): one typed reason per document, recorded at **one** entry
//! point ([`note`]) by every exit from the GPU path, logged once when it changes, kept in a short
//! history, shown in the status bar (`chrome_ui::render_path_status`) and returned by the control
//! channel (`perf.renderPath`). `perf.gpuFallback` mirrors the current reason as text.
use std::collections::{HashMap, VecDeque};
use std::fmt;
use serde_json::{Value, json};
use crate::PhotocraftApp;
/// Changes the history keeps.
pub const HISTORY: usize = 32;
/// Why a view is drawn by the CPU compositor or on the CPU canvas.
#[derive(Clone, Debug, PartialEq)]
pub enum CpuReason {
/// The layer pages a full (or large) refresh needs don't fit the GPU memory budget (bytes).
OverBudget { needed: u64, budget: u64 },
/// The display textures don't fit the GPU texture budget (bytes).
CanvasTooLarge { bytes: u64, budget: u64 },
/// The driver couldn't build the compositor's pipelines (such as DX12 FXC X3507, #8733).
CompositorBuild(String),
/// The device was lost (the fault's text).
DeviceLost(String),
/// An uncaptured GPU error (the fault's text).
GpuError(String),
/// What the wgpu compositor can't express (Advanced Blending, CMYK, effects…), its own text.
Unsupported(String),
/// An adjustment dialog previews through the CPU proxy (#7487).
AdjustPreview(&'static str),
/// A flipped or pixel-aspect-corrected view: the GPU canvas shader has neither.
ViewTransform,
/// The window's adapter is a software renderer.
SoftwareAdapter,
/// Startup chose CPU rendering (the preference, `--safe-gpu`, an earlier crash…).
CpuMode(String),
}
impl CpuReason {
/// The reason from a device fault.
pub fn from_fault(f: &photocraft_gpu::Fault) -> Self {
if f.is_lost() { CpuReason::DeviceLost(f.to_string()) } else { CpuReason::GpuError(f.to_string()) }
}
/// A stable id of the kind of reason (the control channel's `kind`): reasons compare by it,
/// not by their numbers or text.
pub fn kind(&self) -> &'static str {
match self {
CpuReason::OverBudget { .. } => "overBudget",
CpuReason::CanvasTooLarge { .. } => "canvasTooLarge",
CpuReason::CompositorBuild(_) => "compositorBuild",
CpuReason::DeviceLost(_) => "deviceLost",
CpuReason::GpuError(_) => "gpuError",
CpuReason::Unsupported(_) => "unsupported",
CpuReason::AdjustPreview(_) => "adjustPreview",
CpuReason::ViewTransform => "viewTransform",
CpuReason::SoftwareAdapter => "softwareAdapter",
CpuReason::CpuMode(_) => "cpuMode",
}
}
/// Reasons that apply to full refreshes only: a small GPU edit doesn't end them.
fn full_refresh_only(&self) -> bool {
matches!(self, CpuReason::OverBudget { .. } | CpuReason::CanvasTooLarge { .. })
}
}
impl fmt::Display for CpuReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use crate::chrome_ui::fmt_bytes;
match self {
CpuReason::OverBudget { needed, budget } => {
write!(f, "layers need {} of GPU memory, budget {}; full refresh on the CPU", fmt_bytes(*needed), fmt_bytes(*budget))
}
CpuReason::CanvasTooLarge { bytes, budget } => {
write!(f, "the canvas needs {} of GPU textures, budget {}; drawing it on the CPU canvas", fmt_bytes(*bytes), fmt_bytes(*budget))
}
CpuReason::CompositorBuild(e) => write!(f, "the GPU compositor couldn't be built: {e}"),
CpuReason::DeviceLost(e) | CpuReason::GpuError(e) | CpuReason::Unsupported(e) => f.write_str(e),
CpuReason::AdjustPreview(why) => write!(f, "the adjustment preview uses the CPU proxy: {why}"),
CpuReason::ViewTransform => f.write_str("a flipped or pixel-aspect-corrected view is drawn on the CPU"),
CpuReason::SoftwareAdapter => f.write_str("the graphics adapter is a software renderer"),
CpuReason::CpuMode(why) => write!(f, "CPU rendering: {why}"),
}
}
}
/// What a refresh or view did.
#[derive(Clone, Debug, PartialEq)]
pub enum Path {
/// The wgpu compositor drew it (`full`: the whole document).
Gpu {
full: bool,
},
Cpu(CpuReason),
}
/// One change of a document's (or, with `doc` 0, the app's) reason.
#[derive(Clone, Debug, PartialEq)]
pub struct Change {
pub t_ms: f64,
pub doc: u64,
pub reason: Option<CpuReason>,
}
/// The current reasons and their history.
#[derive(Clone, Debug, Default)]
pub struct RenderPath {
docs: HashMap<u64, CpuReason>,
/// A reason for every document: the GPU canvas was dropped, or never started.
app_wide: Option<CpuReason>,
startup_checked: bool,
history: VecDeque<Change>,
}
impl RenderPath {
/// Why document `doc` is drawn on the CPU now, or None on the GPU.
pub fn current(&self, doc: u64) -> Option<&CpuReason> {
self.app_wide.as_ref().or_else(|| self.docs.get(&doc))
}
/// The changes, oldest first.
pub fn history(&self) -> impl Iterator<Item = &Change> {
self.history.iter()
}
fn push(&mut self, doc: u64, reason: Option<CpuReason>) {
if self.history.len() == HISTORY {
self.history.pop_front();
}
self.history.push_back(Change { t_ms: crate::gpu_canvas::now_ms(), doc, reason });
}
}
fn doc_name(app: &PhotocraftApp, doc: u64) -> String {
app.session.documents().iter().find(|st| st.doc.id.0 == doc).map_or_else(|| format!("document {doc}"), |st| st.doc.name.clone())
}
fn log_change(who: &str, reason: Option<&CpuReason>) {
match reason {
Some(r) => log::info!("render path: {who}: CPU ({}: {r})", r.kind()),
None => log::info!("render path: {who}: back on the GPU"),
}
}
/// Record what drew document `doc`: the one entry point of every exit from the GPU path. A new
/// kind of reason (not new numbers) is logged once and kept in the history; a partial GPU refresh
/// leaves a reason that applies to full refreshes only.
pub fn note(app: &mut PhotocraftApp, doc: u64, path: Path) {
let rp = &mut app.render_path;
let prev = rp.docs.get(&doc);
let next = match path {
Path::Gpu { full: false } if prev.is_some_and(CpuReason::full_refresh_only) => return,
Path::Gpu { .. } => None,
Path::Cpu(r) => Some(r),
};
let changed = prev.map(CpuReason::kind) != next.as_ref().map(CpuReason::kind);
match &next {
Some(r) => rp.docs.insert(doc, r.clone()),
None => rp.docs.remove(&doc),
};
app.perf.gpu_fallback = app.render_path.current(doc).map(ToString::to_string);
if changed {
log_change(&doc_name(app, doc), next.as_ref());
app.render_path.push(doc, next);
}
}
/// Record a reason for every document (the GPU canvas was dropped or never started), or its end.
pub fn note_app(app: &mut PhotocraftApp, reason: Option<CpuReason>) {
let rp = &mut app.render_path;
let changed = rp.app_wide.as_ref().map(CpuReason::kind) != reason.as_ref().map(CpuReason::kind);
rp.app_wide = reason.clone();
app.perf.gpu_fallback = reason.as_ref().map(ToString::to_string);
if changed {
log_change("all documents", reason.as_ref());
app.render_path.push(0, reason);
}
}
/// A view that may draw on the GPU again: end a [`CpuReason::ViewTransform`] reason.
pub fn view_ok(app: &mut PhotocraftApp, doc: u64) {
if app.render_path.docs.get(&doc) == Some(&CpuReason::ViewTransform) {
note(app, doc, Path::Gpu { full: true });
}
}
/// Once, when the window has no GPU canvas: a software adapter or CPU mode chosen at startup.
pub fn frame(app: &mut PhotocraftApp) {
if app.render_path.startup_checked || app.gpu.is_some() || app.gpu_fault.is_some() {
return;
}
let info = &app.perf.gpu_info;
let reason = if info.device_type == "cpu" {
CpuReason::SoftwareAdapter
} else if info.canvas == "cpu" {
CpuReason::CpuMode(info.fallback.clone().unwrap_or_else(|| format!("performance.gpuBackend is {}", info.preference)))
} else {
// The adapter isn't known yet (or this host has none to report).
return;
};
app.render_path.startup_checked = true;
note_app(app, Some(reason));
}
fn reason_json(doc: u64, r: Option<&CpuReason>) -> Value {
json!({"doc": doc, "kind": r.map(CpuReason::kind), "detail": r.map(ToString::to_string)})
}
/// The control channel's `perf.renderPath`: the active document's reason (`null` on the GPU) and
/// the history, oldest first.
pub fn inspect(app: &PhotocraftApp) -> Value {
let active = app.session.active().map(|st| st.doc.id.0);
let current = active.and_then(|d| app.render_path.current(d).map(|r| reason_json(d, Some(r))));
let history: Vec<Value> = app
.render_path
.history()
.map(|c| {
let mut v = reason_json(c.doc, c.reason.as_ref());
v["t"] = json!(c.t_ms);
v
})
.collect();
json!({"current": current, "history": history})
}
#[cfg(test)]
mod tests {
use super::*;
fn app() -> PhotocraftApp {
PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default())
}
fn over(needed: u64) -> Path {
Path::Cpu(CpuReason::OverBudget { needed, budget: 2 << 30 })
}
#[test]
fn reasons_compare_by_kind_not_numbers() {
let mut app = app();
note(&mut app, 1, over(3 << 30));
note(&mut app, 1, over(4 << 30));
assert_eq!(app.render_path.history().count(), 1);
assert_eq!(app.render_path.current(1), Some(&CpuReason::OverBudget { needed: 4 << 30, budget: 2 << 30 }), "the numbers update");
assert!(app.perf.gpu_fallback.as_deref().is_some_and(|f| f.contains("4.0G")), "{:?}", app.perf.gpu_fallback);
note(&mut app, 1, Path::Cpu(CpuReason::Unsupported("Advanced Blending on `A`".into())));
assert_eq!(app.render_path.history().count(), 2, "another kind is a change");
}
#[test]
fn a_partial_gpu_refresh_keeps_an_over_budget_reason() {
let mut app = app();
note(&mut app, 1, over(3 << 30));
note(&mut app, 1, Path::Gpu { full: false });
assert!(app.render_path.current(1).is_some(), "a brush dab doesn't end it");
assert!(app.perf.gpu_fallback.is_some());
note(&mut app, 1, Path::Gpu { full: true });
assert!(app.render_path.current(1).is_none());
assert!(app.perf.gpu_fallback.is_none());
assert_eq!(app.render_path.history().count(), 2);
// Other reasons end at any GPU refresh.
note(&mut app, 1, Path::Cpu(CpuReason::ViewTransform));
note(&mut app, 1, Path::Gpu { full: false });
assert!(app.render_path.current(1).is_none());
}
#[test]
fn the_fallback_log_does_not_repeat_between_partial_refreshes() {
// Over budget, a dab, a full refresh, a dab, a full refresh: one change, not five.
let mut app = app();
note(&mut app, 1, over(3 << 30));
note(&mut app, 1, Path::Gpu { full: false });
note(&mut app, 1, over(3 << 30));
note(&mut app, 1, Path::Gpu { full: false });
note(&mut app, 1, over(3 << 30));
assert_eq!(app.render_path.history().count(), 1);
}
#[test]
fn history_keeps_the_last_32_changes() {
let mut app = app();
for i in 0..40 {
note(&mut app, i, Path::Cpu(CpuReason::ViewTransform));
}
let docs: Vec<u64> = app.render_path.history().map(|c| c.doc).collect();
assert_eq!(docs, (8..40).collect::<Vec<_>>());
}
#[test]
fn over_budget_reason_names_the_working_set_and_budget() {
let text = CpuReason::OverBudget { needed: 3600 << 20, budget: 512 << 20 }.to_string();
assert!(text.contains("3.5G") && text.contains("512.0M"), "{text}");
let text = CpuReason::CanvasTooLarge { bytes: 3 << 30, budget: 1 << 30 }.to_string();
assert!(text.contains("3.0G") && text.contains("1.0G"), "{text}");
}
#[test]
fn a_software_adapter_is_the_reason_at_startup() {
let mut app = app();
assert!(app.gpu.is_none());
frame(&mut app);
assert!(app.render_path.current(1).is_none(), "no adapter known yet");
app.perf.gpu_info.adapter = "llvmpipe".into();
app.perf.gpu_info.device_type = "cpu".into();
frame(&mut app);
assert_eq!(app.render_path.current(1), Some(&CpuReason::SoftwareAdapter));
frame(&mut app);
assert_eq!(app.render_path.history().count(), 1, "once");
let mut app = self::app();
app.perf.gpu_info.device_type = "integratedGpu".into();
app.perf.gpu_info.canvas = "cpu".into();
app.perf.gpu_info.fallback = Some("--safe-gpu".into());
frame(&mut app);
assert_eq!(app.render_path.current(7), Some(&CpuReason::CpuMode("--safe-gpu".into())));
assert_eq!(inspect(&app)["history"][0]["kind"], "cpuMode");
}
}
+1 -1
View File
@@ -66,7 +66,7 @@ fn injected_loss_stops_gpu_work_without_panicking() {
// Every entry point is a no-op or an error now.
let r = g.refresh(key, &d, None, None);
assert_eq!(r.kind, "lost");
assert!(r.fallback.as_deref().unwrap_or("").contains("GPU device lost"));
assert!(r.fallback.as_ref().is_some_and(|f| f.to_string().contains("GPU device lost")));
assert!(g.composite(&d, d.bounds(), false).is_err());
assert!(!g.upload_rect(key, [0, 0], [1, 1], &[0; 4]));
g.upload_full(key, [1, 1], &[0; 4]);