From 3f18ff4b5ad3bab86739a17bc2d558cabc5bc115 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Mon, 12 Oct 2026 14:45:10 +0200 Subject: [PATCH 01/13] LR-VIEW-ZOOM: renders on the window's device come back as textures, not pixels (#1228) lightcraft-gpu can render on a device the window lends (share_window_device): the kernels compile on it, and try_render_texture hands a render over as an Rgba8Unorm texture (egui's own format) with no copy of the image back to the CPU. A small pad_rows kernel lays the kept part out for the buffer-to-texture copy and counts unwritten and lit pixels, so the incomplete-image and all-black checks still run on two words read back. try_render and the texture path share one failure path. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/src/ctx.rs | 48 +++++- crates/gpu/src/lib.rs | 269 +++++++++++++++++++++++-------- crates/gpu/src/render.rs | 114 ++++++++++++- crates/gpu/src/wgsl/present.wgsl | 45 ++++++ crates/gpu/tests/texture.rs | 139 ++++++++++++++++ 5 files changed, 540 insertions(+), 75 deletions(-) create mode 100644 crates/gpu/src/wgsl/present.wgsl create mode 100644 crates/gpu/tests/texture.rs diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 33e02fbe4b6..1af04602eeb 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -69,6 +69,11 @@ const MODULES: &[Module] = &[ bindings: &[("src", false, "f32"), ("dst", true, "f32"), ("coverage", false, "u32")], entries: &["orient", "sample_affine", "sample_warp"], }, + Module { + src: include_str!("wgsl/present.wgsl"), + bindings: &[("src", false, "u32"), ("dst", true, "u32"), ("stats", true, "atomic")], + entries: &["pad_rows"], + }, ]; struct Kernel { @@ -243,6 +248,10 @@ pub struct Gpu { free: std::sync::Mutex>, /// Largest storage buffer the device accepts (bytes). pub max_buffer: u64, + /// Largest texture side the device accepts. + pub max_texture: u32, + /// The window's device ([`Gpu::shared`]): renders can be handed to the window as textures. + pub shared: bool, } /// WGSL constants shared by every module (generated from the CPU pipeline's values). @@ -327,9 +336,31 @@ impl Gpu { ..Default::default() })) .map_err(|e| format!("{}: device creation failed ({e})", info.name))?; + Gpu::build(device, queue, info, false) + } + + /// Render on the device the window created (issue #1228): renders then reach the screen as + /// textures on that device, with no copy back to the CPU. Refused as [`Gpu::new`] refuses an + /// adapter: a software one, or one with too few storage buffers for the kernels. + pub fn shared(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) -> Result { + if info.device_type == wgpu::DeviceType::Cpu { + return Err(format!("software adapter ({}) skipped: the CPU pipeline is faster", info.name)); + } + let n = device.limits().max_storage_buffers_per_shader_stage; + if n < 10 { + return Err(format!("{} has too few storage buffers per shader stage ({n} < 10)", info.name)); + } + Gpu::build(device, queue, info, true) + } + + /// Install the error handlers and compile the kernels on `device`. + fn build(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo, shared: bool) -> Result { // Errors outside a render's error scopes (see `ErrorScopes`): log, and stop using the GPU. - device.on_uncaptured_error(std::sync::Arc::new(|e| { - log::error!("gpu: {e}"); + // On the window's device this covers the window's own errors too (its handler only + // logged): renders then go back to the CPU, and to textures egui uploads itself. + let what = if shared { "gpu (window device)" } else { "gpu" }; + device.on_uncaptured_error(std::sync::Arc::new(move |e| { + log::error!("{what}: {e}"); crate::mark_broken(&format!("device error: {e}")); })); // wgpu reports a lost device (driver reset, GPU hang, watchdog) only here — never as an @@ -378,9 +409,16 @@ impl Gpu { usage: wgpu::BufferUsages::STORAGE, mapped_at_creation: false, }); - let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); - log::info!("gpu: {} ({:?}), buffers ≤ {} MiB", info.name, info.backend, max_buffer >> 20); - Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer }) + let limits = device.limits(); + let mut max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); + // (a device of our own was requested with these limits already; the window's was not) + if let Some((binding, buffer)) = limits_override() { + max_buffer = max_buffer.min(binding).min(buffer); + } + let max_texture = limits.max_texture_dimension_2d; + let with = if shared { ", shared with the window" } else { "" }; + log::info!("gpu: {} ({:?}){with}, buffers ≤ {} MiB", info.name, info.backend, max_buffer >> 20); + Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, max_texture, shared }) } /// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible). diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 452e2dd6721..9b773413efc 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -275,6 +275,50 @@ fn env_disabled() -> bool { #[cfg(not(target_arch = "wasm32"))] static GPU: std::sync::OnceLock> = std::sync::OnceLock::new(); +/// The window's device, lent by [`share_window_device`]: the render device is created on it. +#[cfg(not(target_arch = "wasm32"))] +static WINDOW: Mutex> = Mutex::new(None); + +/// Render on the window's wgpu device instead of a device of LightCraft's own (issue #1228), so +/// that renders reach the screen as textures on it ([`try_render_texture`]) with no copy back to +/// the CPU. Call it once the window is up, before anything renders, then [`warm_up`]. Does nothing +/// once the render device exists; a device that can't run the kernels (a software adapter, too few +/// storage buffers) leaves renders on a device of their own, with read-back pixels as before. +/// The window's device must have been requested with the adapter's limits +/// ([`window_device_limits`]). +#[cfg(not(target_arch = "wasm32"))] +pub fn share_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu::AdapterInfo) { + if GPU.get().is_none() { + *WINDOW.lock().unwrap_or_else(|e| e.into_inner()) = Some((device, queue, info)); + } +} + +/// The limits to request the window's device with so renders can share it +/// ([`share_window_device`]): the adapter's own, as the render device asks for, with at least the +/// 8192 px texture side egui needs for 4k+ displays. A GL adapter keeps egui's WebGL2 limits (the +/// kernels never run there). +#[cfg(not(target_arch = "wasm32"))] +pub fn window_device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { + if adapter.get_info().backend == wgpu::Backend::Gl { + return wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::downlevel_webgl2_defaults() }; + } + let limits = adapter.limits(); + wgpu::Limits { max_texture_dimension_2d: limits.max_texture_dimension_2d.max(8192), ..limits } +} + +/// Whether renders run on the window's device, so [`try_render_texture`] can hand them over +/// without a readback. Never creates the device. +pub fn shares_window_device() -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + existing_device().is_some_and(|g| g.shared) + } + #[cfg(target_arch = "wasm32")] + { + false + } +} + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn device() -> Option<&'static ctx::Gpu> { // turned off (preference, environment): don't even load the driver (issue #136) @@ -288,6 +332,21 @@ pub(crate) fn device() -> Option<&'static ctx::Gpu> { let _work = exit::enter()?; GPU.get_or_init(|| { let Some(backends) = backend::compute_backends() else { return Err("disabled by LIGHTCRAFT_GPU_BACKEND=off".into()) }; + // the window's device, when its backend is one renders may use + let window = WINDOW.lock().unwrap_or_else(|e| e.into_inner()).take().filter(|(_, _, info)| backends.contains(info.backend.into())); + if let Some((device, queue, info)) = window { + let backend: wgpu::Backends = info.backend.into(); + let name = info.name.clone(); + let r = backend::with_init_marker(backend, move || { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || ctx::Gpu::shared(device, queue, info))) + .unwrap_or_else(|_| Err("kernel build panicked".into())) + }); + match r { + Ok(g) => return Ok(g), + // e.g. a software window adapter: a device of our own may still be better + Err(why) => log::info!("gpu: not rendering on the window's device ({name}): {why}"), + } + } let r = backend::with_init_marker(backends, || { std::panic::catch_unwind(|| ctx::Gpu::new(backends)).unwrap_or_else(|_| Err("device creation panicked".into())) }); @@ -458,6 +517,11 @@ pub fn handles(depth: lightcraft_pipeline::OutputDepth, device_proof: bool, over depth == lightcraft_pipeline::OutputDepth::U8 && !device_proof && overlay != lightcraft_pipeline::Overlay::HdrRange } +/// Whether `req` soft-proofs against an output-device profile, which [`handles`] leaves to the CPU. +fn device_proof(req: &RenderRequest) -> bool { + req.proof.is_some_and(|p| lightcraft_pipeline::proof_profile(p.profile).is_some()) +} + /// [`render`], reporting why this render made no GPU image: [`Fallback::NotTried`] when the GPU /// was not used (callers can ask [`unavailable_reason`]), [`Fallback::Failed`] with the reason /// when the GPU render failed and the CPU must render it. The reason belongs to this call, unlike @@ -471,77 +535,62 @@ pub fn try_render( ) -> Result { #[cfg(not(target_arch = "wasm32"))] { - // sections switched off with their eye render as if at their defaults (issue #316) - let effective = s.effective(); - let s: &DevelopSettings = &effective; - let device_proof = req.proof.is_some_and(|p| lightcraft_pipeline::proof_profile(p.profile).is_some()); - if !enabled() || !handles(req.depth, device_proof, req.overlay) { + attempt( + s, + req, + stages, + |r: &Rendered| (r.image.width, r.image.height), + |gpu, s, ext, fault| render::render(gpu, src, info, s, req, ext, fault), + ) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (src, info, s, req, stages); + Err(Fallback::NotTried) + } +} + +/// A render on the window's device, ready to draw ([`try_render_texture`]): `width × height` +/// sRGB-encoded RGBA8 pixels in an `Rgba8Unorm` texture, egui's own texture format. +pub struct GpuTexture { + #[cfg(not(target_arch = "wasm32"))] + pub texture: wgpu::Texture, + pub width: usize, + pub height: usize, +} + +/// Whether [`try_render_texture`] takes requests of this kind: what [`handles`] takes, without an +/// overlay (overlays are drawn on read-back pixels), and only while renders share the window's +/// device ([`shares_window_device`]). +pub fn texture_handles(req: &RenderRequest) -> bool { + handles(req.depth, device_proof(req), req.overlay) && req.overlay == lightcraft_pipeline::Overlay::None && shares_window_device() +} + +/// [`try_render`] into a texture on the window's device, with no copy of the image back to the +/// CPU (issue #1228): for views that only draw it, such as the loupe's zoom window. There is no +/// histogram. [`Fallback::NotTried`] when [`texture_handles`] says no; the caller then renders +/// with [`try_render`] (or on the CPU). +pub fn try_render_texture( + src: &Arc, + info: &SourceInfo, + s: &DevelopSettings, + req: &RenderRequest, + stages: Option<&StageCache>, +) -> Result { + #[cfg(not(target_arch = "wasm32"))] + { + if !texture_handles(req) { return Err(Fallback::NotTried); } - let s = &*lightcraft_pipeline::settings_for(s, req); - // in flight until this returns; not tried once the process is ending (issue #620) - let _work = exit::enter().ok_or(Fallback::NotTried)?; - let gpu = device().ok_or(Fallback::NotTried)?; - let ext = stages.map(|c| c.extension::()); - let fault = take_fault(); - // A simulated failure stops GPU use on this thread only (see `BROKEN_HERE`). - let stop = |reason: &str| if fault.is_some() { mark_broken_here(reason) } else { mark_broken(reason) }; - let _ = ctx::take_failure(); // nothing left over from an earlier render on this thread - let (r, scoped) = { - let _scope = ctx::RenderScope::new(gpu); - let errors = ctx::ErrorScopes::push(gpu); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref(), fault))); - (r, errors.pop()) - }; - // An error the device raised explains the readback failures that follow it; a buffer - // over the limit explains the errors its placeholder raises. - let failure = match (ctx::take_failure(), scoped) { - (Some(f), _) if f.kind == ctx::FailKind::Limit => Some(f), - (f, scoped) => scoped.or(f), - }; - let reason = match (r, failure) { - (Err(_), _) => { - log::error!("gpu: render failed; using the CPU pipeline from now on"); - stop("a GPU render panicked"); - "a GPU render panicked; the GPU is not used again".to_string() - } - (Ok(r), Some(f)) => { - // the view's cached device stages may hold results of the failed passes - if let Some(e) = &ext { - e.clear(); - } - let what = match &r { - Some(r) => format!("{}×{}", r.image.width, r.image.height), - None => "GPU render".into(), - }; - let reason = match f.kind { - ctx::FailKind::Fatal => { - stop(&f.reason); - format!("{what}: {}; the GPU is not used again", f.reason) - } - ctx::FailKind::OutOfMemory => { - gpu.trim(0); - format!("{what}: {}", f.reason) - } - ctx::FailKind::Limit | ctx::FailKind::Blank => format!("{what}: {}", f.reason), - }; - log::warn!("gpu: rendering on the CPU instead: {reason}"); - if render::profiling() { - eprintln!(" gpu fallback to the CPU: {reason}"); - } - reason - } - // a device error on another thread or a lost device during the render - (Ok(Some(_)), None) if BROKEN.load(Ordering::Relaxed) => { - format!("device failure during the render: {}", unavailable_reason().unwrap_or_default()) - } - (Ok(Some(r)), None) => return Ok(r), - // every path of `render::render` that gives up records a failure first; should one - // not, the CPU renders it rather than nothing - (Ok(None), None) => "GPU render: no image came back".to_string(), - }; - record_fallback(reason.clone()); - Err(Fallback::Failed(reason)) + attempt( + s, + req, + stages, + |t: &GpuTexture| (t.width, t.height), + |gpu, s, ext, fault| { + if gpu.shared { render::render_texture(gpu, src, info, s, req, ext, fault) } else { None } + }, + ) } #[cfg(target_arch = "wasm32")] { @@ -550,6 +599,88 @@ pub fn try_render( } } +/// Run `go` on the GPU with the render's settings, error scopes and failure accounting: its +/// result, or why the CPU must render instead. `size` names a result in a failure's reason. +#[cfg(not(target_arch = "wasm32"))] +fn attempt( + s: &DevelopSettings, + req: &RenderRequest, + stages: Option<&StageCache>, + size: impl Fn(&T) -> (usize, usize), + go: impl FnOnce(&ctx::Gpu, &DevelopSettings, Option<&GpuStages>, Option) -> Option, +) -> Result { + // sections switched off with their eye render as if at their defaults (issue #316) + let effective = s.effective(); + let s: &DevelopSettings = &effective; + if !enabled() || !handles(req.depth, device_proof(req), req.overlay) { + return Err(Fallback::NotTried); + } + let s = &*lightcraft_pipeline::settings_for(s, req); + // in flight until this returns; not tried once the process is ending (issue #620) + let _work = exit::enter().ok_or(Fallback::NotTried)?; + let gpu = device().ok_or(Fallback::NotTried)?; + let ext = stages.map(|c| c.extension::()); + let fault = take_fault(); + // A simulated failure stops GPU use on this thread only (see `BROKEN_HERE`). + let stop = |reason: &str| if fault.is_some() { mark_broken_here(reason) } else { mark_broken(reason) }; + let _ = ctx::take_failure(); // nothing left over from an earlier render on this thread + let (r, scoped) = { + let _scope = ctx::RenderScope::new(gpu); + let errors = ctx::ErrorScopes::push(gpu); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| go(gpu, s, ext.as_deref(), fault))); + (r, errors.pop()) + }; + // An error the device raised explains the readback failures that follow it; a buffer + // over the limit explains the errors its placeholder raises. + let failure = match (ctx::take_failure(), scoped) { + (Some(f), _) if f.kind == ctx::FailKind::Limit => Some(f), + (f, scoped) => scoped.or(f), + }; + let reason = match (r, failure) { + (Err(_), _) => { + log::error!("gpu: render failed; using the CPU pipeline from now on"); + stop("a GPU render panicked"); + "a GPU render panicked; the GPU is not used again".to_string() + } + (Ok(r), Some(f)) => { + // the view's cached device stages may hold results of the failed passes + if let Some(e) = &ext { + e.clear(); + } + let what = match r.as_ref().map(&size) { + Some((w, h)) => format!("{w}×{h}"), + None => "GPU render".into(), + }; + let reason = match f.kind { + ctx::FailKind::Fatal => { + stop(&f.reason); + format!("{what}: {}; the GPU is not used again", f.reason) + } + ctx::FailKind::OutOfMemory => { + gpu.trim(0); + format!("{what}: {}", f.reason) + } + ctx::FailKind::Limit | ctx::FailKind::Blank => format!("{what}: {}", f.reason), + }; + log::warn!("gpu: rendering on the CPU instead: {reason}"); + if render::profiling() { + eprintln!(" gpu fallback to the CPU: {reason}"); + } + reason + } + // a device error on another thread or a lost device during the render + (Ok(Some(_)), None) if BROKEN.load(Ordering::Relaxed) => { + format!("device failure during the render: {}", unavailable_reason().unwrap_or_default()) + } + (Ok(Some(r)), None) => return Ok(r), + // every path of `render::render` that gives up records a failure first; should one + // not, the CPU renders it rather than nothing + (Ok(None), None) => "GPU render: no image came back".to_string(), + }; + record_fallback(reason.clone()); + Err(Fallback::Failed(reason)) +} + #[cfg(test)] mod tests { use lightcraft_pipeline::{OutputDepth, Overlay}; diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 64990db0e11..8aa1d794390 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -586,6 +586,47 @@ pub fn render( stages: Option<&GpuStages>, fault: Option, ) -> Option { + match render_as(gpu, src, info, s, req, stages, fault, false)? { + Made::Pixels(r) => Some(r), + Made::Texture(_) => None, + } +} + +/// [`render`] into a texture on the window's device (issue #1228): no copy back to the CPU, no +/// histogram and no overlay (the caller asks [`crate::texture_handles`] first). +#[allow(clippy::too_many_arguments)] +pub fn render_texture( + gpu: &Gpu, + src: &Arc, + info: &SourceInfo, + s: &DevelopSettings, + req: &RenderRequest, + stages: Option<&GpuStages>, + fault: Option, +) -> Option { + match render_as(gpu, src, info, s, req, stages, fault, true)? { + Made::Texture(t) => Some(t), + Made::Pixels(_) => None, + } +} + +/// What a render made: pixels on the CPU, or a texture on the window's device. +enum Made { + Pixels(Rendered), + Texture(crate::GpuTexture), +} + +#[allow(clippy::too_many_arguments)] +fn render_as( + gpu: &Gpu, + src: &Arc, + info: &SourceInfo, + s: &DevelopSettings, + req: &RenderRequest, + stages: Option<&GpuStages>, + fault: Option, + texture: bool, +) -> Option { let mut t = profiling().then(std::time::Instant::now); // Each stage is submitted on its own; under `LIGHTCRAFT_PROFILE` also waited for, so the // timings are real. @@ -711,6 +752,11 @@ pub fn render( groups2(w, rows.min(h - y0), [16, 16]), ); } + if texture { + let made = to_texture(&mut cx, &out, w, h, plan.keep.map(|k| (k.x, k.y, k.w, k.h))); + lap("finish + present", &mut t, &mut cx); + return made.map(Made::Texture); + } // the alpha a mask overlay shows: copied out before the readback below submits let overlay_mask = req.overlay.mask(s).map(|m| { let list = s.masks.iter().filter(|m| m.visible && !m.components.is_empty()); @@ -780,7 +826,73 @@ pub fn render( if let Some(k) = plan.keep { image = image.crop(k.x, k.y, k.w, k.h); } - Some(Rendered { image, histogram, deep: None }) + Some(Made::Pixels(Rendered { image, histogram, deep: None })) +} + +/// Copy the kept part (`keep`: x, y, w, h; all of the `w × h` output when `None`) of the packed +/// RGBA8 output `out` into a new texture, with the checks the read-back path runs on the CPU: a +/// pixel the per-pixel kernel never wrote fails the render, an entirely black one is redone on the +/// CPU. Only two counters come back from the device. +fn to_texture(cx: &mut Cx<'_>, out: &Buf, w: usize, h: usize, keep: Option<(usize, usize, usize, usize)>) -> Option { + let gpu = cx.gpu; + let (x0, y0, kw, kh) = keep.unwrap_or((0, 0, w, h)); + // a crop past the output would read past `out`: never expected, but not a reason to crash + if kw == 0 || kh == 0 || x0.saturating_add(kw) > w || y0.saturating_add(kh) > h { + fail(FailKind::Fatal, format!("a {kw}×{kh} window at {x0},{y0} is outside the {w}×{h} render")); + return None; + } + if kw > gpu.max_texture as usize || kh > gpu.max_texture as usize { + fail(FailKind::Limit, format!("{kw}×{kh} is over the device's {} px texture side", gpu.max_texture)); + return None; + } + // rows padded to the copy alignment (256 bytes = 64 pixels) + let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize / 4; + let stride = kw.div_ceil(align) * align; + let padded = cx.gpu.buffer(stride * kh); + let stats = cx.zeroed(2); + let p = [w as u32, x0 as u32, y0 as u32, kw as u32, kh as u32, stride as u32]; + cx.run("pad_rows", &p, &[Some(out), Some(&padded), Some(&stats)], groups2(kw, kh, [16, 16])); + if crate::ctx::failed() { + return None; + } + let texture = gpu.device.create_texture(&wgpu::TextureDescriptor { + label: Some("lightcraft render"), + size: wgpu::Extent3d { width: kw as u32, height: kh as u32, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + // what egui samples its own textures as: sRGB-encoded bytes, blended in gamma space + format: wgpu::TextureFormat::Rgba8Unorm, + // (COPY_SRC: a screenshot or a test can still read it back) + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + { + let enc = cx.enc.get_or_insert_with(|| gpu.encoder()); + enc.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: padded.raw(), + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride as u32 * 4), rows_per_image: Some(kh as u32) }, + }, + texture.as_image_copy(), + wgpu::Extent3d { width: kw as u32, height: kh as u32, depth_or_array_layers: 1 }, + ); + } + // submits everything recorded, the copy included, and waits for it + let counts: Vec = cx.read(&stats, 2); + if crate::ctx::failed() { + return None; + } + let (unwritten, lit) = (counts.first().copied().unwrap_or(0), counts.get(1).copied().unwrap_or(0)); + if unwritten > 0 { + fail(FailKind::Fatal, format!("the GPU returned an incomplete image ({unwritten} of {} pixels unwritten)", kw * kh)); + return None; + } + if kw * kh >= 4096 && lit == 0 { + fail(FailKind::Blank, "the GPU result is entirely black; rendering it on the CPU to be sure".into()); + return None; + } + Some(crate::GpuTexture { texture, width: kw, height: kh }) } /// Pixels whose alpha is not 255 (cheap: no early exit, so it vectorizes). diff --git a/crates/gpu/src/wgsl/present.wgsl b/crates/gpu/src/wgsl/present.wgsl new file mode 100644 index 00000000000..7645221766f --- /dev/null +++ b/crates/gpu/src/wgsl/present.wgsl @@ -0,0 +1,45 @@ +// Hand a render to the window without reading it back (issue #1228): copy the kept part of the +// per-pixel stage's packed RGBA8 output into rows padded for a buffer-to-texture copy, and count +// what the CPU path checks on the read-back image (`render::render`): pixels the kernel never +// wrote (alpha other than 255) and pixels that are not black. +// P: src_w, x0, y0, w, h (the kept part), stride (words per padded row). Bindings: src, dst, stats +// (stats[0] = unwritten, stats[1] = not black; cleared by the caller). + +var wg_unwritten: atomic; +var wg_lit: atomic; + +@compute @workgroup_size(16, 16) +fn pad_rows(@builtin(global_invocation_id) g: vec3, @builtin(local_invocation_index) li: u32) { + let src_w = pu(0u); + let x0 = pu(1u); + let y0 = pu(2u); + let w = pu(3u); + let h = pu(4u); + let stride = pu(5u); + if (li == 0u) { + atomicStore(&wg_unwritten, 0u); + atomicStore(&wg_lit, 0u); + } + workgroupBarrier(); + if (g.x < w && g.y < h) { + let v = src[(y0 + g.y) * src_w + x0 + g.x]; + dst[g.y * stride + g.x] = v; + if ((v >> 24u) != 255u) { + atomicAdd(&wg_unwritten, 1u); + } + if ((v & 0xffffffu) != 0u) { + atomicAdd(&wg_lit, 1u); + } + } + workgroupBarrier(); + if (li == 0u) { + let u = atomicLoad(&wg_unwritten); + let l = atomicLoad(&wg_lit); + if (u > 0u) { + atomicAdd(&stats[0], u); + } + if (l > 0u) { + atomicAdd(&stats[1], l); + } + } +} diff --git a/crates/gpu/tests/texture.rs b/crates/gpu/tests/texture.rs new file mode 100644 index 00000000000..ef64e9b547b --- /dev/null +++ b/crates/gpu/tests/texture.rs @@ -0,0 +1,139 @@ +//! Issue #1228: renders on a device the window lends (`share_window_device`) reach the window as +//! textures, with no copy back to the CPU. The texture holds exactly the pixels the read-back +//! render returns, for a whole frame, a zoom window and a window that spots grew (and then cut +//! back), and a render that can't be trusted still falls back. +//! Its own test binary: the window's device has to be lent before anything creates the render +//! device. Skips (passes with a note) when no GPU adapter exists. + +use std::sync::Arc; + +use lightcraft_develop::{DevelopSettings, Spot}; +use lightcraft_geom::Point; +use lightcraft_gpu::{Fallback, Fault, GpuTexture}; +use lightcraft_pipeline::{Overlay, PixelWindow, RenderRequest, SourceInfo}; + +/// A device as the window creates it: the default backends, the adapter's limits. +fn window_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> { + let backends = lightcraft_gpu::backend::compute_backends()?; + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = backends; + let instance = wgpu::Instance::new(desc); + let adapter = pollster::block_on( + instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }), + ) + .ok()?; + let limits = lightcraft_gpu::window_device_limits(&adapter); + let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + label: Some("test window device"), + required_limits: limits, + ..Default::default() + })) + .ok()?; + Some((device, queue, adapter.get_info())) +} + +/// The texture's pixels, read back for the comparison. +fn pixels(device: &wgpu::Device, queue: &wgpu::Queue, t: &GpuTexture) -> Vec<[u8; 4]> { + let stride = (t.width * 4).div_ceil(256) * 256; + let buf = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: (stride * t.height) as u64, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut enc = device.create_command_encoder(&Default::default()); + enc.copy_texture_to_buffer( + t.texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &buf, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride as u32), rows_per_image: Some(t.height as u32) }, + }, + wgpu::Extent3d { width: t.width as u32, height: t.height as u32, depth_or_array_layers: 1 }, + ); + queue.submit([enc.finish()]); + let slice = buf.slice(..); + slice.map_async(wgpu::MapMode::Read, |r| r.expect("map")); + device.poll(wgpu::PollType::wait_indefinitely()).expect("poll"); + let data = slice.get_mapped_range().expect("mapped"); + let mut out = Vec::with_capacity(t.width * t.height); + for row in data.chunks(stride) { + out.extend(row[..t.width * 4].chunks_exact(4).map(|p| [p[0], p[1], p[2], p[3]])); + } + out +} + +#[test] +fn renders_reach_the_window_as_textures_identical_to_the_read_back_pixels() { + let Some((device, queue, info)) = window_device() else { + eprintln!("skipped: no GPU adapter"); + return; + }; + if info.device_type == wgpu::DeviceType::Cpu { + eprintln!("skipped: software adapter ({})", info.name); + return; + } + // before the device is lent, nothing renders into textures + let fit = RenderRequest::fit(900, 600); + assert!(!lightcraft_gpu::shares_window_device()); + assert!(!lightcraft_gpu::texture_handles(&fit)); + lightcraft_gpu::share_window_device(device.clone(), queue.clone(), info); + assert!(lightcraft_gpu::available(), "{:?}", lightcraft_gpu::unavailable_reason()); + assert!(lightcraft_gpu::shares_window_device(), "renders run on the lent device"); + assert!(lightcraft_gpu::texture_handles(&fit)); + + let src = Arc::new(lightcraft_scenes::demo_library()[0].render(960, 640)); + let srci = SourceInfo { raw: true, ..Default::default() }; + let mut s = DevelopSettings::default(); + s.light.exposure = 0.4; + s.effects.clarity = 25.0; + let mut spotted = s.clone(); + spotted.spots.push(Spot { + points: vec![Point::new(0.45, 0.45)], + size: 0.03, + feather: 30.0, + opacity: 100.0, + source_offset: Some(Point::new(0.15, 0.0)), + ..Default::default() + }); + // a window narrower than the copy alignment's 64 px and of an odd height: padded rows + let window = |x, y, w, h| RenderRequest { window: Some(PixelWindow { x, y, w, h }), ..RenderRequest::fit(3000, 2000) }; + let cases: [(&str, &DevelopSettings, RenderRequest); 4] = [ + ("whole frame", &s, fit), + ("zoom window", &s, window(1200, 800, 640, 480)), + ("narrow odd window", &s, window(1300, 900, 37, 51)), + ("window grown by a spot", &spotted, window(1200, 800, 640, 480)), + ]; + for (name, s, req) in &cases { + let read = lightcraft_gpu::try_render(&src, &srci, s, req, None).unwrap_or_else(|e| panic!("{name}: read-back render: {e:?}")); + let tex = lightcraft_gpu::try_render_texture(&src, &srci, s, req, None).unwrap_or_else(|e| panic!("{name}: texture render: {e:?}")); + assert_eq!((tex.width, tex.height), (read.image.width, read.image.height), "{name}: size"); + let got = pixels(&device, &queue, &tex); + let differ: Vec = got.iter().zip(&read.image.data).enumerate().filter(|(_, (a, b))| a != b).map(|(i, _)| i).collect(); + assert!( + differ.is_empty(), + "{name}: {} of {} pixels differ from the read-back ones, first at {:?}: {:?} vs {:?}", + differ.len(), + got.len(), + differ.first(), + differ.first().map(|&i| got[i]), + differ.first().map(|&i| read.image.data[i]) + ); + } + + // overlays are drawn on read-back pixels: not tried as a texture + let overlay = RenderRequest { overlay: Overlay::Spots(50), ..RenderRequest::fit(900, 600) }; + assert!(!lightcraft_gpu::texture_handles(&overlay)); + assert!(matches!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &overlay, None), Err(Fallback::NotTried))); + + // work that never ran is caught without the image coming back (simulated: this thread only) + lightcraft_gpu::inject_fault(Fault::DropWork); + match lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None) { + Err(Fallback::Failed(why)) => assert!(why.contains("incomplete"), "{why}"), + other => panic!("dropped work must fall back, got {:?}", other.err()), + } + lightcraft_gpu::reset_failures(); + // an output over the device limits falls back without a device error + lightcraft_gpu::inject_fault(Fault::Limit(1 << 20)); + assert!(matches!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None), Err(Fallback::Failed(_)))); + assert!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None).is_ok(), "a limit is no device failure"); +} From c7df7fd59ec50e3de01fa84a730ffbd0a5181866 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Mon, 12 Oct 2026 15:18:05 +0200 Subject: [PATCH 02/13] Fix macOS build: menu-bar Quit no longer calls eframe's on_exit (from #994) The change of PR #994, carried here because the device-lost recovery for drops out when that merges. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/main.rs | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 868112a97f5..4d6b0a3a2e2 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -69,7 +69,7 @@ impl eframe::App for App { // Quit from the menu bar: save exactly what closing the window saves (settings and // library, after the unsaved-changes check; otherwise its prompt shows), then end the // process instead of closing the viewport while AppKit is terminating (PR #444). - eframe::App::on_exit(self, None); + self.save_and_shut_down(); std::process::exit(0); } self.0.logic(ctx); @@ -85,6 +85,25 @@ impl eframe::App for App { self.0.ui(ui); } fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { + self.save_and_shut_down(); + // macOS (#1331): end the process here, before eframe tears the window down, as Quit from + // the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's + // content view and restores its class on teardown; AppKit's Touch Bar support observes + // that view (KVO), so in the next display cycle `-[_NSTouchBarFinderObservation + // invalidate]` throws "not registered" and closing the window ends in a crash report. + // Nothing after this is needed: settings and library are saved, background work has + // stopped and the log file is unbuffered. `on_exit` only runs once the app exists, so a + // renderer that fails to start still relaunches on the next one (`window_gpu`). + #[cfg(target_os = "macos")] + std::process::exit(0); + } +} + +impl App { + /// Save settings and the library, then wait for background work: closing the window, Quit + /// from the macOS menu bar, or starting again after a lost graphics device (which must not + /// end the process here, so the macOS exit stays in `on_exit`). + fn save_and_shut_down(&mut self) { // (a size the window was just given is remembered too) self.0.ui.window = self.1.window_at_exit(self.0.ui.window); if let Err(e) = self.1.save(&self.0) { @@ -97,16 +116,6 @@ impl eframe::App for App { if !self.0.shutdown(EXIT_WAIT) { log::warn!("quit: background work was still running after {EXIT_WAIT:?}"); } - // macOS (#1331): end the process here, before eframe tears the window down, as Quit from - // the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's - // content view and restores its class on teardown; AppKit's Touch Bar support observes - // that view (KVO), so in the next display cycle `-[_NSTouchBarFinderObservation - // invalidate]` throws "not registered" and closing the window ends in a crash report. - // Nothing after this is needed: settings and library are saved, background work has - // stopped and the log file is unbuffered. `on_exit` only runs once the app exists, so a - // renderer that fails to start still relaunches on the next one (`window_gpu`). - #[cfg(target_os = "macos")] - std::process::exit(0); } } From 77a33c717e1d10e219fbca300cec15a32a9d8f66 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Mon, 12 Oct 2026 15:20:36 +0200 Subject: [PATCH 03/13] LR-VIEW-ZOOM: zoom windows reach the screen as GPU textures, no readback; a lost device restarts (#1228) The desktop app lends the window's wgpu device to the renderer (requested with the adapter's limits), and the zoom windows of Detail, Before/After, Compare and Reference come back as textures on it: RenderJob::to_texture, RenderResult::texture, registered with egui-wgpu through render::NativeTextures. A display profile's per-channel curves are applied by the copy kernel; LUT profiles, overlays, the whole frame (its histogram), glow and LIGHTCRAFT_GPU_TEXTURES=0 keep read-back pixels. Headless screenshots read a texture back on demand (lightcraft_gpu::read_texture). 24 MP raw at 1:1, 30 Exposure steps on an M4 Max: 30.4 ms p50 per step (22-44) instead of 40.7 ms (36-71); the window's 44 MB CPU copy is gone. A lost device is lost to the window too, and egui-wgpu panics drawing anything on it: the app now draws empty frames, saves, and asks (native dialog) to restart or quit; a loss mid-frame ends run_native and the app starts again. Restarts use LIGHTCRAFT_GPU_TEXTURES=0. LIGHTCRAFT_GPU_LOSE_AFTER= reproduces a driver reset. Tests: texture.rs (texture == read-back pixels incl. padded rows, spot-grown windows, display curves; faults fall back), texture_lost.rs, and a window_gpu test that egui-wgpu draws empty frames on a lost device without a panic. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/main.rs | 29 +++ apps/lightcraft/src/window_gpu.rs | 189 +++++++++++++++++- crates/codecs/src/display.rs | 10 + crates/engine/src/import.rs | 1 + crates/engine/src/media.rs | 80 +++++++- crates/engine/src/slide_title.rs | 1 + crates/gpu/src/ctx.rs | 65 +++++- crates/gpu/src/lib.rs | 56 +++++- crates/gpu/src/render.rs | 29 ++- crates/gpu/src/wgsl/present.wgsl | 16 +- crates/gpu/tests/it/main.rs | 5 +- crates/gpu/tests/texture.rs | 35 +++- crates/gpu/tests/texture_lost.rs | 63 ++++++ .../ui-egui/examples/thumb_request_bench.rs | 11 +- crates/ui-egui/src/i18n.rs | 11 + crates/ui-egui/src/panels/compare.rs | 2 +- crates/ui-egui/src/panels/detail.rs | 3 +- crates/ui-egui/src/render.rs | 124 +++++++++++- crates/ui-egui/src/tests_lifecycle_037.rs | 9 +- docs/gpu-pipeline.md | 42 +++- docs/parity-checklist.md | 5 +- 21 files changed, 732 insertions(+), 54 deletions(-) create mode 100644 crates/gpu/tests/texture_lost.rs diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 4d6b0a3a2e2..ea755f7e22a 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -72,6 +72,18 @@ impl eframe::App for App { self.save_and_shut_down(); std::process::exit(0); } + // The window's device was lost (issue #1228: renders share it): nothing can be drawn on it + // again. Save, then restart or quit as the user answers (nothing else runs meanwhile). + if lightcraft_engine::gpu::window_device_lost() { + if let Some(restart) = window_gpu::device_lost_answer(ctx) { + self.save_and_shut_down(); + if restart { + window_gpu::relaunch_with_own_render_device(); + } + std::process::exit(0); + } + return; + } self.0.logic(ctx); self.1.tick(&mut self.0, ctx); } @@ -82,6 +94,11 @@ impl eframe::App for App { } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0); + // on a lost device, a frame with anything in it panics in egui-wgpu (its staging buffers + // can't be made): draw nothing until the restart (see `logic`) + if lightcraft_engine::gpu::window_device_lost() { + return; + } self.0.ui(ui); } fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { @@ -1017,6 +1034,9 @@ fn main() -> eframe::Result { // the window's renderer is up (eframe calls this after creating it) win_files_app.started(window_renderer); came_up_app.store(true, std::sync::atomic::Ordering::Relaxed); + // renders run on the window's device and reach it as textures (issue #1228): lent + // before anything can create a render device of its own + let window_textures = window_gpu::lend_device(cc.wgpu_render_state.as_ref()); let (mut session, mut problem) = open_session(in_memory, &launch, seed_demo && files.is_empty()); // AI masks: the SAM 3 checkpoint (facebook/sam3) in /models/sam3, or LIGHTCRAFT_SAM3_DIR // (never required: without it, AI masks offer to download it; see docs/ai-masks.md) @@ -1026,6 +1046,9 @@ fn main() -> eframe::Result { hdr_display::report(cc.wgpu_render_state.as_ref().map(|r| r.target_format)); let mut app = LightcraftApp::new(session, services(cc, app_log_file.as_deref())); app.set_startup_update_check(true); + if let Some(t) = window_textures { + app.renderer.set_native_textures(std::sync::Arc::new(t)); + } if let Some(ui) = prefs { app.ui = ui; } @@ -1117,6 +1140,12 @@ fn main() -> eframe::Result { // a panic that still escaped the renderer's start (the probe and error handler should // prevent it): an error like any other failed start let started = started.unwrap_or_else(|_| Err(eframe::Error::AppCreation("the window's renderer panicked while starting".into()))); + // the device renders share with the window was lost while a frame was being drawn (egui-wgpu + // panics there): not a failed start — start again, with renders on a device of their own + if started.is_err() && lightcraft_engine::gpu::window_device_lost() && window_gpu::relaunch_with_own_render_device() { + log::error!("LightCraft lost its graphics device while drawing; starting again"); + return Ok(()); + } if let Err(e) = &started { // the renderer never came up: start again, which tries the next one in the chain if window_gpu::relaunch_after_failure(&win_files) { diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index fefa65a5162..e6d9ccf97aa 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -149,10 +149,105 @@ pub fn base_options() -> WgpuConfiguration { n.instance_descriptor.backend_options = backend::backend_options(); // no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250) n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags); + // the adapter's limits, so renders can share the device and hand the window textures (#1228) + n.device_descriptor = std::sync::Arc::new(|adapter| wgpu::DeviceDescriptor { + label: Some("egui wgpu device"), + required_limits: lightcraft_engine::gpu::window_device_limits(adapter), + ..Default::default() + }); } c } +/// Renders that stay on the GPU (issue #1228), drawn through the window's egui-wgpu renderer: they +/// are made on its device ([`lend_device`]) and registered as its textures. +pub struct WindowTextures(eframe::egui_wgpu::RenderState); + +impl lightcraft_ui_egui::render::NativeTextures for WindowTextures { + fn register(&self, texture: &lightcraft_engine::gpu::GpuTexture) -> Option { + let view = texture.texture.create_view(&wgpu::TextureViewDescriptor::default()); + // linear filtering, clamped edges: what egui's own render textures use (`TextureOptions::LINEAR`) + Some(self.0.renderer.write().register_native_texture(&self.0.device, &view, wgpu::FilterMode::Linear)) + } + + fn free(&self, id: egui::TextureId) { + self.0.renderer.write().free_texture(&id); + } +} + +/// Lend the window's device to the GPU renderer, before anything renders: renders then come back +/// as textures on it, which [`WindowTextures`] (returned) draws. `None` with the glow renderer, +/// or when the window's adapter can't run the kernels — renders then keep a device of their own. +pub fn lend_device(render_state: Option<&eframe::egui_wgpu::RenderState>) -> Option { + // `LIGHTCRAFT_GPU_TEXTURES=0`: renders keep a device of their own and come back as pixels + // (a driver that misbehaves with a shared device; A/B measurements) + if std::env::var("LIGHTCRAFT_GPU_TEXTURES").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")) { + return None; + } + let rs = render_state?; + let info = rs.adapter.get_info(); + // (a software adapter: the CPU pipeline is faster; the render device refuses it too) + if info.device_type == wgpu::DeviceType::Cpu { + return None; + } + lightcraft_engine::gpu::share_window_device(rs.device.clone(), rs.queue.clone(), info); + Some(WindowTextures(rs.clone())) +} + +/// The answer to the lost-device dialog: `None` until it was shown, `Some(None)` while it is +/// open, then `Some(Some(restart))`. +static LOST_ANSWER: std::sync::Mutex>> = std::sync::Mutex::new(None); + +/// The window's device was lost (`lightcraft_engine::gpu::window_device_lost`; issue #1228): the +/// window can't draw on it again. Asks once, in a native dialog on its own thread (no GPU needed), +/// whether to restart or quit; `Some(restart)` once answered. Without a dialog to click away +/// (`LIGHTCRAFT_NO_PREFS`: tests, scripts) the answer is quit. +pub fn device_lost_answer(ctx: &egui::Context) -> Option { + let mut answer = LOST_ANSWER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(a) = *answer { + return a; + } + log::error!("window: the graphics device was lost; LightCraft can't draw its window any more"); + if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() { + *answer = Some(Some(false)); + return Some(false); + } + *answer = Some(None); + let ctx = ctx.clone(); + let asked = std::thread::Builder::new().name("device-lost".into()).spawn(move || { + let (title, text, restart, quit) = lightcraft_ui_egui::i18n::device_lost_message(); + let r = rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Error) + .set_title(title) + .set_description(text) + .set_buttons(rfd::MessageButtons::OkCancelCustom(restart.clone(), quit)) + .show(); + let again = matches!(&r, rfd::MessageDialogResult::Custom(b) if *b == restart) || r == rfd::MessageDialogResult::Ok; + *LOST_ANSWER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Some(again)); + ctx.request_repaint(); + }); + if asked.is_err() { + // no thread for the dialog: start again rather than leave a window that can't draw + *answer = Some(Some(true)); + return Some(true); + } + None +} + +/// Start LightCraft again after the window's device was lost, with the arguments it was started +/// with and renders on a device of their own (`LIGHTCRAFT_GPU_TEXTURES=0`): a driver that loses +/// shared devices can't take the new window down with a render. +pub fn relaunch_with_own_render_device() -> bool { + let Ok(exe) = std::env::current_exe() else { return false }; + log::warn!("window: starting again, renders on a device of their own"); + std::process::Command::new(exe) + .args(std::env::args_os().skip(1)) + .env("LIGHTCRAFT_GPU_TEXTURES", "0") + .spawn() + .map_err(|e| log::error!("window: could not start again: {e}")) + .is_ok() +} + /// The first renderer of `order` that probes cleanly (glow is taken without a probe). fn pick_probed(order: &[WindowRenderer], problems: &mut Vec) -> Option<(WindowRenderer, Option)> { for &r in order { @@ -187,10 +282,10 @@ fn probe(backends: Backends) -> Result { ..Default::default() })) .map_err(|e| format!("no adapter: {e}"))?; - let base = if adapter.get_info().backend == wgpu::Backend::Gl { wgpu::Limits::downlevel_webgl2_defaults() } else { wgpu::Limits::default() }; + // (as `base_options` asks: renders can share the device) let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { label: Some("egui wgpu device"), - required_limits: wgpu::Limits { max_texture_dimension_2d: 8192, ..base }, + required_limits: lightcraft_engine::gpu::window_device_limits(&adapter), ..Default::default() })) .map_err(|e| format!("{}: no device: {e}", adapter.get_info().name))?; @@ -334,4 +429,94 @@ mod tests { // outside a scope: logged by our handler, not a panic let _ = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl("not wgsl".into()) }); } + + /// Issue #1228: renders share the window's device, so a lost device (driver reset, GPU hang) + /// is lost to the window too. egui-wgpu panics drawing a frame with anything in it there (its + /// staging buffers can't be made), so the app draws empty frames once the device is lost and + /// offers a restart (`main.rs`). An empty frame — a render's native texture registered on the + /// lost device, textures uploaded, the frame recorded and submitted, textures freed — must + /// not panic. + #[test] + fn a_lost_window_device_draws_empty_frames_without_a_panic() { + use eframe::egui_wgpu::{Renderer, RendererOptions, ScreenDescriptor}; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: backend::window_backends(), + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let desc = wgpu::DeviceDescriptor { required_limits: lightcraft_engine::gpu::window_device_limits(&adapter), ..Default::default() }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&desc)) else { return }; + install_error_handler(&device); + let format = wgpu::TextureFormat::Bgra8Unorm; + let mut renderer = Renderer::new(&device, format, RendererOptions::default()); + let render = |size: u32| { + device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }) + }; + let shown = renderer.register_native_texture(&device, &render(64).create_view(&Default::default()), wgpu::FilterMode::Linear); + device.destroy(); + let _ = device.poll(wgpu::PollType::wait_indefinitely()); + // the next render arrives after the loss: registered on the lost device + let next = renderer.register_native_texture(&device, &render(64).create_view(&Default::default()), wgpu::FilterMode::Linear); + let managed = egui::TextureId::Managed(7); + let delta = egui::epaint::ImageDelta::full(egui::ColorImage::new([8, 8], vec![egui::Color32::GRAY; 64]), egui::TextureOptions::LINEAR); + renderer.update_texture(&device, &queue, managed, &delta); + let mut mesh = egui::Mesh::with_texture(next); + let r = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(64.0, 64.0)); + mesh.add_rect_with_uv(r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); + let shapes = [egui::epaint::ClippedPrimitive { clip_rect: r, primitive: egui::epaint::Primitive::Mesh(mesh) }]; + let screen = ScreenDescriptor { size_in_pixels: [64, 64], pixels_per_point: 1.0 }; + // what the app must not draw on a lost device (should egui-wgpu stop panicking here, the + // empty frames in `main.rs` can go) + let drawn = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let mut enc = device.create_command_encoder(&Default::default()); + renderer.update_buffers(&device, &queue, &mut enc, &shapes, &screen) + })); + assert!(drawn.is_err(), "egui-wgpu draws on a lost device now"); + let jobs: [egui::epaint::ClippedPrimitive; 0] = []; + let mut enc = device.create_command_encoder(&Default::default()); + let user = renderer.update_buffers(&device, &queue, &mut enc, &jobs, &screen); + let target = device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 64, height: 64, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }); + let view = target.create_view(&Default::default()); + { + let pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor { + label: None, + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + depth_slice: None, + resolve_target: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + renderer.render(&mut pass.forget_lifetime(), &jobs, &screen); + } + queue.submit(user.into_iter().chain([enc.finish()])); + renderer.free_texture(&shown); + renderer.free_texture(&next); + renderer.free_texture(&managed); + } } diff --git a/crates/codecs/src/display.rs b/crates/codecs/src/display.rs index e26e6ab6ecc..8d263b735ba 100644 --- a/crates/codecs/src/display.rs +++ b/crates/codecs/src/display.rs @@ -169,6 +169,16 @@ impl DisplayProfile { !matches!(self.correction, Correction::None) } + /// What [`correct`](Self::correct) does when it is per-channel tables (a matrix/TRC profile + /// whose curves aren't sRGB's): output = `t[channel][input]`. `None` when it does nothing or + /// a full CMS transform. Lets a GPU render apply the correction itself (issue #1228). + pub fn correction_curves(&self) -> Option<&[[u8; 256]; 3]> { + match &self.correction { + Correction::Curves(t) => Some(t), + _ => None, + } + } + /// A render in the display's primaries with the sRGB curve (the pipeline's display target) → /// the display's device values, in place. pub fn correct(&self, img: &mut Rgba8) -> Result<(), String> { diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index bb81bd24071..90de8e74eff 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -1619,6 +1619,7 @@ impl Session { display: None, slide: None, preview_cut: None, + texture: false, display_fit: None, }; let embedded = match (&self.media.preview_loader, c.kind) { diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index e76ef816916..a6f0a2942bc 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -784,6 +784,9 @@ pub struct RenderJob { /// A face tile that can be cut from the raw's embedded preview, tried before `source` /// ([`crate::Session::face_job`]; `None` for every other job). pub preview_cut: Option, + /// Hand the result over as a texture on the window's device when the GPU can + /// ([`Self::to_texture`]). + pub texture: bool, /// Shrink a full-quality result to fit this size (physical pixels) with a Lanczos filter once /// it is rendered. The loupe renders a little larger than it is drawn (its edge is rounded up /// to a 64 px step) and the window would otherwise shrink the texture with 2-tap bilinear sampling, which blurs fine detail at @@ -821,6 +824,9 @@ pub struct RenderResult { /// The display profile (id) the image is encoded for; `None`: sRGB (see /// [`crate::display::present`]). pub display: Option, + /// The result as a texture on the window's device ([`RenderJob::to_texture`]); `rendered` is + /// then an empty image with an empty histogram. + pub texture: Option, } impl RenderJob { @@ -893,6 +899,28 @@ impl RenderJob { self } + /// Hand the result over as a texture on the window's device, with no copy of its pixels back + /// to the CPU (issue #1228), when the GPU renders it and nothing needs the pixels: a view + /// that only draws them (the loupe's zoom window), with no overlay, nothing cached and no + /// display correction left to apply on the CPU. Otherwise the job renders as before. The + /// result is the same image, so the key stays. + pub fn to_texture(mut self, on: bool) -> Self { + self.texture = on; + self + } + + /// Whether this job can render into a texture ([`Self::to_texture`]) at all. + fn texture_wanted(&self) -> bool { + self.texture + && self.cache.is_none() + && self.slide.is_none() + && self.view_cache.is_none() + && self.display_fit.is_none() + && self.display.as_ref().is_none_or(|d| !d.profile.needs_correction() || d.profile.correction_curves().is_some()) + && gpu_takes(&self.settings, &self.request) + && lightcraft_gpu::texture_handles(&self.request) + } + /// Reuse `stages` across this view's renders. pub fn with_stages(mut self, stages: Arc) -> Self { self.stages = Some(stages); @@ -936,6 +964,7 @@ impl RenderJob { loaded: None, quick: None, display: None, + texture: None, } } @@ -979,6 +1008,7 @@ impl RenderJob { loaded: None, quick: None, display: None, + texture: None, }; } // a face tile of an unedited raw: cut from the camera's embedded preview when it is big enough @@ -999,9 +1029,11 @@ impl RenderJob { loaded: None, quick: None, display: None, + texture: None, }; } let was_loaded = matches!(self.source, SourceRef::Loaded(_)); + let want_texture = self.texture_wanted(); // The app is closing (issue #620): nobody is left to show this, and quitting waits for the // jobs that are running. Without this, one that lost the GPU mid-way would render on the CPU. let closing = || lightcraft_gpu::shutting_down().then(|| "LightCraft is closing".to_string()); @@ -1017,7 +1049,36 @@ impl RenderJob { // Thumbnails (many small jobs side by side) stay on the CPU; views and exports use // the GPU when there is one. let gpu = self.cache.is_none(); + // a view that only draws the result: a texture on the window's device, no readback + let mut texture_fallback = None; + if want_texture { + // the display's curves, when they aren't sRGB's: applied on the GPU too + let curves = self.display.as_ref().and_then(|d| d.profile.correction_curves()); + match lightcraft_gpu::try_render_texture(src, &info, &self.settings, &self.request, self.stages.as_deref(), curves) { + Ok(t) => { + let empty = Rgba8 { width: 0, height: 0, data: Vec::new() }; + let histogram = Histogram::of_srgb8(&empty); + return RenderResult { + request_id: self.request_id, + source_key: self.source_key, + photo: self.photo, + level: self.level, + key: self.key, + rendered: Ok(Rendered { image: empty, histogram, deep: None }), + gpu_fallback: None, + loaded: (!was_loaded).then_some(source), + quick: None, + // rendered into the display's primaries, and its curve is sRGB's + display: self.display.as_ref().filter(|_| self.request.display.is_some()).map(|d| d.id()), + texture: Some(t), + }; + } + Err(lightcraft_gpu::Fallback::Failed(why)) => texture_fallback = Some(why), + Err(lightcraft_gpu::Fallback::NotTried) => {} + } + } let (mut rendered, gpu_fallback) = develop_reporting(src, &info, &self.settings, &self.request, self.stages.as_deref(), gpu); + let gpu_fallback = texture_fallback.or(gpu_fallback); // for a display profile: the image goes to the display's values, the histogram // and the cached view preview stay sRGB let mut srgb = None; @@ -1063,6 +1124,7 @@ impl RenderJob { loaded: (!was_loaded).then_some(source), quick: None, display, + texture: None, } } Err(e) => self.failed(e), @@ -1096,6 +1158,12 @@ pub fn develop_reporting( (rendered, fallback) } +/// Whether a view's render is tried on the GPU at all: LUT profiles and refined masks have no GPU +/// stage, and soft proofs render on the CPU. +fn gpu_takes(s: &DevelopSettings, req: &RenderRequest) -> bool { + !lightcraft_pipeline::lut::is_lut_profile(&s.profile.id) && !s.masks.iter().any(|m| m.visible && m.refine > 0.0) && req.proof.is_none() +} + fn develop_image( src: &Arc, info: &SourceInfo, @@ -1104,12 +1172,7 @@ fn develop_image( stages: Option<&StageCache>, gpu: bool, ) -> (Rendered, Option) { - // LUT profiles have no GPU stage: they render on the CPU - let fallback = if gpu - && !lightcraft_pipeline::lut::is_lut_profile(&s.profile.id) - && !s.masks.iter().any(|m| m.visible && m.refine > 0.0) - && req.proof.is_none() - { + let fallback = if gpu && gpu_takes(s, req) { match lightcraft_gpu::try_render(src, info, s, req, stages) { Ok(r) => return (r, None), Err(lightcraft_gpu::Fallback::Failed(why)) => Some(why), @@ -1168,6 +1231,7 @@ impl QuickJob { loaded: None, quick: None, display: None, + texture: None, }) } @@ -1185,6 +1249,7 @@ impl QuickJob { loaded: None, quick, display: None, + texture: None, }; let rendered = |image: Rgba8| { let histogram = Histogram::of_srgb8(&image); @@ -1329,6 +1394,7 @@ impl crate::Session { display: None, slide: None, preview_cut: None, + texture: false, display_fit: None, }) } @@ -1383,6 +1449,7 @@ impl crate::Session { display: None, slide: None, preview_cut: None, + texture: false, display_fit: None, }) } @@ -1438,6 +1505,7 @@ impl crate::Session { display: None, slide: None, preview_cut, + texture: false, display_fit: None, }) } diff --git a/crates/engine/src/slide_title.rs b/crates/engine/src/slide_title.rs index 5885463b1c5..1fae5623eab 100644 --- a/crates/engine/src/slide_title.rs +++ b/crates/engine/src/slide_title.rs @@ -363,6 +363,7 @@ impl TitleCompose { quick: None, display: None, gpu_fallback: None, + texture: None, } } } diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 1af04602eeb..9c605e99c6d 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -71,7 +71,7 @@ const MODULES: &[Module] = &[ }, Module { src: include_str!("wgsl/present.wgsl"), - bindings: &[("src", false, "u32"), ("dst", true, "u32"), ("stats", true, "atomic")], + bindings: &[("src", false, "u32"), ("dst", true, "u32"), ("stats", true, "atomic"), ("curves", false, "u32")], entries: &["pad_rows"], }, ]; @@ -365,10 +365,15 @@ impl Gpu { })); // wgpu reports a lost device (driver reset, GPU hang, watchdog) only here — never as an // error — so without this callback a lost device went unnoticed. - device.set_device_lost_callback(|reason, msg| { + // On the window's device the window loses it too (it can't draw again until restarted): + // `window_device_lost` tells the app. + device.set_device_lost_callback(move |reason, msg| { DEVICE_LOST.store(true, Ordering::Relaxed); - log::error!("gpu: device lost ({reason:?}): {msg}"); + log::error!("{what}: device lost ({reason:?}): {msg}"); crate::mark_broken(&format!("device lost ({reason:?}): {msg}")); + if shared { + crate::WINDOW_LOST.store(true, std::sync::atomic::Ordering::Relaxed); + } }); // a kernel the driver's compiler refuses is a validation or an internal error: no GPU, not a half-built one let scopes = [device.push_error_scope(wgpu::ErrorFilter::Validation), device.push_error_scope(wgpu::ErrorFilter::Internal)]; @@ -657,6 +662,60 @@ impl Gpu { } } +impl Gpu { + /// The pixels of an `Rgba8Unorm` texture on this device (a render handed to the window, read + /// back for a screenshot), or why not. + pub fn read_texture(&self, texture: &wgpu::Texture) -> Result { + let (w, h) = (texture.width() as usize, texture.height() as usize); + if texture.format() != wgpu::TextureFormat::Rgba8Unorm || !texture.usage().contains(wgpu::TextureUsages::COPY_SRC) { + return Err("not a render texture".into()); + } + let stride = (w * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize; + let size = (stride * h) as u64; + if size == 0 || size > self.device.limits().max_buffer_size { + return Err(format!("a {w}×{h} texture can't be read back")); + } + let staging = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("texture readback"), + size, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut enc = self.encoder(); + enc.copy_texture_to_buffer( + texture.as_image_copy(), + wgpu::TexelCopyBufferInfo { + buffer: &staging, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride as u32), rows_per_image: Some(h as u32) }, + }, + wgpu::Extent3d { width: w as u32, height: h as u32, depth_or_array_layers: 1 }, + ); + self.queue.submit([enc.finish()]); + let slice = staging.slice(..); + let (tx, rx) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |r| { + let _ = tx.send(r); + }); + self.device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(READBACK_TIMEOUT) }).map_err(|e| e.to_string())?; + match rx.recv_timeout(std::time::Duration::from_secs(10)) { + Ok(Ok(())) => {} + Ok(Err(e)) => return Err(e.to_string()), + Err(e) => return Err(format!("map callback: {e}")), + } + let data = slice.get_mapped_range().map_err(|e| format!("{e:?}"))?; + let mut out = Vec::with_capacity(w * h); + for row in data.chunks(stride) { + out.extend_from_slice(row.get(..w * 4).unwrap_or_default().as_chunks::<4>().0); + } + drop(data); + staging.unmap(); + if out.len() != w * h { + return Err("the texture came back incomplete".into()); + } + Ok(lightcraft_raster::Rgba8 { width: w, height: h, data: out }) + } +} + /// Longest wait for a render's GPU work: beyond it the render fails over to the CPU (drivers /// normally reset a hung GPU much sooner). const READBACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 9b773413efc..519bcfa1ccc 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -306,6 +306,18 @@ pub fn window_device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { wgpu::Limits { max_texture_dimension_2d: limits.max_texture_dimension_2d.max(8192), ..limits } } +/// Set when the device lent by [`share_window_device`] was lost (driver reset, GPU hang). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +static WINDOW_LOST: AtomicBool = AtomicBool::new(false); + +/// Whether the window's device, lent to renders ([`share_window_device`]), was lost: renders +/// have gone back to the CPU, but the window can't draw on it again either. The app then offers +/// a restart (with a device of its own for renders: `LIGHTCRAFT_GPU_TEXTURES=0`). A device lost +/// while renders had their own leaves the window alone, and this stays false. +pub fn window_device_lost() -> bool { + WINDOW_LOST.load(Ordering::Relaxed) +} + /// Whether renders run on the window's device, so [`try_render_texture`] can hand them over /// without a readback. Never creates the device. pub fn shares_window_device() -> bool { @@ -569,13 +581,15 @@ pub fn texture_handles(req: &RenderRequest) -> bool { /// [`try_render`] into a texture on the window's device, with no copy of the image back to the /// CPU (issue #1228): for views that only draw it, such as the loupe's zoom window. There is no /// histogram. [`Fallback::NotTried`] when [`texture_handles`] says no; the caller then renders -/// with [`try_render`] (or on the CPU). +/// with [`try_render`] (or on the CPU). `curves`: a display profile's per-channel correction +/// ([`lightcraft_codecs`' `DisplayProfile::correction_curves`]), applied on the way into the texture. pub fn try_render_texture( src: &Arc, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>, + curves: Option<&[[u8; 256]; 3]>, ) -> Result { #[cfg(not(target_arch = "wasm32"))] { @@ -588,17 +602,48 @@ pub fn try_render_texture( stages, |t: &GpuTexture| (t.width, t.height), |gpu, s, ext, fault| { - if gpu.shared { render::render_texture(gpu, src, info, s, req, ext, fault) } else { None } + if gpu.shared { render::render_texture(gpu, src, info, s, req, ext, fault, curves) } else { None } }, ) } #[cfg(target_arch = "wasm32")] { - let _ = (src, info, s, req, stages); + let _ = (src, info, s, req, stages, curves); Err(Fallback::NotTried) } } +/// The pixels of a render handed over as a texture ([`try_render_texture`]), read back from the +/// device: for what can't draw it there (a headless screenshot). `None` once the device is gone. +pub fn read_texture(t: &GpuTexture) -> Option { + #[cfg(not(target_arch = "wasm32"))] + { + let _work = exit::enter()?; + let gpu = existing_device()?; + gpu.read_texture(&t.texture).map_err(|e| log::warn!("gpu: reading a render texture back: {e}")).ok() + } + #[cfg(target_arch = "wasm32")] + { + let _ = t; + None + } +} + +/// `LIGHTCRAFT_GPU_LOSE_AFTER=`: after `n` GPU renders the device is destroyed, as a driver +/// reset or GPU hang loses it — to see the app recover (renders back on the CPU; with a device +/// shared with the window, the restart it offers). A testing switch, like `LIGHTCRAFT_GPU_LIMITS`. +#[cfg(not(target_arch = "wasm32"))] +fn lose_device_when_asked(gpu: &ctx::Gpu) { + static AFTER: std::sync::OnceLock> = std::sync::OnceLock::new(); + static DONE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let Some(n) = *AFTER.get_or_init(|| std::env::var("LIGHTCRAFT_GPU_LOSE_AFTER").ok().and_then(|v| v.trim().parse().ok())) else { return }; + if DONE.fetch_add(1, Ordering::Relaxed) + 1 == n { + log::warn!("gpu: LIGHTCRAFT_GPU_LOSE_AFTER={n}: destroying the device"); + gpu.device.destroy(); + let _ = gpu.device.poll(wgpu::PollType::Poll); + } +} + /// Run `go` on the GPU with the render's settings, error scopes and failure accounting: its /// result, or why the CPU must render instead. `size` names a result in a failure's reason. #[cfg(not(target_arch = "wasm32"))] @@ -672,7 +717,10 @@ fn attempt( (Ok(Some(_)), None) if BROKEN.load(Ordering::Relaxed) => { format!("device failure during the render: {}", unavailable_reason().unwrap_or_default()) } - (Ok(Some(r)), None) => return Ok(r), + (Ok(Some(r)), None) => { + lose_device_when_asked(gpu); + return Ok(r); + } // every path of `render::render` that gives up records a failure first; should one // not, the CPU renders it rather than nothing (Ok(None), None) => "GPU render: no image came back".to_string(), diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 8aa1d794390..683e6dba178 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -586,14 +586,15 @@ pub fn render( stages: Option<&GpuStages>, fault: Option, ) -> Option { - match render_as(gpu, src, info, s, req, stages, fault, false)? { + match render_as(gpu, src, info, s, req, stages, fault, None)? { Made::Pixels(r) => Some(r), Made::Texture(_) => None, } } /// [`render`] into a texture on the window's device (issue #1228): no copy back to the CPU, no -/// histogram and no overlay (the caller asks [`crate::texture_handles`] first). +/// histogram and no overlay (the caller asks [`crate::texture_handles`] first). `curves`: a +/// display profile's per-channel correction, applied on the way into the texture. #[allow(clippy::too_many_arguments)] pub fn render_texture( gpu: &Gpu, @@ -603,8 +604,9 @@ pub fn render_texture( req: &RenderRequest, stages: Option<&GpuStages>, fault: Option, + curves: Option<&[[u8; 256]; 3]>, ) -> Option { - match render_as(gpu, src, info, s, req, stages, fault, true)? { + match render_as(gpu, src, info, s, req, stages, fault, Some(curves))? { Made::Texture(t) => Some(t), Made::Pixels(_) => None, } @@ -625,7 +627,7 @@ fn render_as( req: &RenderRequest, stages: Option<&GpuStages>, fault: Option, - texture: bool, + texture: Option>, ) -> Option { let mut t = profiling().then(std::time::Instant::now); // Each stage is submitted on its own; under `LIGHTCRAFT_PROFILE` also waited for, so the @@ -752,8 +754,8 @@ fn render_as( groups2(w, rows.min(h - y0), [16, 16]), ); } - if texture { - let made = to_texture(&mut cx, &out, w, h, plan.keep.map(|k| (k.x, k.y, k.w, k.h))); + if let Some(curves) = texture { + let made = to_texture(&mut cx, &out, w, h, plan.keep.map(|k| (k.x, k.y, k.w, k.h)), curves); lap("finish + present", &mut t, &mut cx); return made.map(Made::Texture); } @@ -833,7 +835,14 @@ fn render_as( /// RGBA8 output `out` into a new texture, with the checks the read-back path runs on the CPU: a /// pixel the per-pixel kernel never wrote fails the render, an entirely black one is redone on the /// CPU. Only two counters come back from the device. -fn to_texture(cx: &mut Cx<'_>, out: &Buf, w: usize, h: usize, keep: Option<(usize, usize, usize, usize)>) -> Option { +fn to_texture( + cx: &mut Cx<'_>, + out: &Buf, + w: usize, + h: usize, + keep: Option<(usize, usize, usize, usize)>, + curves: Option<&[[u8; 256]; 3]>, +) -> Option { let gpu = cx.gpu; let (x0, y0, kw, kh) = keep.unwrap_or((0, 0, w, h)); // a crop past the output would read past `out`: never expected, but not a reason to crash @@ -850,8 +859,10 @@ fn to_texture(cx: &mut Cx<'_>, out: &Buf, w: usize, h: usize, keep: Option<(usiz let stride = kw.div_ceil(align) * align; let padded = cx.gpu.buffer(stride * kh); let stats = cx.zeroed(2); - let p = [w as u32, x0 as u32, y0 as u32, kw as u32, kh as u32, stride as u32]; - cx.run("pad_rows", &p, &[Some(out), Some(&padded), Some(&stats)], groups2(kw, kh, [16, 16])); + // the display's per-channel tables, one word per entry + let tables = curves.map(|c| gpu.upload(&c.iter().flatten().map(|v| *v as u32).collect::>())); + let p = [w as u32, x0 as u32, y0 as u32, kw as u32, kh as u32, stride as u32, curves.is_some() as u32]; + cx.run("pad_rows", &p, &[Some(out), Some(&padded), Some(&stats), tables.as_ref()], groups2(kw, kh, [16, 16])); if crate::ctx::failed() { return None; } diff --git a/crates/gpu/src/wgsl/present.wgsl b/crates/gpu/src/wgsl/present.wgsl index 7645221766f..51b3c908397 100644 --- a/crates/gpu/src/wgsl/present.wgsl +++ b/crates/gpu/src/wgsl/present.wgsl @@ -2,8 +2,11 @@ // per-pixel stage's packed RGBA8 output into rows padded for a buffer-to-texture copy, and count // what the CPU path checks on the read-back image (`render::render`): pixels the kernel never // wrote (alpha other than 255) and pixels that are not black. -// P: src_w, x0, y0, w, h (the kept part), stride (words per padded row). Bindings: src, dst, stats -// (stats[0] = unwritten, stats[1] = not black; cleared by the caller). +// With a display profile whose curves aren't sRGB's, the copy also applies its per-channel tables +// (what `DisplayProfile::correct` does on the CPU): curves[c * 256 + v]. +// P: src_w, x0, y0, w, h (the kept part), stride (words per padded row), curved (0/1). Bindings: +// src, dst, stats (stats[0] = unwritten, stats[1] = not black, of the render before the curves; +// cleared by the caller), curves. var wg_unwritten: atomic; var wg_lit: atomic; @@ -23,7 +26,14 @@ fn pad_rows(@builtin(global_invocation_id) g: vec3, @builtin(local_invocati workgroupBarrier(); if (g.x < w && g.y < h) { let v = src[(y0 + g.y) * src_w + x0 + g.x]; - dst[g.y * stride + g.x] = v; + var o = v; + if (pu(6u) != 0u) { + let r = curves[v & 0xffu]; + let gr = curves[256u + ((v >> 8u) & 0xffu)]; + let b = curves[512u + ((v >> 16u) & 0xffu)]; + o = (v & 0xff000000u) | (b << 16u) | (gr << 8u) | r; + } + dst[g.y * stride + g.x] = o; if ((v >> 24u) != 255u) { atomicAdd(&wg_unwritten, 1u); } diff --git a/crates/gpu/tests/it/main.rs b/crates/gpu/tests/it/main.rs index d26d1efc94d..3a1ee12eed5 100644 --- a/crates/gpu/tests/it/main.rs +++ b/crates/gpu/tests/it/main.rs @@ -1,7 +1,8 @@ //! The integration tests, one module per file, linked into one test binary. //! Binaries of their own: `tests/shutdown.rs` and `tests/shutdown_first.rs` close the GPU for the whole -//! process, and `tests/memory.rs` checks the process's device-memory counters, which renders on other test -//! threads would change. +//! process, `tests/memory.rs` checks the process's device-memory counters, which renders on other test +//! threads would change, and `tests/texture.rs` and `tests/texture_lost.rs` lend a window device before +//! anything creates the render device (issue #1228). mod equivalence; mod fallback; diff --git a/crates/gpu/tests/texture.rs b/crates/gpu/tests/texture.rs index ef64e9b547b..48998fefa94 100644 --- a/crates/gpu/tests/texture.rs +++ b/crates/gpu/tests/texture.rs @@ -32,7 +32,7 @@ fn window_device() -> Option<(wgpu::Device, wgpu::Queue, wgpu::AdapterInfo)> { Some((device, queue, adapter.get_info())) } -/// The texture's pixels, read back for the comparison. +/// The texture's pixels, read back for the comparison (independently of `read_texture`). fn pixels(device: &wgpu::Device, queue: &wgpu::Queue, t: &GpuTexture) -> Vec<[u8; 4]> { let stride = (t.width * 4).div_ceil(256) * 256; let buf = device.create_buffer(&wgpu::BufferDescriptor { @@ -57,7 +57,7 @@ fn pixels(device: &wgpu::Device, queue: &wgpu::Queue, t: &GpuTexture) -> Vec<[u8 let data = slice.get_mapped_range().expect("mapped"); let mut out = Vec::with_capacity(t.width * t.height); for row in data.chunks(stride) { - out.extend(row[..t.width * 4].chunks_exact(4).map(|p| [p[0], p[1], p[2], p[3]])); + out.extend_from_slice(row[..t.width * 4].as_chunks::<4>().0); } out } @@ -105,7 +105,7 @@ fn renders_reach_the_window_as_textures_identical_to_the_read_back_pixels() { ]; for (name, s, req) in &cases { let read = lightcraft_gpu::try_render(&src, &srci, s, req, None).unwrap_or_else(|e| panic!("{name}: read-back render: {e:?}")); - let tex = lightcraft_gpu::try_render_texture(&src, &srci, s, req, None).unwrap_or_else(|e| panic!("{name}: texture render: {e:?}")); + let tex = lightcraft_gpu::try_render_texture(&src, &srci, s, req, None, None).unwrap_or_else(|e| panic!("{name}: texture render: {e:?}")); assert_eq!((tex.width, tex.height), (read.image.width, read.image.height), "{name}: size"); let got = pixels(&device, &queue, &tex); let differ: Vec = got.iter().zip(&read.image.data).enumerate().filter(|(_, (a, b))| a != b).map(|(i, _)| i).collect(); @@ -118,22 +118,43 @@ fn renders_reach_the_window_as_textures_identical_to_the_read_back_pixels() { differ.first().map(|&i| got[i]), differ.first().map(|&i| read.image.data[i]) ); + // what a headless screenshot reads back + assert_eq!(lightcraft_gpu::read_texture(&tex).map(|i| i.data), Some(got), "{name}: read_texture"); } + // a display profile's per-channel curves are applied on the way into the texture, as + // `DisplayProfile::correct` applies them on the CPU (a different table per channel) + let mut curves = [[0u8; 256]; 3]; + for (c, t) in curves.iter_mut().enumerate() { + for (i, v) in t.iter_mut().enumerate() { + *v = match c { + 0 => 255 - i as u8, + 1 => ((i as f32 / 255.0).powf(1.8) * 255.0).round() as u8, + _ => (i as u8).saturating_add(17), + }; + } + } + let req = window(1200, 800, 640, 480); + let read = lightcraft_gpu::try_render(&src, &srci, &s, &req, None).expect("read-back render"); + let want: Vec<[u8; 4]> = + read.image.data.iter().map(|p| [curves[0][p[0] as usize], curves[1][p[1] as usize], curves[2][p[2] as usize], p[3]]).collect(); + let tex = lightcraft_gpu::try_render_texture(&src, &srci, &s, &req, None, Some(&curves)).expect("texture render with curves"); + assert!(pixels(&device, &queue, &tex) == want, "the display curves differ from the CPU's"); + // overlays are drawn on read-back pixels: not tried as a texture let overlay = RenderRequest { overlay: Overlay::Spots(50), ..RenderRequest::fit(900, 600) }; assert!(!lightcraft_gpu::texture_handles(&overlay)); - assert!(matches!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &overlay, None), Err(Fallback::NotTried))); + assert!(matches!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &overlay, None, None), Err(Fallback::NotTried))); // work that never ran is caught without the image coming back (simulated: this thread only) lightcraft_gpu::inject_fault(Fault::DropWork); - match lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None) { + match lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None, None) { Err(Fallback::Failed(why)) => assert!(why.contains("incomplete"), "{why}"), other => panic!("dropped work must fall back, got {:?}", other.err()), } lightcraft_gpu::reset_failures(); // an output over the device limits falls back without a device error lightcraft_gpu::inject_fault(Fault::Limit(1 << 20)); - assert!(matches!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None), Err(Fallback::Failed(_)))); - assert!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None).is_ok(), "a limit is no device failure"); + assert!(matches!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None, None), Err(Fallback::Failed(_)))); + assert!(lightcraft_gpu::try_render_texture(&src, &srci, &s, &fit, None, None).is_ok(), "a limit is no device failure"); } diff --git a/crates/gpu/tests/texture_lost.rs b/crates/gpu/tests/texture_lost.rs new file mode 100644 index 00000000000..179976ecf60 --- /dev/null +++ b/crates/gpu/tests/texture_lost.rs @@ -0,0 +1,63 @@ +//! Issue #1228: when renders share the window's device and that device is lost (a driver reset, +//! a GPU hang; simulated with `Device::destroy`), nothing panics: renders go back to the CPU, +//! reading a texture back gives nothing, textures already handed over drop cleanly, and +//! `window_device_lost` tells the app that the window needs a restart. +//! Its own test binary: it lends a device before anything creates one. Skips without a GPU. + +use std::sync::Arc; + +use lightcraft_develop::DevelopSettings; +use lightcraft_gpu::Fallback; +use lightcraft_pipeline::{RenderRequest, SourceInfo}; + +#[test] +fn a_lost_window_device_falls_back_without_a_panic() { + let Some(backends) = lightcraft_gpu::backend::compute_backends() else { return }; + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = backends; + let instance = wgpu::Instance::new(desc); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { + eprintln!("skipped: no GPU adapter"); + return; + }; + if adapter.get_info().device_type == wgpu::DeviceType::Cpu { + eprintln!("skipped: software adapter"); + return; + } + let desc = wgpu::DeviceDescriptor { required_limits: lightcraft_gpu::window_device_limits(&adapter), ..Default::default() }; + let (device, queue) = pollster::block_on(adapter.request_device(&desc)).expect("device"); + lightcraft_gpu::share_window_device(device.clone(), queue.clone(), adapter.get_info()); + // (creates the render device on the lent one, as the app's start-up check does) + assert!(lightcraft_gpu::available() && lightcraft_gpu::shares_window_device()); + + let src = Arc::new(lightcraft_scenes::demo_library()[0].render(640, 420)); + let info = SourceInfo { raw: true, ..Default::default() }; + let s = DevelopSettings::default(); + let req = RenderRequest::fit(640, 420); + let shown = lightcraft_gpu::try_render_texture(&src, &info, &s, &req, None, None).expect("a texture before the loss"); + assert!(!lightcraft_gpu::window_device_lost()); + + device.destroy(); + let _ = device.poll(wgpu::PollType::wait_indefinitely()); + // (the lost-device callback runs from a poll) + for _ in 0..100 { + if lightcraft_gpu::window_device_lost() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + let _ = device.poll(wgpu::PollType::Poll); + } + assert!(lightcraft_gpu::window_device_lost(), "the app is told the window's device is gone"); + assert!(lightcraft_gpu::unavailable_reason().is_some_and(|r| r.contains("lost")), "{:?}", lightcraft_gpu::unavailable_reason()); + assert!(!lightcraft_gpu::texture_handles(&req) || !lightcraft_gpu::enabled()); + + // renders are not tried on the GPU again: the CPU renders them, as pixels + assert!(matches!(lightcraft_gpu::try_render_texture(&src, &info, &s, &req, None, None), Err(Fallback::NotTried))); + assert!(matches!(lightcraft_gpu::try_render(&src, &info, &s, &req, None), Err(Fallback::NotTried))); + let cpu = lightcraft_pipeline::render(&src, &info, &s, &req); + assert_eq!((cpu.image.width, cpu.image.height), (shown.width, shown.height)); + // a screenshot of what was on screen finds nothing to read, without a panic + assert!(lightcraft_gpu::read_texture(&shown).is_none()); + lightcraft_gpu::trim_pool(0); + drop(shown); +} diff --git a/crates/ui-egui/examples/thumb_request_bench.rs b/crates/ui-egui/examples/thumb_request_bench.rs index 166c0e9b62c..f36eca92a90 100644 --- a/crates/ui-egui/examples/thumb_request_bench.rs +++ b/crates/ui-egui/examples/thumb_request_bench.rs @@ -113,7 +113,16 @@ fn micro(points: usize, pending: bool) { let key = app.session.thumb_job(id, 384).unwrap().key; app.renderer.textures.insert( Slot::Thumb(id), - Tex { key, photo: id, tex: texture.clone(), size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, + Tex { + key, + photo: id, + tex: lightcraft_ui_egui::render::TexImage::Managed(texture.clone()), + size: [1, 1], + histogram: None, + ms: 0.0, + quick: None, + pixels: None, + }, ); } request_thumb(&mut app, id, 384, 10); diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 9ba1cd5afb3..a990dea4d42 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -345,6 +345,17 @@ pub fn upper_first(text: &str) -> String { } } +/// The native dialog shown when the window's graphics device was lost mid-session (issue #1228): +/// title, text, and the two buttons (restart, quit). +pub fn device_lost_message() -> (String, String, String, String) { + ( + tr("LightCraft lost its graphics device").to_string(), + tr("The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.").to_string(), + tr("Restart").to_string(), + tr("Quit").to_string(), + ) +} + /// A stock preset's or profile's name in the UI language; an imported or user-edited name stays /// exactly as its owner wrote it. pub fn builtin_label(source: &str, builtin: bool) -> &str { diff --git a/crates/ui-egui/src/panels/compare.rs b/crates/ui-egui/src/panels/compare.rs index 829500da47b..ff994281f7d 100644 --- a/crates/ui-egui/src/panels/compare.rs +++ b/crates/ui-egui/src/panels/compare.rs @@ -431,7 +431,7 @@ fn request_window(app: &mut LightcraftApp, v: &TileView) -> Option Opt // the After window is proofed like the whole-frame render under it; the Before side is // never proofed (its whole-frame render isn't either) let proof = app.ui.soft_proof.then_some(app.ui.proof); - let job = job.with_overlay(overlay).with_proof(if v.before { None } else { proof }); + // only drawn: stays on the GPU when it renders there (issue #1228) + let job = job.with_overlay(overlay).with_proof(if v.before { None } else { proof }).to_texture(app.renderer.takes_textures()); // keyed as the renderer keys the texture (a display profile changes the key) let job = app.renderer.job_for(v.slot, job); // The overlay and the proof are part of the tile's identity too, so changing mask view/colour diff --git a/crates/ui-egui/src/render.rs b/crates/ui-egui/src/render.rs index 973c0d8b867..dfec124b926 100644 --- a/crates/ui-egui/src/render.rs +++ b/crates/ui-egui/src/render.rs @@ -66,10 +66,62 @@ pub enum Slot { HdrHistogram, } +/// The window's renderer, for renders that stay on the GPU (issue #1228): renders on the window's +/// device ([`lightcraft_engine::gpu::share_window_device`]) are drawn from their own texture, +/// with no copy of the pixels through the CPU. The desktop app gives it (egui-wgpu); without it +/// every render is an egui texture made from its pixels. +pub trait NativeTextures: Send + Sync { + /// Make `texture` drawable by egui; `None` when it can't be (the caller drops the render). + fn register(&self, texture: &lightcraft_engine::gpu::GpuTexture) -> Option; + /// Forget a texture [`Self::register`] returned. + fn free(&self, id: egui::TextureId); +} + +/// A texture egui draws: one it made from pixels, or a render that stayed on the GPU. +pub enum TexImage { + Managed(egui::TextureHandle), + Native(NativeTex), +} + +/// A render's texture on the window's device, registered with egui until dropped. +pub struct NativeTex { + id: egui::TextureId, + size: [usize; 2], + owner: Arc, + /// Kept alive while egui may draw it (and read back for headless screenshots). + texture: lightcraft_engine::gpu::GpuTexture, +} + +impl Drop for NativeTex { + fn drop(&mut self) { + self.owner.free(self.id); + } +} + +impl TexImage { + pub fn id(&self) -> egui::TextureId { + match self { + TexImage::Managed(t) => t.id(), + TexImage::Native(t) => t.id, + } + } + + pub fn size(&self) -> [usize; 2] { + match self { + TexImage::Managed(t) => t.size(), + TexImage::Native(t) => t.size, + } + } + + pub fn is_native(&self) -> bool { + matches!(self, TexImage::Native(_)) + } +} + pub struct Tex { pub key: u64, pub photo: PhotoId, - pub tex: egui::TextureHandle, + pub tex: TexImage, pub size: [usize; 2], pub histogram: Option, pub ms: f64, @@ -250,6 +302,8 @@ pub struct Renderer { pub(crate) stage_budget_override: Option, /// The monitor profile textures are made for (`app.displayProfile`; `None`: sRGB). display: Option>, + /// The window's renderer, for renders handed over as textures on its device (issue #1228). + native: Option>, /// Since when nothing has been pending, and whether the GPU pool was trimmed since. #[cfg(not(target_arch = "wasm32"))] idle: Option<(std::time::Instant, bool)>, @@ -314,6 +368,7 @@ impl Renderer { #[cfg(test)] stage_budget_override: None, display: None, + native: None, #[cfg(not(target_arch = "wasm32"))] idle: None, } @@ -441,10 +496,23 @@ impl Renderer { if let Some(d) = display { lightcraft_engine::display::present(&mut r, d); } - let color = r.rendered.as_ref().ok().map(|x| Arc::new(color_image(&x.image))); + // (a render that stayed on the GPU has no pixels to convert) + let color = r.rendered.as_ref().ok().filter(|_| r.texture.is_none()).map(|x| Arc::new(color_image(&x.image))); Finished { result: r, color } } + /// Draw renders that stay on the GPU through the window's renderer from now on (issue #1228). + pub fn set_native_textures(&mut self, native: Arc) { + self.native = Some(native); + } + + /// Whether a view's render may come back as a texture on the window's device rather than as + /// pixels: the window's renderer takes them. (A headless screenshot reads such a texture back + /// when it is taken: [`Self::cpu_textures`].) + pub fn takes_textures(&self) -> bool { + self.native.is_some() && lightcraft_engine::gpu::shares_window_device() + } + fn request_needed(&self, slot: Slot, key: u64, priority: u32) -> bool { // A matching old texture must not mask a different newer request (e.g. undo). if let Some(&(k, p)) = self.pending.get(&slot) { @@ -869,6 +937,10 @@ impl Renderer { if slot.is_view() { self.shown_ids.insert(slot, r.request_id); } + // a render that stayed on the GPU can't be converted here: made for another profile, it is obsolete + if r.texture.is_some() && r.display != self.display_id() { + continue; + } // (results from an offload, which doesn't know the display profile: converted here) if let Some(d) = &self.display { let before = r.display; @@ -918,13 +990,36 @@ impl Renderer { if let Slot::Thumb(id) = slot { self.textures.remove(&Slot::ThumbQuick(id)); } + // a render that stayed on the GPU: drawn from its own texture (issue #1228) + if let Some(gt) = r.texture { + let size = [gt.width, gt.height]; + let Some(id) = self.native.as_ref().and_then(|n| n.register(>)) else { + // (no window renderer to take it: asked for only when there is one) + log::warn!("render {slot:?}: the window's renderer did not take a GPU texture"); + continue; + }; + let Some(owner) = self.native.clone() else { continue }; + let tex = TexImage::Native(NativeTex { id, size, owner, texture: gt }); + // (no histogram: only the whole frame's is shown) + let t = Tex { key: r.key, photo: r.photo, tex, size, histogram: None, ms, quick: r.quick, pixels: None }; + self.textures.insert(slot, t); + if slot == Slot::Main { + self.last_main_ms = ms; + } + changed = true; + continue; + } let img = &rendered.image; let color = color.unwrap_or_else(|| Arc::new(color_image(img))); let pixels = self.keep_pixels.then(|| color.clone()); let name = format!("{slot:?}"); match self.textures.get_mut(&slot) { Some(t) => { - t.tex.set(color, egui::TextureOptions::LINEAR); + match &mut t.tex { + TexImage::Managed(h) => h.set(color, egui::TextureOptions::LINEAR), + // (the native texture is freed when replaced) + TexImage::Native(_) => t.tex = TexImage::Managed(ctx.load_texture(name, color, egui::TextureOptions::LINEAR)), + } t.pixels = pixels; t.key = r.key; t.photo = r.photo; @@ -934,7 +1029,7 @@ impl Renderer { t.quick = r.quick; } None => { - let tex = ctx.load_texture(name, color, egui::TextureOptions::LINEAR); + let tex = TexImage::Managed(ctx.load_texture(name, color, egui::TextureOptions::LINEAR)); self.textures.insert( slot, Tex { @@ -1011,13 +1106,24 @@ impl Renderer { let copies: usize = self.textures.values().filter_map(|t| t.pixels.as_ref()).map(|p| p.pixels.len() * 4).sum(); serde_json::json!({ "stageCaches": {"count": self.stages.len(), "cpuBytes": cpu, "gpuBytes": gpu, "budgetBytes": self.stage_budget(), "trimmed": self.stages_trimmed, "sharedSourceBytes": lightcraft_engine::gpu::shared_source_bytes()}, - "textures": {"count": self.textures.len(), "bytes": tex, "cpuCopyBytes": copies}, + "textures": {"count": self.textures.len(), "bytes": tex, "cpuCopyBytes": copies, "native": self.textures.values().filter(|t| t.tex.is_native()).count()}, }) } /// CPU copies of the current textures by id (see [`Self::keep_pixels`]). pub fn cpu_textures(&self) -> HashMap { - self.textures.values().filter_map(|t| Some((t.tex.id(), crate::softpaint::CpuTexture::linear(t.pixels.clone()?)))).collect() + self.textures + .values() + .filter_map(|t| { + let pixels = match (&t.pixels, &t.tex) { + (Some(p), _) => p.clone(), + // a render that stayed on the GPU: read back now (screenshots only) + (None, TexImage::Native(n)) if self.keep_pixels => Arc::new(color_image(&lightcraft_engine::gpu::read_texture(&n.texture)?)), + _ => return None, + }; + Some((t.tex.id(), crate::softpaint::CpuTexture::linear(pixels))) + }) + .collect() } /// Drop the import review thumbnails (a new review, or the dialog closed). @@ -1860,7 +1966,10 @@ mod stage_budget_tests { let ctx = egui::Context::default(); let mut r = Renderer::default(); let tex = ctx.load_texture("window", egui::ColorImage::new([1, 1], vec![egui::Color32::BLACK]), Default::default()); - r.textures.insert(Slot::Region, Tex { key: 1, photo: PhotoId(1), tex, size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }); + r.textures.insert( + Slot::Region, + Tex { key: 1, photo: PhotoId(1), tex: TexImage::Managed(tex), size: [1, 1], histogram: None, ms: 0.0, quick: None, pixels: None }, + ); let long_ago = std::time::Instant::now().checked_sub(IDLE_TRIM * 2).unwrap(); r.idle = Some((long_ago, false)); r.trim_when_idle(&ctx); @@ -1991,6 +2100,7 @@ mod color_image_tests { loaded: None, quick: None, display: None, + texture: None, }; let histogram = Histogram::of_srgb8(&image); let ok = Renderer::run_for(|| result(Ok(lightcraft_pipeline::Rendered { image: image.clone(), histogram, deep: None })), &None); diff --git a/crates/ui-egui/src/tests_lifecycle_037.rs b/crates/ui-egui/src/tests_lifecycle_037.rs index bfb08f1b49a..6ee3cfe5d82 100644 --- a/crates/ui-egui/src/tests_lifecycle_037.rs +++ b/crates/ui-egui/src/tests_lifecycle_037.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use crate::headless::Headless; -use crate::render::{Slot, Tex}; +use crate::render::{Slot, Tex, TexImage}; use crate::{ControlResponse, LightcraftApp, MAX_PENDING_SHOTS, MAX_SHOT_BYTES, PendingShot, Services, ShotGeometry}; use lightcraft_engine::slideshow::Item; @@ -559,9 +559,10 @@ fn hidden_slideshow_pauses_and_keeps_its_remaining_time() { // Every slide is "ready": without the hidden gate, 10 hidden seconds would advance the show. for id in app.session.visible_cloned() { let tex = ctx.load_texture(format!("slide-{}", id.0), egui::ColorImage::filled([2, 2], egui::Color32::WHITE), Default::default()); - app.renderer - .textures - .insert(Slot::Slide(Item::Photo(id)), Tex { key: 0, photo: id, tex, size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }); + app.renderer.textures.insert( + Slot::Slide(Item::Photo(id)), + Tex { key: 0, photo: id, tex: TexImage::Managed(tex), size: [2, 2], histogram: None, ms: 0.0, quick: None, pixels: None }, + ); } let first = app.ui.slideshow.as_ref().unwrap().play.current(); let selection = app.session.active(); diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index f88f81c3901..c7ab5f59124 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -49,6 +49,9 @@ Overrides (read once at launch): - `LIGHTCRAFT_GPU=0`: GPU rendering off for the process (the window is unaffected). - Both `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` also keep AI Denoise, the face models and the AI mask model (SAM 3 on Metal) on the CPU. +- `LIGHTCRAFT_GPU_TEXTURES=0`: renders get a device of their own instead of sharing the window's, + and come back as pixels ([Renders as window textures](#renders-as-window-textures-issue-1228)); + what a restart after a lost device sets. **DX12 shader compiler (issue #471).** Every instance (window and compute) compiles DX12 shaders with FXC (`d3dcompiler_47.dll`, part of Windows; `lightcraft_gpu::backend::backend_options`). wgpu's @@ -236,6 +239,8 @@ passes on as `RenderResult::gpu_fallback`; an export carries it as `Exported::gp each file of an `app.export` batch result has `gpuFallback` when its render fell back (issue #675). **Reproducing a smaller GPU:** `LIGHTCRAFT_GPU_LIMITS=webgpu` (or `downlevel`) creates the device with 128 MiB storage bindings / 256 MiB buffers, `LIGHTCRAFT_GPU_LIMITS=` with n MiB / 2n MiB. +**Reproducing a driver reset:** `LIGHTCRAFT_GPU_LOSE_AFTER=` destroys the device after n GPU +renders ([Renders as window textures](#renders-as-window-textures-issue-1228)). Tests inject failures with `lightcraft_gpu::inject_fault` (`crates/gpu/tests/it/fallback.rs`, `export_falls_back_to_the_cpu_when_gpu_work_is_lost`). The fault is thread-local, and so are its consequences: a simulated fatal failure stops GPU use on the injecting thread only (`available()` @@ -243,6 +248,39 @@ false, `unavailable_reason()` set there), until `reset_failures()`, which undoes real failure still stops the whole process. Such a test asserts on its own render's reason, not on `last_fallback()`, so it can run beside other tests rendering on the GPU (issue #675). +## Renders as window textures (issue #1228) +The desktop app lends the window's wgpu device to the renderer (`window_gpu::lend_device` → +`lightcraft_gpu::share_window_device`, before anything renders): the kernels compile on it, and the +window's device is requested with the adapter's limits (`window_device_limits`) so they fit. A +render that is only drawn — the zoom windows of Detail, Before/After, Compare and Reference +(`RenderJob::to_texture`) — then comes back as a texture on that device +(`lightcraft_gpu::try_render_texture`) instead of pixels: the `pad_rows` kernel copies the kept +part of the output into rows aligned for a buffer-to-texture copy, applies a display profile's +per-channel curves on the way (`DisplayProfile::correction_curves`), and counts unwritten and lit +pixels, so the incomplete-image and all-black checks still run on two words read back. The UI +registers the texture with egui-wgpu (`render::NativeTextures`, `TexImage::Native`) and frees it +when it is replaced. A 24 MP raw at 1:1 on an M4 Max: 30 ms per Exposure step instead of 41 ms +(p50 round trip, 22–44 ms instead of 36–71 ms), and the window's 44 MB CPU copy is gone. + +Read-back pixels stay for everything else, and are the fallback: the whole frame (its histogram is +shown), overlays (drawn on the CPU), soft proofs and deep renders, LUT-based display profiles (a +CMS transform), thumbnails and exports; the glow renderer or a software window adapter (no device +to share); `LIGHTCRAFT_GPU_TEXTURES=0` (renders keep a device of their own, as before); and any +render that falls back to the CPU. A headless screenshot reads a texture back when it is taken +(`lightcraft_gpu::read_texture`). + +**A lost device.** Render errors stay in their render's error scopes (thread-local) and never reach +the window. A *lost* device (driver reset, GPU hang) is lost to the window too — as it was before +sharing, when a reset took every device on the GPU. Renders go back to the CPU, and +`lightcraft_gpu::window_device_lost()` is set: egui-wgpu panics drawing anything on a lost device, +so the app draws empty frames and asks in a native dialog to restart or quit; after saving, a +restart starts LightCraft again with `LIGHTCRAFT_GPU_TEXTURES=0`. A loss in the middle of a frame +(the panic happens before the app can stop drawing) ends `run_native` with an error, and the app +starts again the same way; the library has written every command to its journal, so only a +slider drag in progress is lost. Tested by `crates/gpu/tests/texture_lost.rs` and +`window_gpu::tests::a_lost_window_device_draws_empty_frames_without_a_panic`; seen end to end with +`LIGHTCRAFT_GPU_LOSE_AFTER=`, which destroys the device after n GPU renders. + ## Correctness: CPU oracle and equivalence tests `crates/gpu/tests/it/equivalence.rs` renders the same settings on both and compares 8-bit sRGB: bounds **mean |Δ| < 0.5 LSB and max |Δ| ≤ 3 LSB** per channel. Measured (Apple M4 Pro, Metal): @@ -343,8 +381,8 @@ A view's stages keep an uploaded source only up to 96 MB (a Preview-level source 2.5–2.6 GB → 0.91–0.96 GB, heap peak 930 → ~600 MB; stepping median ~13 ms (unchanged). ## Open items -- Keep the loupe texture on the GPU (render into an `egui-wgpu` texture on eframe's device instead of - reading back); share the device with eframe. +- The whole-frame loupe render still reads back (its histogram is shown): a GPU histogram (below) + would let it stay on the GPU too; overlays drawn by a kernel would let their windows stay. - WebGPU in the browser build (async init, single device per canvas). - Defringe and spot removal kernels; Sky/Subject heuristics (replaced by the segmenter in M12). - Tiling for sources / outputs beyond the buffer limit (24 MP+ on WebGPU-default limits, 60 MP+ diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index afbed8675ee..dcfcbade451 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (LR-VIEW-ZOOM: zoom windows as GPU textures without a readback, opt-in, issue #1228; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -129,7 +129,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-VIEW-EDIT | Edit view | P0 | ✅ | `cmd:panel.edit` | | | LR-VIEW-FULLSCREEN | Full-screen preview | P1 | ✅ | `cmd:view.fullScreenPreview`, `cmd:view.enterFullScreen` | photo on black, arrows step, Esc exits; ⇧⌘F window full screen | | LR-VIEW-FILMSTRIP | Filmstrip | P0 | ✅ | `cmd:view.filmstrip`, `crates/ui-egui/src/panels/detail.rs` | the photo context menu on right-click; the mouse wheel scrolls it sideways, a third of its width per notch as in Lightroom Classic (trackpads scroll the points they report); it follows the active photo only when that changes (centred if off screen), so a scrolled strip stays put; every selected photo is highlighted, the active one framed in white, as in the grid | -| LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with an output-device profile proof or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. Handing GPU renders to egui without a CPU readback is #1228. A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays (Visualize Spots, Point Color range, HDR range) get windows too, tested equal to the whole-frame render's pixels. Photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the browser): the window grows to hold the spot and its source patch, or the dabs near it, and if that would take more (a clone from far away at 8:1) the loupe keeps the whole-frame render instead, and spots with an automatic source pick it from a fixed-size render of the whole frame (so a window's choice can differ from a whole-frame render's, which picks at its own resolution). The wide stages (dehaze, clarity, highlights/shadows base) and Refine Edges on masks read a window margin capped at 768 px; measured on hard-edged blocks that costs at most a few levels at 8:1. the histogram and Navigator come from the whole-frame render. Compare and Reference get the same windows, one per pane (`Slot::CompareRegion`, `panels/compare.rs`), over each pane's whole-frame render (at most 2560 px); while either view is open two originals stay decoded (`MediaCache::set_full_capacity`), so one pane's window does not evict the other's source; a pinch, or a slider drag on the active photo in Reference, keeps the windows there are until it ends. Mask overlays and soft proofing get the same windows (the window carries the overlay or the proof; only an output-device-profile proof renders on the CPU, where a tick at 100 % on a 1400 × 900 canvas takes about 36 ms instead of a full-size 24 MP proof). Verified: a 1:1 window of a 24 MP photo with tone and colour edits is the full-size export to within one level (`one_to_one_window_pixels_are_export_pixels`). Measured on Linux (Ryzen AI Max+ 395, Radeon 8060S, GPU, `profile_slider_drag`): median tick→shown 7 ms at fit, 33 ms at 100 % and 6 ms at 400 % on 1400 × 900; 21 ms at 100 % and 9 ms at 400 % on 2800 × 1700; 36 ms at 100 % with an output-device-profile soft proof (the CPU path) | +| LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with an output-device profile proof or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. The zoom windows (Detail, Before/After, Compare and Reference) reach the screen as GPU textures with no copy back to the CPU (issue #1228): renders run on the window's own wgpu device, and a window comes back as a texture egui draws, display-profile curves applied on the GPU; a 24 MP raw at 1:1 updates in 30 ms instead of 41 ms per step (p50, M4 Max). The whole frame, overlays, LUT-based display profiles, the glow renderer and `LIGHTCRAFT_GPU_TEXTURES=0` keep read-back pixels; if the shared device is lost, renders go back to the CPU and the app offers to restart (`window_gpu::device_lost_answer`). A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays (Visualize Spots, Point Color range, HDR range) get windows too, tested equal to the whole-frame render's pixels. Photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the browser): the window grows to hold the spot and its source patch, or the dabs near it, and if that would take more (a clone from far away at 8:1) the loupe keeps the whole-frame render instead, and spots with an automatic source pick it from a fixed-size render of the whole frame (so a window's choice can differ from a whole-frame render's, which picks at its own resolution). The wide stages (dehaze, clarity, highlights/shadows base) and Refine Edges on masks read a window margin capped at 768 px; measured on hard-edged blocks that costs at most a few levels at 8:1. the histogram and Navigator come from the whole-frame render. Compare and Reference get the same windows, one per pane (`Slot::CompareRegion`, `panels/compare.rs`), over each pane's whole-frame render (at most 2560 px); while either view is open two originals stay decoded (`MediaCache::set_full_capacity`), so one pane's window does not evict the other's source; a pinch, or a slider drag on the active photo in Reference, keeps the windows there are until it ends. Mask overlays and soft proofing get the same windows (the window carries the overlay or the proof; only an output-device-profile proof renders on the CPU, where a tick at 100 % on a 1400 × 900 canvas takes about 36 ms instead of a full-size 24 MP proof). Verified: a 1:1 window of a 24 MP photo with tone and colour edits is the full-size export to within one level (`one_to_one_window_pixels_are_export_pixels`). Measured on Linux (Ryzen AI Max+ 395, Radeon 8060S, GPU, `profile_slider_drag`): median tick→shown 7 ms at fit, 33 ms at 100 % and 6 ms at 400 % on 1400 × 900; 21 ms at 100 % and 9 ms at 400 % on 2800 × 1700; 36 ms at 100 % with an output-device-profile soft proof (the CPU path) | | LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus_read.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests_focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests_focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only | | LR-VIEW-NAVIGATOR | Navigator mini map | P1 | ✅ | `cmd:view.navigator`, `crates/ui-egui/src/panels/detail.rs` | shown while zoomed (bottom right); click/drag pans | | LR-VIEW-BEFOREAFTER | Before / after | P0 | ✅ | `cmd:view.showOriginal`, `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom`, `cmd:beforeAfter.setBefore`, `cmd:beforeAfter.copyAfterToBefore`, `cmd:beforeAfter.copyBeforeToAfter`, `cmd:beforeAfter.swap`, `cmd:beforeAfter.resetBefore` | all four layouts; before = the import state (defaults + import preset) or a chosen history step / version / the current settings; copy and swap (View → Before/After Settings, History row menu). The chosen before lasts for the session; in side by side and top / bottom, clicks with the white-balance selector, colour samplers and targeted adjustment work in the Before view too (`crates/ui-egui/src/tests_before_after.rs`). Zoomed in, the side by side and stacked views each stay in their pane, with their labels under it. Click zoom animates both panes together, including cached window tiles; input follows the displayed image and render requests use the final size (#1821) | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | LR-VIEW-ZOOM: zoom windows reach the screen as GPU textures on the window's device, without a CPU readback (opt-in, `LIGHTCRAFT_GPU_TEXTURES=1`); a lost shared device offers a restart (issue #1228); status unchanged | | 2026-10-25 | patch | LR-BEHAV-TITLEBAR: the top bar's title-bar gestures come from craft-window's `title_bar`: a double-click follows the system setting, and a press on a button, the search field or a panel floating over the bar never moves the window; status counts unchanged | | 2026-10-24 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 (`keyword.nextSet`, `keyword.previousSet`) go to the next / previous keyword set; status counts unchanged (KEYC-METADATA stays 🟡) | | 2026-10-24 | minor | KEYC-METADATA: ⌘K / Ctrl+K (`panel.addKeywords`, Add Keywords) shows the Keywords panel, opens Keywording and puts the cursor in the Add keyword box; status counts unchanged (KEYC-METADATA stays 🟡) | From b76e507c7cbc162ebcdfcfdbcd7eb0a7dd4f5561 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Mon, 12 Oct 2026 18:13:26 +0200 Subject: [PATCH 04/13] LR-VIEW-ZOOM: window textures are opt-in (LIGHTCRAFT_GPU_TEXTURES=1): a shared queue drops frames (#1228) One device has one queue, and the window's frames wait behind renders there. 8 s 1:1 Exposure drags on a 61 MP raw, 4 alternating runs, one render per view slot: the shared device dropped 0-4 % of frames (p95 12-23 ms, worst 33-131 ms), renders on their own device none (p95 8-13 ms, worst 18-36 ms), for window renders of 4-15 ms instead of 24-50 ms. Pacing the renders' submissions made it worse and is not kept. Renders keep their own device by default; a restart after a lost shared device clears the switch. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/window_gpu.rs | 13 +++++++------ docs/gpu-pipeline.md | 20 ++++++++++++++------ docs/parity-checklist.md | 2 +- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index e6d9ccf97aa..5c55374ab43 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -179,9 +179,10 @@ impl lightcraft_ui_egui::render::NativeTextures for WindowTextures { /// as textures on it, which [`WindowTextures`] (returned) draws. `None` with the glow renderer, /// or when the window's adapter can't run the kernels — renders then keep a device of their own. pub fn lend_device(render_state: Option<&eframe::egui_wgpu::RenderState>) -> Option { - // `LIGHTCRAFT_GPU_TEXTURES=0`: renders keep a device of their own and come back as pixels - // (a driver that misbehaves with a shared device; A/B measurements) - if std::env::var("LIGHTCRAFT_GPU_TEXTURES").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")) { + // Opt-in (`LIGHTCRAFT_GPU_TEXTURES=1`): a window update is fresher, but one device has one + // queue, and frames wait behind renders there — a 1:1 slider drag on a 61 MP raw dropped 0–4 % + // of its frames, where renders on a device of their own dropped none (issue #1228). + if !std::env::var("LIGHTCRAFT_GPU_TEXTURES").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")) { return None; } let rs = render_state?; @@ -235,14 +236,14 @@ pub fn device_lost_answer(ctx: &egui::Context) -> Option { } /// Start LightCraft again after the window's device was lost, with the arguments it was started -/// with and renders on a device of their own (`LIGHTCRAFT_GPU_TEXTURES=0`): a driver that loses -/// shared devices can't take the new window down with a render. +/// with and renders on a device of their own (`LIGHTCRAFT_GPU_TEXTURES` cleared, so the +/// default): a driver that loses shared devices can't take the new window down with a render. pub fn relaunch_with_own_render_device() -> bool { let Ok(exe) = std::env::current_exe() else { return false }; log::warn!("window: starting again, renders on a device of their own"); std::process::Command::new(exe) .args(std::env::args_os().skip(1)) - .env("LIGHTCRAFT_GPU_TEXTURES", "0") + .env_remove("LIGHTCRAFT_GPU_TEXTURES") .spawn() .map_err(|e| log::error!("window: could not start again: {e}")) .is_ok() diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index c7ab5f59124..fd2558c0fee 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -49,9 +49,9 @@ Overrides (read once at launch): - `LIGHTCRAFT_GPU=0`: GPU rendering off for the process (the window is unaffected). - Both `LIGHTCRAFT_GPU=0` and `LIGHTCRAFT_GPU_BACKEND=off` also keep AI Denoise, the face models and the AI mask model (SAM 3 on Metal) on the CPU. -- `LIGHTCRAFT_GPU_TEXTURES=0`: renders get a device of their own instead of sharing the window's, - and come back as pixels ([Renders as window textures](#renders-as-window-textures-issue-1228)); - what a restart after a lost device sets. +- `LIGHTCRAFT_GPU_TEXTURES=1` (opt-in): renders share the window's device and zoom windows come + back as textures ([Renders as window textures](#renders-as-window-textures-issue-1228)); a + restart after a lost device clears it. **DX12 shader compiler (issue #471).** Every instance (window and compute) compiles DX12 shaders with FXC (`d3dcompiler_47.dll`, part of Windows; `lightcraft_gpu::backend::backend_options`). wgpu's @@ -249,7 +249,15 @@ real failure still stops the whole process. Such a test asserts on its own rende `last_fallback()`, so it can run beside other tests rendering on the GPU (issue #675). ## Renders as window textures (issue #1228) -The desktop app lends the window's wgpu device to the renderer (`window_gpu::lend_device` → +**Opt-in: `LIGHTCRAFT_GPU_TEXTURES=1`.** A device has one queue, and the window's frames wait +behind the renders on it. In 8 s 1:1 Exposure drags on a 61 MP raw (M4 Max, 4 alternating runs, +both with one render per view slot) the shared device dropped 0–4 % of frames (p95 12–23 ms, +worst 33–131 ms) where renders on a device of their own dropped none (p95 8–13 ms, worst +18–36 ms), against window renders of 4–15 ms instead of 24–50 ms. Pacing the renders' +submissions (waiting for each piece before queueing the next) made it worse. Until the window's +frames can go first, renders keep their own device by default. + +With it, the desktop app lends the window's wgpu device to the renderer (`window_gpu::lend_device` → `lightcraft_gpu::share_window_device`, before anything renders): the kernels compile on it, and the window's device is requested with the adapter's limits (`window_device_limits`) so they fit. A render that is only drawn — the zoom windows of Detail, Before/After, Compare and Reference @@ -265,7 +273,7 @@ when it is replaced. A 24 MP raw at 1:1 on an M4 Max: 30 ms per Exposure step in Read-back pixels stay for everything else, and are the fallback: the whole frame (its histogram is shown), overlays (drawn on the CPU), soft proofs and deep renders, LUT-based display profiles (a CMS transform), thumbnails and exports; the glow renderer or a software window adapter (no device -to share); `LIGHTCRAFT_GPU_TEXTURES=0` (renders keep a device of their own, as before); and any +to share); without `LIGHTCRAFT_GPU_TEXTURES=1` (renders keep a device of their own); and any render that falls back to the CPU. A headless screenshot reads a texture back when it is taken (`lightcraft_gpu::read_texture`). @@ -274,7 +282,7 @@ the window. A *lost* device (driver reset, GPU hang) is lost to the window too sharing, when a reset took every device on the GPU. Renders go back to the CPU, and `lightcraft_gpu::window_device_lost()` is set: egui-wgpu panics drawing anything on a lost device, so the app draws empty frames and asks in a native dialog to restart or quit; after saving, a -restart starts LightCraft again with `LIGHTCRAFT_GPU_TEXTURES=0`. A loss in the middle of a frame +restart starts LightCraft again without `LIGHTCRAFT_GPU_TEXTURES`. A loss in the middle of a frame (the panic happens before the app can stop drawing) ends `run_native` with an error, and the app starts again the same way; the library has written every command to its journal, so only a slider drag in progress is lost. Tested by `crates/gpu/tests/texture_lost.rs` and diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index dcfcbade451..ad7a9660459 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -129,7 +129,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-VIEW-EDIT | Edit view | P0 | ✅ | `cmd:panel.edit` | | | LR-VIEW-FULLSCREEN | Full-screen preview | P1 | ✅ | `cmd:view.fullScreenPreview`, `cmd:view.enterFullScreen` | photo on black, arrows step, Esc exits; ⇧⌘F window full screen | | LR-VIEW-FILMSTRIP | Filmstrip | P0 | ✅ | `cmd:view.filmstrip`, `crates/ui-egui/src/panels/detail.rs` | the photo context menu on right-click; the mouse wheel scrolls it sideways, a third of its width per notch as in Lightroom Classic (trackpads scroll the points they report); it follows the active photo only when that changes (centred if off screen), so a scrolled strip stays put; every selected photo is highlighted, the active one framed in white, as in the grid | -| LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with an output-device profile proof or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. The zoom windows (Detail, Before/After, Compare and Reference) reach the screen as GPU textures with no copy back to the CPU (issue #1228): renders run on the window's own wgpu device, and a window comes back as a texture egui draws, display-profile curves applied on the GPU; a 24 MP raw at 1:1 updates in 30 ms instead of 41 ms per step (p50, M4 Max). The whole frame, overlays, LUT-based display profiles, the glow renderer and `LIGHTCRAFT_GPU_TEXTURES=0` keep read-back pixels; if the shared device is lost, renders go back to the CPU and the app offers to restart (`window_gpu::device_lost_answer`). A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays (Visualize Spots, Point Color range, HDR range) get windows too, tested equal to the whole-frame render's pixels. Photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the browser): the window grows to hold the spot and its source patch, or the dabs near it, and if that would take more (a clone from far away at 8:1) the loupe keeps the whole-frame render instead, and spots with an automatic source pick it from a fixed-size render of the whole frame (so a window's choice can differ from a whole-frame render's, which picks at its own resolution). The wide stages (dehaze, clarity, highlights/shadows base) and Refine Edges on masks read a window margin capped at 768 px; measured on hard-edged blocks that costs at most a few levels at 8:1. the histogram and Navigator come from the whole-frame render. Compare and Reference get the same windows, one per pane (`Slot::CompareRegion`, `panels/compare.rs`), over each pane's whole-frame render (at most 2560 px); while either view is open two originals stay decoded (`MediaCache::set_full_capacity`), so one pane's window does not evict the other's source; a pinch, or a slider drag on the active photo in Reference, keeps the windows there are until it ends. Mask overlays and soft proofing get the same windows (the window carries the overlay or the proof; only an output-device-profile proof renders on the CPU, where a tick at 100 % on a 1400 × 900 canvas takes about 36 ms instead of a full-size 24 MP proof). Verified: a 1:1 window of a 24 MP photo with tone and colour edits is the full-size export to within one level (`one_to_one_window_pixels_are_export_pixels`). Measured on Linux (Ryzen AI Max+ 395, Radeon 8060S, GPU, `profile_slider_drag`): median tick→shown 7 ms at fit, 33 ms at 100 % and 6 ms at 400 % on 1400 × 900; 21 ms at 100 % and 9 ms at 400 % on 2800 × 1700; 36 ms at 100 % with an output-device-profile soft proof (the CPU path) | +| LR-VIEW-ZOOM | Zoom & pan | P0 | ✅ | `cmd:view.zoomFit`, `cmd:view.zoom100`, `cmd:view.zoomIn`, `cmd:view.zoomOut`, `cmd:view.zoomToggle`, `cmd:view.clickZoom`, `cmd:view.navigate`, `crates/ui-egui/src/panels/detail.rs`, `crates/ui-egui/src/headless.rs` | continuous native pinch / modifier-wheel zoom (Fit–800%, anchored under the pointer), two-finger scroll / touch pan with edge limits; in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); in Detail a middle-button drag (the wheel pressed) pans with a hand cursor whatever tool is active, so Remove / Heal / Clone, mask brushes and Crop don't paint or move meanwhile (`middle_pan`, `tests_canvas_pan.rs`); Detail (including tools, Before/After and full-screen preview), Compare and Reference; fractional percentages preserve small gestures; image, picker and targeted-adjustment cursors stay steady between gesture events; keyboard steps 25–800 % (not 6–1600 %); Fill in the bottom bar; click / Z / Space eases to the chosen ratio (1:1 default, 2:1, 3:1, 4:1, 8:1). The loupe's cost follows the canvas, not the zoom (issue #323): the whole frame is rendered at about canvas size (at most the 2560 px preview source level unless a larger Preview size is chosen, and never above the GPU's texture side), and once the view is zoomed well past that (more than 25 %) the window on screen is rendered too, cut from a frame of at most the photo's own pixels, so beyond 100 % the GPU magnifies it (`region::plan`, `RenderRequest::window`, `Session::region_job`, `crates/ui-egui/src/region.rs`); 1:1 and 2:1–8:1 are sharp at any photo size. A slider tick takes 7–12 ms on a 1400 × 900 canvas and 11–25 ms on a 2800 × 1700 one at 100 % and 400 % of a 24 MP photo (M1 Max, GPU, `profile_slider_drag`); about 20–25 ms at 100 % on the big canvas is over a 16 ms frame. A slider drag renders the whole frame at full size where the GPU draws the view, so the fit view stays sharp while dragging, and at 0.6 of it where that would be too slow: on the CPU, with an output-device profile proof or the HDR range shown, or for a control whose full-size drafts on this photo went clearly over the 16 ms slider budget (more than 20 ms) in two drags in a row (a LUT profile or refined mask the CPU renders, a photo past a GPU limit, a slow GPU); a draft's time is its render plus the frame that uploads and shows it, and a host frame time over 1 s (a hidden or stalled window) counts as unknown. A slow verdict is per photo and control (the same control on another photo, or another control on this one, is timed afresh) and expires: after 30 s a drag tries full size again, the wait doubling after each slow retry up to 240 s. Only a drag timed at full size changes it: one whose full-size drafts' median time (leaving out the first) is at most 20 ms forgets it; a drag that drafts small from its start (while the verdict holds, or where the GPU does not draw the view) or times fewer than two full-size drafts leaves it unchanged. At most 256 (photo, control) pairs are remembered, the oldest forgotten first. The size is chosen when a drag starts and kept until it ends, unless its full-size drafts take more than twice the budget, when it drops to 0.6 after three of them (`region::DragScale`, issue #330). Zoomed in, the whole-frame draft under the window is the 0.6 one (only the histogram and the window's stand-in use it). Render workers convert the pixels for their textures, not the UI thread. With `LIGHTCRAFT_GPU_TEXTURES=1` (opt-in, issue #1228) the zoom windows reach the screen as GPU textures with no copy back to the CPU: renders run on the window's own wgpu device and a window comes back as a texture egui draws, display-profile curves applied on the GPU; a 24 MP raw at 1:1 updates in 30 ms instead of 41 ms per step (p50, M4 Max), but the shared queue drops 0–4 % of a 1:1 drag's frames on a 61 MP raw, where renders on their own device drop none, so it is off by default. If the shared device is lost, renders go back to the CPU and the app offers to restart (`window_gpu::device_lost_answer`). A continuous pinch holds the render sizes (and the windows there are) and the size the fit view is shrunk to until it is quiet. A fit view on a canvas up to about 3200 px (a Retina Mac) never decodes the original; larger displays get a window at fit, which does. Diagnostic overlays (Visualize Spots, Point Color range, HDR range) get windows too, tested equal to the whole-frame render's pixels. Photos whose spots or Auto Mask strokes read too far for one window (only photos longer than 8192 px) render the whole frame at the size it is drawn, as before windows; while a preset or profile is hovered, or over a picture that is not the frame (an unsupported raw's embedded JPEG), the whole frame stays canvas-sized. Before/After (side by side, stacked, `\\` and both wipes) gets the same windows on both sides, clipped to their pane or side of the line. Windows render on the GPU like whole frames (equivalence-tested against the CPU), in the browser build too (windows no wider than its GPU's texture side, at most 3072 px), and are not made while hovering a look, nor over a picture that is not the frame (an unsupported raw's embedded JPEG with another crop). No texture is larger than the GPU allows. Spots and Auto Mask brushes work while what a window reads fits one render (8192 px along an axis, 4096 in the browser): the window grows to hold the spot and its source patch, or the dabs near it, and if that would take more (a clone from far away at 8:1) the loupe keeps the whole-frame render instead, and spots with an automatic source pick it from a fixed-size render of the whole frame (so a window's choice can differ from a whole-frame render's, which picks at its own resolution). The wide stages (dehaze, clarity, highlights/shadows base) and Refine Edges on masks read a window margin capped at 768 px; measured on hard-edged blocks that costs at most a few levels at 8:1. the histogram and Navigator come from the whole-frame render. Compare and Reference get the same windows, one per pane (`Slot::CompareRegion`, `panels/compare.rs`), over each pane's whole-frame render (at most 2560 px); while either view is open two originals stay decoded (`MediaCache::set_full_capacity`), so one pane's window does not evict the other's source; a pinch, or a slider drag on the active photo in Reference, keeps the windows there are until it ends. Mask overlays and soft proofing get the same windows (the window carries the overlay or the proof; only an output-device-profile proof renders on the CPU, where a tick at 100 % on a 1400 × 900 canvas takes about 36 ms instead of a full-size 24 MP proof). Verified: a 1:1 window of a 24 MP photo with tone and colour edits is the full-size export to within one level (`one_to_one_window_pixels_are_export_pixels`). Measured on Linux (Ryzen AI Max+ 395, Radeon 8060S, GPU, `profile_slider_drag`): median tick→shown 7 ms at fit, 33 ms at 100 % and 6 ms at 400 % on 1400 × 900; 21 ms at 100 % and 9 ms at 400 % on 2800 × 1700; 36 ms at 100 % with an output-device-profile soft proof (the CPU path) | | LR-VIEW-FOCUSPOINT | Camera focus point overlay and zoom (beyond Lightroom) | P2 | 🟡 | `cmd:view.focusPoint`, `cmd:view.zoomToFocus`, `cmd:view.zoomToggle`, `cmd:photo.reload`, `cmd:photo.readFocusPoints`, `cmd:focus.pump`, `crates/meta/src/focus.rs`, `crates/meta/src/focus_read.rs`, `crates/engine/src/focus_scan.rs`, `crates/engine/src/tests_focus_scan.rs`, `crates/ui-egui/src/panels/detail.rs` (`focus_box`, `draw_focus_point`), `crates/ui-egui/src/panels/compare.rs`, `crates/ui-egui/src/tests_focus_point.rs`, `docs/focus-points.md` | an extra (Lightroom shows no focus points): the AF frame read from the file at import; photos imported earlier get it in the background from a header-only read of each file (about 32 KB, ~100 photos/s from a spinning disk; activity row, cancellable, resumable; Photo ▸ Read Focus Points) as a box on the upright photo, drawn in Detail, Compare and Survey through rotation and crop (View ▸ Focus Point, ⌥F); Toggle Zoom centres on it (View ▸ Zoom to Focus Point, on by default); Info panel row `AF-C · Wide · Animal Eye Tracking`; `meta.focus` in `photo.inspect`. Partial: Sony ILCE-1 and ILCE-7SM3 only (layout checked against 333 files); other Sony bodies and other makers not yet; manual focus and centre-only Wide reports show nothing; Compare panes share one pan, so Z centres on the active photo's point only | | LR-VIEW-NAVIGATOR | Navigator mini map | P1 | ✅ | `cmd:view.navigator`, `crates/ui-egui/src/panels/detail.rs` | shown while zoomed (bottom right); click/drag pans | | LR-VIEW-BEFOREAFTER | Before / after | P0 | ✅ | `cmd:view.showOriginal`, `cmd:view.beforeAfter`, `cmd:view.beforeAfterSplit`, `cmd:view.beforeAfterTopBottom`, `cmd:view.beforeAfterSplitTopBottom`, `cmd:beforeAfter.setBefore`, `cmd:beforeAfter.copyAfterToBefore`, `cmd:beforeAfter.copyBeforeToAfter`, `cmd:beforeAfter.swap`, `cmd:beforeAfter.resetBefore` | all four layouts; before = the import state (defaults + import preset) or a chosen history step / version / the current settings; copy and swap (View → Before/After Settings, History row menu). The chosen before lasts for the session; in side by side and top / bottom, clicks with the white-balance selector, colour samplers and targeted adjustment work in the Before view too (`crates/ui-egui/src/tests_before_after.rs`). Zoomed in, the side by side and stacked views each stay in their pane, with their labels under it. Click zoom animates both panes together, including cached window tiles; input follows the displayed image and render requests use the final size (#1821) | From f6074cab7a387cd580f1caf6bde3f50abf1bf3c4 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Tue, 13 Oct 2026 09:03:08 +0200 Subject: [PATCH 05/13] LR-VIEW-ZOOM: the window device keeps egui's limits unless renders share it, and never asks above the adapter The window's wgpu device asked for every adapter limit and at least an 8192 px texture side even with LIGHTCRAFT_GPU_TEXTURES off. On an adapter with a smaller side the device request failed and the window didn't open, and every user's device changed, not just those who opt in. Now the window (and its probe) uses egui's own descriptor unless the opt-in is on; then `window_limits` asks for the adapter's limits, never above them (GL: WebGL2 limits with min(8192, adapter) side). Also: the lost-device test says what to do the day egui-wgpu stops panicking on a lost device. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/window_gpu.rs | 44 ++++++++++++++++++++----------- crates/gpu/src/lib.rs | 34 +++++++++++++++++++----- 2 files changed, 55 insertions(+), 23 deletions(-) diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index 5c55374ab43..79c5ca65a52 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -149,16 +149,30 @@ pub fn base_options() -> WgpuConfiguration { n.instance_descriptor.backend_options = backend::backend_options(); // no indirect-call validation pipeline: Intel Metal fails to compile it and the window never opens (#250) n.instance_descriptor.flags = backend::instance_flags_from_env(n.instance_descriptor.flags); - // the adapter's limits, so renders can share the device and hand the window textures (#1228) - n.device_descriptor = std::sync::Arc::new(|adapter| wgpu::DeviceDescriptor { - label: Some("egui wgpu device"), - required_limits: lightcraft_engine::gpu::window_device_limits(adapter), - ..Default::default() - }); + n.device_descriptor = std::sync::Arc::new(device_descriptor); } c } +/// Whether renders may share the window's device and reach it as textures (issue #1228): opt-in, +/// `LIGHTCRAFT_GPU_TEXTURES=1`. +fn gpu_textures_on() -> bool { + std::env::var("LIGHTCRAFT_GPU_TEXTURES").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")) +} + +/// The window's device: egui's own, unless renders may share it ([`gpu_textures_on`]); then the +/// adapter's limits (never above them), so renders can run there and hand the window textures. +fn device_descriptor(adapter: &wgpu::Adapter) -> wgpu::DeviceDescriptor<'static> { + if !gpu_textures_on() { + return (eframe::egui_wgpu::WgpuSetupCreateNew::without_display_handle().device_descriptor)(adapter); + } + wgpu::DeviceDescriptor { + label: Some("egui wgpu device"), + required_limits: lightcraft_engine::gpu::window_device_limits(adapter), + ..Default::default() + } +} + /// Renders that stay on the GPU (issue #1228), drawn through the window's egui-wgpu renderer: they /// are made on its device ([`lend_device`]) and registered as its textures. pub struct WindowTextures(eframe::egui_wgpu::RenderState); @@ -182,7 +196,7 @@ pub fn lend_device(render_state: Option<&eframe::egui_wgpu::RenderState>) -> Opt // Opt-in (`LIGHTCRAFT_GPU_TEXTURES=1`): a window update is fresher, but one device has one // queue, and frames wait behind renders there — a 1:1 slider drag on a 61 MP raw dropped 0–4 % // of its frames, where renders on a device of their own dropped none (issue #1228). - if !std::env::var("LIGHTCRAFT_GPU_TEXTURES").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")) { + if !gpu_textures_on() { return None; } let rs = render_state?; @@ -283,13 +297,9 @@ fn probe(backends: Backends) -> Result { ..Default::default() })) .map_err(|e| format!("no adapter: {e}"))?; - // (as `base_options` asks: renders can share the device) - let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { - label: Some("egui wgpu device"), - required_limits: lightcraft_engine::gpu::window_device_limits(&adapter), - ..Default::default() - })) - .map_err(|e| format!("{}: no device: {e}", adapter.get_info().name))?; + // (as `base_options` asks) + let (device, queue) = pollster::block_on(adapter.request_device(&device_descriptor(&adapter))) + .map_err(|e| format!("{}: no device: {e}", adapter.get_info().name))?; install_error_handler(&device); check_pipeline(&device, |d| { drop(eframe::egui_wgpu::Renderer::new(d, wgpu::TextureFormat::Bgra8Unorm, eframe::egui_wgpu::RendererOptions::default())); @@ -478,8 +488,10 @@ mod tests { mesh.add_rect_with_uv(r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE); let shapes = [egui::epaint::ClippedPrimitive { clip_rect: r, primitive: egui::epaint::Primitive::Mesh(mesh) }]; let screen = ScreenDescriptor { size_in_pixels: [64, 64], pixels_per_point: 1.0 }; - // what the app must not draw on a lost device (should egui-wgpu stop panicking here, the - // empty frames in `main.rs` can go) + // what the app must not draw on a lost device. This pins an egui-wgpu bug: the day an + // egui-wgpu update stops panicking here, this assertion fails. Then delete it and this + // half of the test, and draw frames on a lost device as usual (the empty frames in + // `main.rs` can go); the empty frame below must still not panic. let drawn = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let mut enc = device.create_command_encoder(&Default::default()); renderer.update_buffers(&device, &queue, &mut enc, &shapes, &screen) diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 519bcfa1ccc..ac11a2ac785 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -294,16 +294,22 @@ pub fn share_window_device(device: wgpu::Device, queue: wgpu::Queue, info: wgpu: } /// The limits to request the window's device with so renders can share it -/// ([`share_window_device`]): the adapter's own, as the render device asks for, with at least the -/// 8192 px texture side egui needs for 4k+ displays. A GL adapter keeps egui's WebGL2 limits (the -/// kernels never run there). +/// ([`share_window_device`]): [`window_limits`] for this adapter. #[cfg(not(target_arch = "wasm32"))] pub fn window_device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { - if adapter.get_info().backend == wgpu::Backend::Gl { - return wgpu::Limits { max_texture_dimension_2d: 8192, ..wgpu::Limits::downlevel_webgl2_defaults() }; + window_limits(adapter.get_info().backend, adapter.limits()) +} + +/// The window device's limits on an adapter of `backend` that supports `adapter`: the adapter's +/// own, as the render device asks for. A GL adapter keeps egui's WebGL2 limits with its 8192 px +/// texture side for 4k+ displays (the kernels never run there). Never above `adapter`: a device +/// asked for more than the adapter has isn't created, and the window doesn't open. +pub fn window_limits(backend: wgpu::Backend, adapter: wgpu::Limits) -> wgpu::Limits { + if backend == wgpu::Backend::Gl { + let side = adapter.max_texture_dimension_2d.min(8192); + return wgpu::Limits { max_texture_dimension_2d: side, ..wgpu::Limits::downlevel_webgl2_defaults() }; } - let limits = adapter.limits(); - wgpu::Limits { max_texture_dimension_2d: limits.max_texture_dimension_2d.max(8192), ..limits } + adapter } /// Set when the device lent by [`share_window_device`] was lost (driver reset, GPU hang). @@ -743,4 +749,18 @@ mod tests { assert!(!super::handles(OutputDepth::U8, true, Overlay::None)); assert!(!super::handles(OutputDepth::U8, false, Overlay::HdrRange)); } + + // The window device never asks for more than the adapter has: an adapter with a 4096 px + // texture side (older or mobile GPUs, software adapters) would refuse 8192, and the window + // wouldn't open; a larger side is the adapter's own + #[test] + fn the_window_device_never_asks_above_the_adapter() { + let adapter = |side| wgpu::Limits { max_texture_dimension_2d: side, ..wgpu::Limits::downlevel_defaults() }; + for backend in [wgpu::Backend::Metal, wgpu::Backend::Vulkan, wgpu::Backend::Dx12, wgpu::Backend::Gl] { + assert_eq!(super::window_limits(backend, adapter(4096)).max_texture_dimension_2d, 4096, "{backend:?}"); + } + assert_eq!(super::window_limits(wgpu::Backend::Metal, adapter(16384)).max_texture_dimension_2d, 16384); + assert_eq!(super::window_limits(wgpu::Backend::Gl, adapter(16384)).max_texture_dimension_2d, 8192); + assert_eq!(super::window_limits(wgpu::Backend::Vulkan, adapter(4096)), adapter(4096)); + } } From d86abeba6b4f2951094a96e325160effd69ef54e Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Tue, 13 Oct 2026 09:09:00 +0200 Subject: [PATCH 06/13] LR-VIEW-ZOOM: the lost-device dialog is translated in every language (#1228) Its title, text and Restart button fell back to English (Quit was already translated); a test checks every catalog has all four. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/locales/cs.json | 5 ++++- crates/ui-egui/locales/de.json | 5 ++++- crates/ui-egui/locales/es.json | 5 ++++- crates/ui-egui/locales/fi.json | 5 ++++- crates/ui-egui/locales/fr.json | 5 ++++- crates/ui-egui/locales/id.json | 5 ++++- crates/ui-egui/locales/it.json | 5 ++++- crates/ui-egui/locales/ja.json | 5 ++++- crates/ui-egui/locales/ka.json | 5 ++++- crates/ui-egui/locales/pl.json | 5 ++++- crates/ui-egui/locales/pt-br.json | 5 ++++- crates/ui-egui/locales/ru.json | 5 ++++- crates/ui-egui/locales/sv.json | 5 ++++- crates/ui-egui/locales/uk.json | 5 ++++- crates/ui-egui/locales/vi.json | 5 ++++- crates/ui-egui/locales/zh-hans.json | 5 ++++- crates/ui-egui/locales/zh-hant.json | 5 ++++- crates/ui-egui/src/i18n.rs | 13 +++++++++++++ 18 files changed, 81 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524d..941e22622e4 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -2408,5 +2408,8 @@ "Import dropped files without review": "Importovat přetažené soubory bez kontroly", "An import is running": "Import už běží", "An import is running. Drop photos when it has finished": "Import už běží. Fotky přetáhněte, až skončí", - "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky" + "Finish Lightroom catalog import before adding photos": "Dokončete import katalogu Lightroom, než přidáte fotky", + "LightCraft lost its graphics device": "LightCraft ztratil grafické zařízení", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Grafický ovladač přestal odpovídat, takže LightCraft už nemůže vykreslovat své okno. Vaše knihovna a úpravy jsou uloženy.\n\nPro pokračování LightCraft restartujte.", + "Restart": "Restartovat" } diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782f..5c59606699d 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -3440,5 +3440,8 @@ "Import dropped files without review": "Abgelegte Dateien ohne Prüfung importieren", "An import is running": "Ein Import läuft", "An import is running. Drop photos when it has finished": "Ein Import läuft. Lege die Fotos ab, wenn er fertig ist", - "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst" + "Finish Lightroom catalog import before adding photos": "Schließe den Import des Lightroom-Katalogs ab, bevor du Fotos hinzufügst", + "LightCraft lost its graphics device": "LightCraft hat sein Grafikgerät verloren", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Der Grafiktreiber reagiert nicht mehr, daher kann LightCraft sein Fenster nicht mehr zeichnen. Ihre Bibliothek und Ihre Bearbeitungen sind gespeichert.\n\nStarten Sie LightCraft neu, um fortzufahren.", + "Restart": "Neu starten" } diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff2..b072a33919d 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2358,5 +2358,8 @@ "Import dropped files without review": "Importar los archivos soltados sin revisión", "An import is running": "Hay una importación en curso", "An import is running. Drop photos when it has finished": "Hay una importación en curso. Suelta las fotos cuando termine", - "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos" + "Finish Lightroom catalog import before adding photos": "Termina la importación del catálogo de Lightroom antes de añadir fotos", + "LightCraft lost its graphics device": "LightCraft ha perdido su dispositivo gráfico", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "El controlador gráfico ha dejado de responder, así que LightCraft ya no puede dibujar su ventana. Su biblioteca y sus ediciones están guardadas.\n\nReinicie LightCraft para continuar.", + "Restart": "Reiniciar" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e0a8c622a36..a5bc1b74a63 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2327,5 +2327,8 @@ "Drop to open the face model": "Pudota avataksesi kasvomallin", "Dropped Files": "Pudotetut tiedostot", "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", - "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta" + "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", + "LightCraft lost its graphics device": "LightCraft menetti grafiikkalaitteensa", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Näytönohjaimen ajuri lakkasi vastaamasta, joten LightCraft ei voi enää piirtää ikkunaansa. Kirjastosi ja muokkauksesi on tallennettu.\n\nJatka käynnistämällä LightCraft uudelleen.", + "Restart": "Käynnistä uudelleen" } diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda6..42f93a110fc 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2390,5 +2390,8 @@ "Checking recent libraries": "Vérification des bibliothèques récentes", "The photos are imported once a library is open": "Les photos seront importées dès qu'une bibliothèque sera ouverte", "Open a library first, then drop the presets again": "Ouvrez d'abord une bibliothèque, puis déposez à nouveau les préréglages", - "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :" + "This library couldn't be checked:": "Impossible de vérifier cette bibliothèque :", + "LightCraft lost its graphics device": "LightCraft a perdu son périphérique graphique", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Le pilote graphique ne répond plus : LightCraft ne peut plus dessiner sa fenêtre. Votre bibliothèque et vos retouches sont enregistrées.\n\nRedémarrez LightCraft pour continuer.", + "Restart": "Redémarrer" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0d6da9b8fb8..ad8fdf84f2c 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2339,5 +2339,8 @@ "Drop to open the face model": "Jatuhkan untuk membuka model wajah", "Dropped Files": "File yang dijatuhkan", "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", - "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan" + "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", + "LightCraft lost its graphics device": "LightCraft kehilangan perangkat grafisnya", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Driver grafis berhenti merespons, sehingga LightCraft tidak dapat lagi menggambar jendelanya. Pustaka dan suntingan Anda sudah disimpan.\n\nMulai ulang LightCraft untuk melanjutkan.", + "Restart": "Mulai Ulang" } diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d15..33150bcb611 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2361,5 +2361,8 @@ "Import dropped files without review": "Importa i file rilasciati senza revisione", "An import is running": "Un'importazione è in corso", "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", - "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto" + "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", + "LightCraft lost its graphics device": "LightCraft ha perso il dispositivo grafico", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Il driver grafico ha smesso di rispondere, quindi LightCraft non può più disegnare la sua finestra. La tua libreria e le modifiche sono salvate.\n\nRiavvia LightCraft per continuare.", + "Restart": "Riavvia" } diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd7..bac27a3b157 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2356,5 +2356,8 @@ "Import dropped files without review": "ドロップしたファイルを確認せずに読み込む", "An import is running": "読み込み中です", "An import is running. Drop photos when it has finished": "読み込み中です。完了してから写真をドロップしてください", - "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください" + "Finish Lightroom catalog import before adding photos": "写真を追加する前に Lightroom カタログの読み込みを完了してください", + "LightCraft lost its graphics device": "LightCraft がグラフィックスデバイスを失いました", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "グラフィックスドライバーが応答しなくなったため、LightCraft はウインドウを描画できなくなりました。ライブラリと編集内容は保存されています。\n\n続けるには LightCraft を再起動してください。", + "Restart": "再起動" } diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 32c40770018..c3686188899 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -2734,5 +2734,8 @@ "Import dropped files without review": "ჩაგდებული ფაილების იმპორტი გადახედვის გარეშე", "An import is running": "იმპორტი მიმდინარეობს", "An import is running. Drop photos when it has finished": "იმპორტი მიმდინარეობს. ფოტოები ჩააგდეთ, როცა დასრულდება", - "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი" + "Finish Lightroom catalog import before adding photos": "ფოტოების დამატებამდე დაასრულეთ Lightroom-ის კატალოგის იმპორტი", + "LightCraft lost its graphics device": "LightCraft-მა დაკარგა გრაფიკული მოწყობილობა", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "გრაფიკულმა დრაივერმა შეწყვიტა პასუხი, ამიტომ LightCraft-ს აღარ შეუძლია თავისი ფანჯრის დახატვა. თქვენი ბიბლიოთეკა და რედაქტირებები შენახულია.\n\nგასაგრძელებლად გადატვირთეთ LightCraft.", + "Restart": "გადატვირთვა" } diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62ad..cc2da9b5ca7 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2283,5 +2283,8 @@ "Import dropped files without review": "Importuj upuszczone pliki bez przeglądu", "An import is running": "Import jest w toku", "An import is running. Drop photos when it has finished": "Import jest w toku. Upuść zdjęcia, gdy się zakończy", - "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia" + "Finish Lightroom catalog import before adding photos": "Zakończ import katalogu Lightrooma, zanim dodasz zdjęcia", + "LightCraft lost its graphics device": "LightCraft utracił urządzenie graficzne", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Sterownik grafiki przestał odpowiadać, więc LightCraft nie może już rysować swojego okna. Twoja biblioteka i zmiany są zapisane.\n\nUruchom ponownie LightCraft, aby kontynuować.", + "Restart": "Uruchom ponownie" } diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b7..852e072435e 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2202,5 +2202,8 @@ "Import dropped files without review": "Importar arquivos soltos sem revisão", "An import is running": "Uma importação está em andamento", "An import is running. Drop photos when it has finished": "Uma importação está em andamento. Solte as fotos quando ela terminar", - "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos" + "Finish Lightroom catalog import before adding photos": "Conclua a importação do catálogo do Lightroom antes de adicionar fotos", + "LightCraft lost its graphics device": "O LightCraft perdeu o dispositivo gráfico", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "O driver gráfico parou de responder, então o LightCraft não consegue mais desenhar a janela. Sua biblioteca e suas edições estão salvas.\n\nReinicie o LightCraft para continuar.", + "Restart": "Reiniciar" } diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 306804df045..a02b9c6814e 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2349,5 +2349,8 @@ "Import dropped files without review": "Импортировать перетащенные файлы без проверки", "An import is running": "Импорт уже выполняется", "An import is running. Drop photos when it has finished": "Импорт уже выполняется. Перетащите фото, когда он закончится", - "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото" + "Finish Lightroom catalog import before adding photos": "Завершите импорт каталога Lightroom, прежде чем добавлять фото", + "LightCraft lost its graphics device": "LightCraft потерял графическое устройство", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Графический драйвер перестал отвечать, поэтому LightCraft больше не может отрисовывать окно. Ваша библиотека и правки сохранены.\n\nПерезапустите LightCraft, чтобы продолжить.", + "Restart": "Перезапустить" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 66e69b7ba5d..c9dae7be6a1 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2429,5 +2429,8 @@ "Drop to open the face model": "Släpp för att öppna ansiktsmodellen", "Dropped Files": "Släppta filer", "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", - "Import dropped files without review": "Importera släppta filer utan granskning" + "Import dropped files without review": "Importera släppta filer utan granskning", + "LightCraft lost its graphics device": "LightCraft förlorade sin grafikenhet", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Grafikdrivrutinen slutade svara, så LightCraft kan inte längre rita sitt fönster. Ditt bibliotek och dina redigeringar är sparade.\n\nStarta om LightCraft för att fortsätta.", + "Restart": "Starta om" } diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe0..b24f9e2e868 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2354,5 +2354,8 @@ "Import dropped files without review": "Імпортувати перетягнуті файли без перегляду", "An import is running": "Імпорт уже виконується", "An import is running. Drop photos when it has finished": "Імпорт уже виконується. Перетягніть фото, коли він завершиться", - "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото" + "Finish Lightroom catalog import before adding photos": "Завершіть імпорт каталогу Lightroom, перш ніж додавати фото", + "LightCraft lost its graphics device": "LightCraft втратив графічний пристрій", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Графічний драйвер перестав відповідати, тому LightCraft більше не може малювати своє вікно. Вашу бібліотеку та редагування збережено.\n\nПерезапустіть LightCraft, щоб продовжити.", + "Restart": "Перезапустити" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index e4fb8feb81c..732b9d2873a 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2235,5 +2235,8 @@ "Drop to open the face model": "Thả để mở mô hình khuôn mặt", "Dropped Files": "Tệp đã thả", "Finish Lightroom catalog import before adding photos": "Hoàn tất nhập danh mục Lightroom trước khi thêm ảnh", - "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại" + "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại", + "LightCraft lost its graphics device": "LightCraft đã mất thiết bị đồ họa", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "Trình điều khiển đồ họa đã ngừng phản hồi nên LightCraft không thể vẽ cửa sổ của mình nữa. Thư viện và các chỉnh sửa của bạn đã được lưu.\n\nHãy khởi động lại LightCraft để tiếp tục.", + "Restart": "Khởi động lại" } diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a6251..62e3379c668 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2200,5 +2200,8 @@ "Import dropped files without review": "不经检查直接导入拖入的文件", "An import is running": "正在导入", "An import is running. Drop photos when it has finished": "正在导入。导入完成后再拖放照片", - "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入" + "Finish Lightroom catalog import before adding photos": "添加照片前,请先完成 Lightroom 目录的导入", + "LightCraft lost its graphics device": "LightCraft 丢失了图形设备", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "图形驱动程序已停止响应,LightCraft 无法再绘制窗口。您的图库和编辑已保存。\n\n请重新启动 LightCraft 以继续。", + "Restart": "重新启动" } diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 0408e23ec87..79b7a064b03 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2157,5 +2157,8 @@ "Import dropped files without review": "不經檢查直接匯入拖放的檔案", "An import is running": "正在匯入", "An import is running. Drop photos when it has finished": "正在匯入。匯入完成後再拖放照片", - "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入" + "Finish Lightroom catalog import before adding photos": "新增照片前,請先完成 Lightroom 目錄的匯入", + "LightCraft lost its graphics device": "LightCraft 遺失了圖形裝置", + "The graphics driver stopped responding, so LightCraft can't draw its window any more. Your library and edits are saved.\n\nRestart LightCraft to continue.": "圖形驅動程式已停止回應,LightCraft 無法再繪製視窗。你的圖庫與編輯都已儲存。\n\n請重新啟動 LightCraft 以繼續。", + "Restart": "重新啟動" } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index a990dea4d42..b20fa74d21a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -964,6 +964,19 @@ mod tests { assert_eq!(restored.language, Locale::ZhHans); } + /// The lost-device dialog (issue #1228) is a native dialog shown when nothing else can be + /// drawn: every language has its title, text and buttons. + #[test] + fn device_lost_dialog_is_translated_in_every_language() { + let english = device_lost_message(); + for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { + for key in [&english.0, &english.1, &english.2, &english.3] { + let value = language.tr(key); + assert!(!value.is_empty() && value != key.as_str(), "{language:?}: {key}"); + } + } + } + /// Smart-album choice values read as words in every language (English "Public Domain"), never as /// rule ids like `publicDomain`; an id the field doesn't know shows as written. A yes/no value /// reads Yes / No, or the language's contextual entry for it where it has one. From 404f95737c783314780e139f9d52b7d9acea9505 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Tue, 13 Oct 2026 09:26:14 +0200 Subject: [PATCH 07/13] LR-VIEW-ZOOM: the web build compiles again (`RenderResult::texture`, native-only `window_limits`) The web render workers built `RenderResult` without the new `texture` field (the wasm check failed on the branch), and `window_limits` named wgpu, which wasm32 builds don't have. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft-web/src/workers.rs | 3 +++ crates/gpu/src/lib.rs | 2 ++ 2 files changed, 5 insertions(+) diff --git a/apps/lightcraft-web/src/workers.rs b/apps/lightcraft-web/src/workers.rs index a5e64886e3d..8c062c6c416 100644 --- a/apps/lightcraft-web/src/workers.rs +++ b/apps/lightcraft-web/src/workers.rs @@ -301,6 +301,7 @@ impl Workers { loaded: None, quick: None, display: None, + texture: None, }; g.done.push((b.slot, r, 0.0)); } @@ -392,6 +393,7 @@ impl Workers { loaded: None, quick: None, display: None, + texture: None, }, ms, )); @@ -446,6 +448,7 @@ impl RenderOffload for Workers { loaded: None, quick: None, display: None, + texture: None, }; g.done.push((slot, r, 0.0)); return None; diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index ac11a2ac785..c4956102762 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -304,6 +304,7 @@ pub fn window_device_limits(adapter: &wgpu::Adapter) -> wgpu::Limits { /// own, as the render device asks for. A GL adapter keeps egui's WebGL2 limits with its 8192 px /// texture side for 4k+ displays (the kernels never run there). Never above `adapter`: a device /// asked for more than the adapter has isn't created, and the window doesn't open. +#[cfg(not(target_arch = "wasm32"))] pub fn window_limits(backend: wgpu::Backend, adapter: wgpu::Limits) -> wgpu::Limits { if backend == wgpu::Backend::Gl { let side = adapter.max_texture_dimension_2d.min(8192); @@ -753,6 +754,7 @@ mod tests { // The window device never asks for more than the adapter has: an adapter with a 4096 px // texture side (older or mobile GPUs, software adapters) would refuse 8192, and the window // wouldn't open; a larger side is the adapter's own + #[cfg(not(target_arch = "wasm32"))] #[test] fn the_window_device_never_asks_above_the_adapter() { let adapter = |side| wgpu::Limits { max_texture_dimension_2d: side, ..wgpu::Limits::downlevel_defaults() }; From 57dbdefd4b8bca8e1de6bf2209c433670f7ddb5d Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Tue, 13 Oct 2026 12:35:56 +0200 Subject: [PATCH 08/13] LR-VIEW-ZOOM: the lost-device dialog keeps the UI language (#1228) The UI language is thread-local and a new thread's is English, so the device-lost dialog built its text on the dialog thread came out in English. `ask_device_lost` now builds the message on the UI thread and hands it to the dialog thread; a regression test sets another language and checks the text the dialog thread receives. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/window_gpu.rs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index 79c5ca65a52..a87f878d2a3 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -229,8 +229,7 @@ pub fn device_lost_answer(ctx: &egui::Context) -> Option { } *answer = Some(None); let ctx = ctx.clone(); - let asked = std::thread::Builder::new().name("device-lost".into()).spawn(move || { - let (title, text, restart, quit) = lightcraft_ui_egui::i18n::device_lost_message(); + let asked = ask_device_lost(move |(title, text, restart, quit)| { let r = rfd::MessageDialog::new() .set_level(rfd::MessageLevel::Error) .set_title(title) @@ -249,6 +248,13 @@ pub fn device_lost_answer(ctx: &egui::Context) -> Option { None } +/// Shows the lost-device dialog (`ask`) on a thread of its own. The message is put together +/// here, on the calling (UI) thread: the UI language is per thread, and a new thread's is English. +fn ask_device_lost(ask: impl FnOnce((String, String, String, String)) + Send + 'static) -> std::io::Result> { + let message = lightcraft_ui_egui::i18n::device_lost_message(); + std::thread::Builder::new().name("device-lost".into()).spawn(move || ask(message)) +} + /// Start LightCraft again after the window's device was lost, with the arguments it was started /// with and renders on a device of their own (`LIGHTCRAFT_GPU_TEXTURES` cleared, so the /// default): a driver that loses shared devices can't take the new window down with a render. @@ -353,6 +359,20 @@ pub fn relaunch_after_failure(files: &Files) -> bool { mod tests { use super::*; + /// The lost-device dialog runs on a thread of its own, whose UI language would be English: + /// its text must be in the language the UI thread has. + #[test] + fn the_lost_device_dialog_speaks_the_ui_language() { + use lightcraft_ui_egui::i18n; + let other = *i18n::Locale::ALL.iter().find(|&&l| l != i18n::Locale::En).unwrap(); + i18n::set_language(other); + let expected = i18n::device_lost_message(); + let (tx, rx) = std::sync::mpsc::channel(); + ask_device_lost(move |message| tx.send(message).unwrap()).unwrap().join().unwrap(); + i18n::set_language(i18n::Locale::En); + assert_eq!(rx.recv().unwrap(), expected, "dialog shown in {other:?}"); + } + fn dir(tag: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("app-window-gpu-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); From 1c9ff11f4927deffa9fa52441031ed178d116be7 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Fri, 16 Oct 2026 22:07:07 +0200 Subject: [PATCH 09/13] LR-VIEW-ZOOM: the lost-window-device test skips software adapters (FreeBSD lavapipe segfault) Mesa's software Vulkan crashes on a destroyed device instead of reporting the loss, which took down the whole lightcraft test binary on the FreeBSD job. The skips now go through lightcraft_testkit::skip! so CI lists them. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/window_gpu.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index a87f878d2a3..d1005e838d6 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -475,11 +475,20 @@ mod tests { ..wgpu::InstanceDescriptor::new_without_display_handle() }); let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { - eprintln!("no GPU adapter: skipped"); + lightcraft_testkit::skip!(Gpu, "no GPU adapter"); return; }; + // Mesa's software Vulkan (lavapipe, the FreeBSD CI runner) segfaults when a destroyed + // device is used, where real drivers report the loss: nothing to learn there. + if adapter.get_info().device_type == wgpu::DeviceType::Cpu { + lightcraft_testkit::skip!(Gpu, "software adapter {} crashes on a destroyed device", adapter.get_info().name); + return; + } let desc = wgpu::DeviceDescriptor { required_limits: lightcraft_engine::gpu::window_device_limits(&adapter), ..Default::default() }; - let Ok((device, queue)) = pollster::block_on(adapter.request_device(&desc)) else { return }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&desc)) else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; install_error_handler(&device); let format = wgpu::TextureFormat::Bgra8Unorm; let mut renderer = Renderer::new(&device, format, RendererOptions::default()); From 01750504a11693991f9d51cb6684089b4ea85c34 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Fri, 16 Oct 2026 23:44:55 +0200 Subject: [PATCH 10/13] LR-VIEW-ZOOM: the lost-window-device test also skips wgpu's GL backend The FreeBSD runner has no Vulkan driver, so the window backends (PRIMARY | GL) give it a Mesa GL adapter, which segfaulted on the destroyed device just as before: 521dcf5c only skipped CPU-type adapters. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/window_gpu.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index d1005e838d6..da8cf7978b4 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -478,10 +478,12 @@ mod tests { lightcraft_testkit::skip!(Gpu, "no GPU adapter"); return; }; - // Mesa's software Vulkan (lavapipe, the FreeBSD CI runner) segfaults when a destroyed - // device is used, where real drivers report the loss: nothing to learn there. - if adapter.get_info().device_type == wgpu::DeviceType::Cpu { - lightcraft_testkit::skip!(Gpu, "software adapter {} crashes on a destroyed device", adapter.get_info().name); + // Software adapters and wgpu's GL backend (Mesa GL on the FreeBSD CI runner, which has no + // Vulkan driver) segfault when a destroyed device is used, where Metal, DX12 and hardware + // Vulkan report the loss: nothing to learn there. + let info = adapter.get_info(); + if info.device_type == wgpu::DeviceType::Cpu || info.backend == wgpu::Backend::Gl { + lightcraft_testkit::skip!(Gpu, "{} adapter {} crashes on a destroyed device", info.backend, info.name); return; } let desc = wgpu::DeviceDescriptor { required_limits: lightcraft_engine::gpu::window_device_limits(&adapter), ..Default::default() }; From ed2b1d18caed845dc8281f00760ae991be56b8ca Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Sun, 18 Oct 2026 18:20:46 +0200 Subject: [PATCH 11/13] LR-VIEW-ZOOM: a lost graphics device never quits with edits that couldn't be saved After the window's device is lost the app now saves first; when the journal and the closing snapshot both fail, the edits stay queued and a native dialog says how many and why, offering Try Again or Quit Anyway. It neither exits nor restarts until saving works or the user picks Quit Anyway. save_and_shut_down returns the save result. Review on PR #1240. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/main.rs | 279 +++++++++++++++++++- apps/lightcraft/src/window_gpu.rs | 54 ++++ crates/ui-egui/locales/cs-formats.json | 3 +- crates/ui-egui/locales/de-formats.json | 3 +- crates/ui-egui/locales/es-formats.json | 3 +- crates/ui-egui/locales/fi-formats.json | 3 +- crates/ui-egui/locales/fr-formats.json | 3 +- crates/ui-egui/locales/id-formats.json | 3 +- crates/ui-egui/locales/it-formats.json | 3 +- crates/ui-egui/locales/ja-formats.json | 3 +- crates/ui-egui/locales/ka-formats.json | 3 +- crates/ui-egui/locales/pl-formats.json | 3 +- crates/ui-egui/locales/pt-br-formats.json | 3 +- crates/ui-egui/locales/ru-formats.json | 3 +- crates/ui-egui/locales/sv-formats.json | 3 +- crates/ui-egui/locales/uk-formats.json | 3 +- crates/ui-egui/locales/vi-formats.json | 3 +- crates/ui-egui/locales/zh-hans-formats.json | 3 +- crates/ui-egui/locales/zh-hant-formats.json | 3 +- crates/ui-egui/src/i18n.rs | 27 ++ docs/gpu-pipeline.md | 7 +- 21 files changed, 389 insertions(+), 29 deletions(-) diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index ea755f7e22a..9a19559c7dc 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -69,15 +69,19 @@ impl eframe::App for App { // Quit from the menu bar: save exactly what closing the window saves (settings and // library, after the unsaved-changes check; otherwise its prompt shows), then end the // process instead of closing the viewport while AppKit is terminating (PR #444). - self.save_and_shut_down(); + // (`may_close` has already offered to keep changes that couldn't be saved) + let _unsaved = self.save_and_shut_down(); std::process::exit(0); } // The window's device was lost (issue #1228: renders share it): nothing can be drawn on it // again. Save, then restart or quit as the user answers (nothing else runs meanwhile). if lightcraft_engine::gpu::window_device_lost() { - if let Some(restart) = window_gpu::device_lost_answer(ctx) { - self.save_and_shut_down(); - if restart { + let mut stage = LOST_STAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let next = self.after_device_lost(&mut stage, &mut WindowDialogs(ctx)); + drop(stage); + if next != LostOutcome::Wait { + self.shut_down(); + if next == LostOutcome::Restart { window_gpu::relaunch_with_own_render_device(); } std::process::exit(0); @@ -102,7 +106,8 @@ impl eframe::App for App { self.0.ui(ui); } fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { - self.save_and_shut_down(); + // (closing the window went through `may_close`, which offers to keep unsaved changes) + let _unsaved = self.save_and_shut_down(); // macOS (#1331): end the process here, before eframe tears the window down, as Quit from // the menu bar already does (PR #444). AccessKit's macOS adapter subclasses the window's // content view and restores its class on teardown; AppKit's Touch Bar support observes @@ -117,10 +122,19 @@ impl eframe::App for App { } impl App { - /// Save settings and the library, then wait for background work: closing the window, Quit - /// from the macOS menu bar, or starting again after a lost graphics device (which must not - /// end the process here, so the macOS exit stays in `on_exit`). - fn save_and_shut_down(&mut self) { + /// Save settings and the library, then wait for background work: closing the window or Quit + /// from the macOS menu bar (which must not end the process here, so the macOS exit stays in + /// `on_exit`). Returns what [`App::save`] returns. + fn save_and_shut_down(&mut self) -> Result<(), Unsaved> { + let saved = self.save(); + self.shut_down(); + saved + } + + /// Save settings and the library. Fails when changes are left that couldn't be written to disk + /// (the log and the closing snapshot both failed); they stay queued, so saving can be tried + /// again. + fn save(&mut self) -> Result<(), Unsaved> { // (a size the window was just given is remembered too) self.0.ui.window = self.1.window_at_exit(self.0.ui.window); if let Err(e) = self.1.save(&self.0) { @@ -129,11 +143,108 @@ impl App { if let Err(e) = self.0.session.close_library() { log::error!("saving the library failed: {e}"); } - // last, with everything saved: no render may be inside the GPU driver when the process ends + // (a snapshot that failed after the log took every change loses nothing) + match self.0.session.unsaved() { + None => Ok(()), + Some((changes, reason)) => Err(Unsaved { changes, reason: reason.to_string() }), + } + } + + /// Wait for background work. Last, with everything saved: no render may be inside the GPU + /// driver when the process ends. + fn shut_down(&mut self) { if !self.0.shutdown(EXIT_WAIT) { log::warn!("quit: background work was still running after {EXIT_WAIT:?}"); } } + + /// One frame of the window after its graphics device was lost (issue #1228). It saves first, + /// so the restart-or-quit question can say everything is saved. When saving fails, the changes + /// stay in memory and a dialog says so and offers to try again: the process only ends without + /// them when the user picks Quit Anyway, as normal quit does (`notices::may_close`). + fn after_device_lost(&mut self, stage: &mut LostDevice, dialogs: &mut impl LostDeviceDialogs) -> LostOutcome { + // (Try Again saves again in the same frame; one retry per frame) + for _ in 0..2 { + if *stage == LostDevice::Save { + *stage = match self.save() { + Ok(()) => LostDevice::Ask, + Err(unsaved) => LostDevice::SaveFailed(unsaved), + }; + } + match stage { + LostDevice::Save => {} + LostDevice::SaveFailed(unsaved) => match dialogs.quit_unsaved(unsaved) { + None => return LostOutcome::Wait, + Some(true) => { + log::warn!("window: quitting without {} change(s) that couldn't be saved: {}", unsaved.changes, unsaved.reason); + return LostOutcome::Quit; + } + Some(false) => *stage = LostDevice::Save, + }, + LostDevice::Ask => { + return match dialogs.restart() { + None => LostOutcome::Wait, + Some(true) => LostOutcome::Restart, + Some(false) => LostOutcome::Quit, + }; + } + } + } + LostOutcome::Wait + } +} + +/// Changes that couldn't be written to disk ([`App::save`]): how many, and why. +#[derive(Debug, Clone, PartialEq)] +struct Unsaved { + changes: usize, + reason: String, +} + +/// Where the window is after its graphics device was lost ([`App::after_device_lost`]). +#[derive(Debug, Clone, PartialEq)] +enum LostDevice { + /// Save settings and the library. + Save, + /// Saving failed: asking whether to try again or quit without these changes. + SaveFailed(Unsaved), + /// Saved: asking whether to restart or quit. + Ask, +} + +/// The running app's lost-device steps (it has one window). +static LOST_STAGE: std::sync::Mutex = std::sync::Mutex::new(LostDevice::Save); + +/// What [`App::after_device_lost`] decided this frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LostOutcome { + /// Keep running: a dialog is open, or saving failed and the user hasn't chosen yet. + Wait, + /// End the process. + Quit, + /// Start LightCraft again, then end this process. + Restart, +} + +/// The native dialogs of the lost-device steps (`window_gpu`); tests answer them instead. +trait LostDeviceDialogs { + /// Restart (`true`) or quit; `None` while the dialog is open. + fn restart(&mut self) -> Option; + /// Saving failed: quit anyway, losing the changes (`true`), or try again (`false`); `None` + /// while the dialog is open. + fn quit_unsaved(&mut self, unsaved: &Unsaved) -> Option; +} + +/// The real dialogs, each on a thread of its own (the window can't draw). +struct WindowDialogs<'a>(&'a egui::Context); + +impl LostDeviceDialogs for WindowDialogs<'_> { + fn restart(&mut self) -> Option { + window_gpu::device_lost_answer(self.0) + } + fn quit_unsaved(&mut self, unsaved: &Unsaved) -> Option { + window_gpu::unsaved_answer(self.0, unsaved.changes, &unsaved.reason) + } } /// How long quitting waits for renders that are running (issue #620). A GPU render takes well under @@ -1214,6 +1325,154 @@ mod tests { d } + /// A library store whose writes fail while `fail` is set (a full or unplugged disk). + #[derive(Clone, Default)] + struct FailingDisk { + files: lightcraft_engine::catalog::MemStore, + fail: std::sync::Arc, + } + + impl FailingDisk { + fn set_failing(&self, on: bool) { + self.fail.store(on, std::sync::atomic::Ordering::SeqCst); + } + fn check(&self) -> std::io::Result<()> { + if self.fail.load(std::sync::atomic::Ordering::SeqCst) { Err(std::io::Error::other("disk full")) } else { Ok(()) } + } + fn session(&self) -> Session { + let mut session = Session::new(); + let stores = lightcraft_engine::library::LibraryStores { + dir: "failing".into(), + catalog: Box::new(self.clone()), + files: Box::new(lightcraft_engine::catalog::MemStore::new()), + on_disk: false, + }; + session.open_library_in(stores, true).unwrap(); + session + } + } + + impl lightcraft_engine::catalog::Store for FailingDisk { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.check()?; + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.check()?; + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn describe(&self) -> String { + "failing".into() + } + } + + /// Answers the lost-device dialogs as a user would, and records what was asked. + #[derive(Default)] + struct Answers { + /// Answers to "saving failed: try again or quit anyway?", in turn (`None`: still open). + quit_unsaved: std::collections::VecDeque>, + /// What that dialog was told each time it was shown. + told: Vec, + /// The answer to "restart or quit?". + restart: Option, + restart_asked: usize, + } + + impl LostDeviceDialogs for Answers { + fn restart(&mut self) -> Option { + self.restart_asked += 1; + self.restart + } + fn quit_unsaved(&mut self, unsaved: &Unsaved) -> Option { + self.told.push(unsaved.clone()); + self.quit_unsaved.pop_front().flatten() + } + } + + fn app_on(session: Session) -> App { + App( + LightcraftApp::new(session, Services::default()), + PrefsWriter::default(), + #[cfg(target_os = "macos")] + None, + ) + } + + /// PR #1240 review: after the window's device is lost, a save that fails (log and closing + /// snapshot both) neither ends nor restarts the app: the edits stay queued in memory, the user + /// is told how many and why, and Try Again saves them once the disk is back. Only then is the + /// restart question (which says the edits are saved) asked. + #[test] + fn a_lost_device_never_quits_with_edits_that_could_not_be_saved() { + let disk = FailingDisk::default(); + let mut app = app_on(disk.session()); + let id = app.0.session.selection.active.unwrap(); + disk.set_failing(true); + assert!(app.0.session.execute("photo.rate", &serde_json::json!({"rating": 4})).is_err()); + assert_eq!(app.0.session.unsaved().map(|u| u.0), Some(1)); + + let mut stage = LostDevice::Save; + let mut answers = Answers { restart: Some(true), ..Default::default() }; + // the dialog is up: keep waiting, with the edit still queued + answers.quit_unsaved.push_back(None); + assert_eq!(app.after_device_lost(&mut stage, &mut answers), LostOutcome::Wait); + assert_eq!(answers.told.len(), 1); + assert_eq!(answers.told[0].changes, 1); + assert!(answers.told[0].reason.contains("disk full"), "{:?}", answers.told[0]); + // Try Again while the disk is still full: asked again, nothing lost, no restart + answers.quit_unsaved.push_back(Some(false)); + assert_eq!(app.after_device_lost(&mut stage, &mut answers), LostOutcome::Wait); + assert_eq!(answers.told.len(), 3, "the failed retry asks again"); + assert_eq!(answers.restart_asked, 0, "the restart question claims the edits are saved"); + assert_eq!(app.0.session.unsaved().map(|u| u.0), Some(1)); + assert!(matches!(stage, LostDevice::SaveFailed(_)), "{stage:?}"); + + // the disk is back: Try Again saves, then the restart question is asked + disk.set_failing(false); + answers.quit_unsaved.push_back(Some(false)); + assert_eq!(app.after_device_lost(&mut stage, &mut answers), LostOutcome::Restart); + assert_eq!(answers.restart_asked, 1); + assert_eq!(app.0.session.unsaved(), None); + let reopened = disk.session(); + assert_eq!(reopened.catalog.photo(id).map(|p| p.rating), Some(4), "the edit reached the disk"); + } + + /// Quit Anyway in that dialog is the one way to end without the unsaved edits, and it never + /// restarts. + #[test] + fn a_lost_device_quits_without_unsaved_edits_only_when_told_to() { + let disk = FailingDisk::default(); + let mut app = app_on(disk.session()); + disk.set_failing(true); + assert!(app.0.session.execute("photo.rate", &serde_json::json!({"rating": 2})).is_err()); + let mut stage = LostDevice::Save; + let mut answers = Answers { restart: Some(true), ..Default::default() }; + answers.quit_unsaved.push_back(Some(true)); + assert_eq!(app.after_device_lost(&mut stage, &mut answers), LostOutcome::Quit); + assert_eq!(answers.restart_asked, 0); + } + + /// When saving works, the restart question comes straight away. + #[test] + fn a_lost_device_saves_then_asks_to_restart() { + let disk = FailingDisk::default(); + let mut app = app_on(disk.session()); + app.0.session.execute("photo.rate", &serde_json::json!({"rating": 3})).unwrap(); + let mut stage = LostDevice::Save; + let mut answers = Answers::default(); + assert_eq!(app.after_device_lost(&mut stage, &mut answers), LostOutcome::Wait, "restart dialog still open"); + answers.restart = Some(false); + assert_eq!(app.after_device_lost(&mut stage, &mut answers), LostOutcome::Quit); + assert!(answers.told.is_empty()); + assert_eq!(answers.restart_asked, 2); + } + /// Issue #374: launch arguments that would walk a whole drive or home folder are reported, /// not imported; empty ones are ignored; the rest are imported as absolute paths. #[test] diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index da8cf7978b4..0d5cb4ff132 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -255,6 +255,60 @@ fn ask_device_lost(ask: impl FnOnce((String, String, String, String)) + Send + ' std::thread::Builder::new().name("device-lost".into()).spawn(move || ask(message)) } +/// The answer to the dialog shown when saving failed after the device was lost: `None` when no +/// dialog is up, `Some(None)` while it is open, then `Some(Some(quit_anyway))` until read. +static UNSAVED_ANSWER: std::sync::Mutex>> = std::sync::Mutex::new(None); + +/// Saving failed after the window's device was lost: `changes` couldn't be written to disk, for +/// `reason`. Asks in a native dialog on its own thread whether to try again or quit without them; +/// `Some(true)` is Quit Anyway, `Some(false)` Try Again (each answer is read once, so a failed +/// retry asks again). Without a dialog (`LIGHTCRAFT_NO_PREFS`, or no thread for one) nothing is +/// answered: the changes are never dropped without someone choosing to. +pub fn unsaved_answer(ctx: &egui::Context, changes: usize, reason: &str) -> Option { + let mut answer = UNSAVED_ANSWER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + match *answer { + Some(Some(quit)) => { + *answer = None; + return Some(quit); + } + Some(None) => return None, + None => {} + } + if std::env::var_os("LIGHTCRAFT_NO_PREFS").is_some() { + return None; + } + log::error!("window: {changes} change(s) couldn't be saved after the graphics device was lost: {reason}"); + let ctx = ctx.clone(); + let asked = ask_unsaved(changes, reason, move |(title, text, try_again, quit)| { + let r = rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Error) + .set_title(title) + .set_description(text) + .set_buttons(rfd::MessageButtons::OkCancelCustom(try_again, quit.clone())) + .show(); + // (as for the lost-device dialog: some platforms answer Ok / Cancel for the two buttons) + let quit = matches!(&r, rfd::MessageDialogResult::Custom(b) if *b == quit) || r == rfd::MessageDialogResult::Cancel; + *UNSAVED_ANSWER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Some(quit)); + ctx.request_repaint(); + }); + match asked { + Ok(_) => *answer = Some(None), + Err(e) => log::error!("window: could not ask about the unsaved changes: {e}"), + } + None +} + +/// Shows the saving-failed dialog (`ask`) on a thread of its own, its message put together on the +/// calling (UI) thread, as [`ask_device_lost`] does. +fn ask_unsaved( + changes: usize, + reason: &str, + ask: impl FnOnce((String, String, String, String)) + Send + 'static, +) -> std::io::Result> { + let message = lightcraft_ui_egui::i18n::device_lost_unsaved_message(changes, reason); + std::thread::Builder::new().name("device-lost".into()).spawn(move || ask(message)) +} + /// Start LightCraft again after the window's device was lost, with the arguments it was started /// with and renders on a device of their own (`LIGHTCRAFT_GPU_TEXTURES` cleared, so the /// default): a driver that loses shared devices can't take the new window down with a render. diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d4..d88d8fd8af9 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "Soubor {name} se nepodařilo přečíst: {e}", "Added {n} photo{}": "Přidáno fotografií: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Kam má jít katalog Lightroomu „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Sloučit s otevřenou knihovnou „{library}“ (fotografie: {count}{:.0})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Grafický ovladač přestal odpovídat, takže LightCraft už nemůže vykreslovat své okno, a knihovnu se nepodařilo uložit: {e}\n\nNeuložené změny: {n}. Pokud nyní aplikaci ukončíte, budou ztraceny. Uvolněte místo na disku nebo znovu připojte disk s knihovnou a zkuste to znovu." } diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f13647..c6c6246624f 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "{name} konnte nicht gelesen werden: {e}", "Added {n} photo{}": "{n} Foto{} hinzugefügt", "Where should the Lightroom catalog “{catalog}” go?": "Wohin soll der Lightroom-Katalog „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mit der geöffneten Bibliothek „{library}“ zusammenführen ({count} Foto{})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Der Grafiktreiber reagiert nicht mehr, daher kann LightCraft sein Fenster nicht mehr zeichnen, und die Bibliothek konnte nicht gespeichert werden: {e}\n\nNicht gespeicherte Änderungen: {n}. Wenn Sie jetzt beenden, gehen sie verloren. Schaffen Sie Speicherplatz oder schließen Sie das Laufwerk der Bibliothek wieder an und versuchen Sie es dann erneut." } diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6e..e766555a17a 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "No se pudo leer {name}: {e}", "Added {n} photo{}": "{n} foto{0} añadida{0}", "Where should the Lightroom catalog “{catalog}” go?": "¿Dónde debe ir el catálogo de Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Combinar con la biblioteca abierta “{library}” ({count} foto{})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "El controlador gráfico ha dejado de responder, así que LightCraft ya no puede dibujar su ventana, y no se ha podido guardar la biblioteca: {e}\n\nCambios sin guardar: {n}. Si sale ahora, se perderán. Libere espacio en disco o vuelva a conectar la unidad de la biblioteca y vuelva a intentarlo." } diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9f..42df2bfb213 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -305,5 +305,6 @@ "Drop to import {n} preset{}": "Pudota tuodaksesi esiasetuksia: {n}{:.0}", "Drop to review {n} item{} for import": "Pudota tarkistaaksesi ennen tuontia (kohteita: {n}){:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Minne Lightroom-luettelo ”{catalog}” tuodaan?", - "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Näytönohjaimen ajuri lakkasi vastaamasta, joten LightCraft ei voi enää piirtää ikkunaansa, ja kirjaston tallentaminen epäonnistui: {e}\n\nTallentamattomia muutoksia: {n}. Jos lopetat nyt, ne menetetään. Vapauta levytilaa tai liitä kirjaston asema uudelleen ja yritä sitten uudelleen." } diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e0..059b5a24589 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "Impossible de lire {name} : {e}", "Added {n} photo{}": "{n} photo{} ajoutée(s)", "Where should the Lightroom catalog “{catalog}” go?": "Où importer le catalogue Lightroom « {catalog} » ?", - "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})" + "Merge into the open library “{library}” ({count} photo{})": "Fusionner avec la bibliothèque ouverte « {library} » ({count} photo{})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Le pilote graphique ne répond plus : LightCraft ne peut plus dessiner sa fenêtre, et l’enregistrement de la bibliothèque a échoué : {e}\n\nModifications non enregistrées : {n}. Si vous quittez maintenant, elles seront perdues. Libérez de l’espace disque ou reconnectez le disque de la bibliothèque, puis réessayez." } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221e..29e7812a4d4 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -305,5 +305,6 @@ "Drop to review {n} item{} for import": "Jatuhkan untuk meninjau {n} item sebelum impor{:.0}", "Inside: {names}": "Di dalam: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Ke mana katalog Lightroom “{catalog}” diimpor?", - "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Driver grafis berhenti merespons, sehingga LightCraft tidak dapat lagi menggambar jendelanya, dan penyimpanan pustaka gagal: {e}\n\nPerubahan yang belum disimpan: {n}. Jika Anda keluar sekarang, perubahan itu akan hilang. Kosongkan ruang disk atau sambungkan kembali drive pustaka, lalu coba lagi." } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e945..6f804d93595 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "Impossibile leggere {name}: {e}", "Added {n} photo{}": "Foto aggiunte: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Dove importare il catalogo Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Unisci alla libreria aperta “{library}” (foto: {count}{:.0})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Il driver grafico ha smesso di rispondere, quindi LightCraft non può più disegnare la sua finestra, e il salvataggio della libreria non è riuscito: {e}\n\nModifiche non salvate: {n}. Se esci ora, andranno perse. Libera spazio su disco o ricollega l'unità della libreria, poi riprova." } diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16dc..0b69cec7406 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "{name} を読み取れませんでした: {e}", "Added {n} photo{}": "{n}枚を追加しました{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom カタログ「{catalog}」をどこに読み込みますか?", - "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "開いているライブラリ「{library}」に統合(写真{count}枚){:.0}", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "グラフィックスドライバーが応答しなくなったため、LightCraft はウインドウを描画できなくなりました。また、ライブラリを保存できませんでした: {e}\n\n保存されていない変更: {n} 件。今終了すると失われます。ディスクの空き容量を増やすか、ライブラリのドライブを接続し直してから、もう一度お試しください。" } diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46036826186..62a9aa4851e 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "ვერ წაიკითხა {name}: {e}", "Added {n} photo{}": "დაემატა ფოტო: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "სად გადავიტანოთ Lightroom-ის კატალოგი „{catalog}“?", - "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "გაერთიანება ღია ბიბლიოთეკასთან „{library}“ (ფოტოები: {count}){:.0}", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "გრაფიკულმა დრაივერმა შეწყვიტა პასუხი, ამიტომ LightCraft-ს აღარ შეუძლია თავისი ფანჯრის დახატვა, ხოლო ბიბლიოთეკის შენახვა ვერ მოხერხდა: {e}\n\nშეუნახავი ცვლილებები: {n}. თუ ახლა გახვალთ, ისინი დაიკარგება. გაათავისუფლეთ ადგილი დისკზე ან ხელახლა მიაერთეთ ბიბლიოთეკის დისკი და სცადეთ ხელახლა." } diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6e..d916fda4e5c 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -305,5 +305,6 @@ "Added {n} photo{}": "Dodano zdjęcia: {n}{:.0}", "Inside: {names}": "Wewnątrz: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Dokąd zaimportować katalog Lightroom „{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Scal z otwartą biblioteką „{library}” (zdjęcia: {count}){:.0}", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Sterownik grafiki przestał odpowiadać, więc LightCraft nie może już rysować swojego okna, a zapisanie biblioteki się nie powiodło: {e}\n\nNiezapisane zmiany: {n}. Jeśli zakończysz teraz, zostaną utracone. Zwolnij miejsce na dysku lub podłącz ponownie dysk z biblioteką, a potem spróbuj ponownie." } diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4b..4df7ab61b15 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "Não foi possível ler {name}: {e}", "Added {n} photo{}": "{n} foto{0} adicionada{0}", "Where should the Lightroom catalog “{catalog}” go?": "Para onde vai o catálogo do Lightroom “{catalog}”?", - "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})" + "Merge into the open library “{library}” ({count} photo{})": "Mesclar na biblioteca aberta “{library}” ({count} foto{})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "O driver gráfico parou de responder, então o LightCraft não consegue mais desenhar a janela, e não foi possível salvar a biblioteca: {e}\n\nAlterações não salvas: {n}. Se você sair agora, elas serão perdidas. Libere espaço em disco ou reconecte a unidade da biblioteca e tente novamente." } diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af42764..9e4145b4ad9 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "Не удалось прочитать {name}: {e}", "Added {n} photo{}": "Добавлено фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куда импортировать каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Объединить с открытой библиотекой «{library}» (фото: {count}){:.0}", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Графический драйвер перестал отвечать, поэтому LightCraft больше не может отрисовывать окно, а библиотеку не удалось сохранить: {e}\n\nНесохранённых изменений: {n}. Если выйти сейчас, они будут потеряны. Освободите место на диске или снова подключите диск с библиотекой и повторите попытку." } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c4..67968f18713 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -305,5 +305,6 @@ "Drop to review {n} item{} for import": "Släpp för att granska {n} objekt före import{:.0}", "Inside: {names}": "Inuti: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", - "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Grafikdrivrutinen slutade svara, så LightCraft kan inte längre rita sitt fönster, och det gick inte att spara biblioteket: {e}\n\nOsparade ändringar: {n}. Om du avslutar nu går de förlorade. Frigör diskutrymme eller anslut bibliotekets enhet igen och försök sedan igen." } diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a25..f6636b16fc0 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "Не вдалося прочитати {name}: {e}", "Added {n} photo{}": "Додано фото: {n}{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Куди імпортувати каталог Lightroom «{catalog}»?", - "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "Об’єднати з відкритою бібліотекою «{library}» (фото: {count}){:.0}", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Графічний драйвер перестав відповідати, тому LightCraft більше не може малювати своє вікно, а бібліотеку не вдалося зберегти: {e}\n\nНезбережених змін: {n}. Якщо вийти зараз, їх буде втрачено. Звільніть місце на диску або знову під’єднайте диск із бібліотекою й спробуйте ще раз." } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff060..ac45298ba50 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -305,5 +305,6 @@ "Drop to import {n} preset{}": "Thả để nhập {n} thiết lập sẵn{:.0}", "Drop to review {n} item{} for import": "Thả để xem lại {n} mục trước khi nhập{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Nhập danh mục Lightroom «{catalog}» vào đâu?", - "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "Trình điều khiển đồ họa đã ngừng phản hồi nên LightCraft không thể vẽ cửa sổ của mình nữa, và việc lưu thư viện đã thất bại: {e}\n\nSố thay đổi chưa lưu: {n}. Nếu bạn thoát bây giờ, chúng sẽ bị mất. Hãy giải phóng dung lượng đĩa hoặc kết nối lại ổ đĩa của thư viện, rồi thử lại." } diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b866..734e13119a4 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "无法读取 {name}:{e}", "Added {n} photo{}": "已添加 {n} 张照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目录“{catalog}”要导入到哪里?", - "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "合并到当前打开的图库“{library}”({count} 张照片){:.0}", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "图形驱动程序已停止响应,LightCraft 无法再绘制窗口,并且图库保存失败:{e}\n\n未保存的更改:{n} 项。如果现在退出,这些更改将会丢失。请释放磁盘空间或重新连接图库所在的驱动器,然后重试。" } diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a2..11f2a3ada53 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -305,5 +305,6 @@ "Could not read {name}: {e}": "無法讀取 {name}:{e}", "Added {n} photo{}": "已加入 {n} 張照片{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Lightroom 目錄「{catalog}」要匯入到哪裡?", - "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}" + "Merge into the open library “{library}” ({count} photo{})": "合併到目前開啟的照片庫「{library}」({count} 張照片){:.0}", + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.": "圖形驅動程式已停止回應,LightCraft 無法再繪製視窗,而且圖庫儲存失敗:{e}\n\n未儲存的變更:{n} 項。如果現在結束,這些變更將會遺失。請釋放磁碟空間或重新連接圖庫所在的磁碟機,然後再試一次。" } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index b20fa74d21a..433bebea5bc 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -356,6 +356,21 @@ pub fn device_lost_message() -> (String, String, String, String) { ) } +/// The native dialog shown when the window's graphics device was lost and saving then failed: +/// title, text (how many changes and why), and the two buttons (try again, quit anyway). +pub fn device_lost_unsaved_message(changes: usize, reason: &str) -> (String, String, String, String) { + ( + tr("LightCraft lost its graphics device").to_string(), + tr_format!( + "The graphics driver stopped responding, so LightCraft can't draw its window any more, and saving the library failed: {e}\n\nUnsaved changes: {n}. If you quit now, they are lost. Free some disk space or reconnect the library's drive, then try again.", + e = reason, + n = changes + ), + tr("Try Again").to_string(), + tr("Quit Anyway").to_string(), + ) +} + /// A stock preset's or profile's name in the UI language; an imported or user-edited name stays /// exactly as its owner wrote it. pub fn builtin_label(source: &str, builtin: bool) -> &str { @@ -975,6 +990,18 @@ mod tests { assert!(!value.is_empty() && value != key.as_str(), "{language:?}: {key}"); } } + // and the one shown when saving then failed, with how many changes and why + let english = device_lost_unsaved_message(3, "disk full"); + assert!(english.1.contains("disk full") && english.1.contains('3'), "{}", english.1); + for language in Locale::ALL.iter().filter(|language| **language != Locale::En) { + set_language(*language); + let message = device_lost_unsaved_message(3, "disk full"); + set_language(Locale::En); + assert!(message.1.contains("disk full") && message.1.contains('3'), "{language:?}: {}", message.1); + for (value, key) in [(&message.0, &english.0), (&message.1, &english.1), (&message.2, &english.2), (&message.3, &english.3)] { + assert!(!value.is_empty() && value != key, "{language:?}: {key}"); + } + } } /// Smart-album choice values read as words in every language (English "Public Domain"), never as diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index fd2558c0fee..15b6e9dd645 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -281,8 +281,11 @@ render that falls back to the CPU. A headless screenshot reads a texture back wh the window. A *lost* device (driver reset, GPU hang) is lost to the window too — as it was before sharing, when a reset took every device on the GPU. Renders go back to the CPU, and `lightcraft_gpu::window_device_lost()` is set: egui-wgpu panics drawing anything on a lost device, -so the app draws empty frames and asks in a native dialog to restart or quit; after saving, a -restart starts LightCraft again without `LIGHTCRAFT_GPU_TEXTURES`. A loss in the middle of a frame +so the app draws empty frames, saves, and asks in a native dialog to restart or quit; a restart +starts LightCraft again without `LIGHTCRAFT_GPU_TEXTURES`. If saving fails (the journal and the +closing snapshot both), the edits stay in memory and a native dialog says how many and why and +offers Try Again; the app ends without them only on Quit Anyway (tested by +`tests::a_lost_device_never_quits_with_edits_that_could_not_be_saved` in `apps/lightcraft`). A loss in the middle of a frame (the panic happens before the app can stop drawing) ends `run_native` with an error, and the app starts again the same way; the library has written every command to its journal, so only a slider drag in progress is lost. Tested by `crates/gpu/tests/texture_lost.rs` and From df572f86745d672fef696e17072021938e6416c6 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Sun, 18 Oct 2026 21:19:59 +0200 Subject: [PATCH 12/13] LR-VIEW-ZOOM: a device lost mid-frame starts the app again (unless edits couldn't be saved) The relaunch check sat after the came_up branch, which a frame-time panic on the lost device always took, so it showed "LightCraft stopped", wrote gpu-lost.marker and turned the GPU off. It now runs inside that branch, before the marker and the dialog, and only when the app had no changes it couldn't save as of its last frame; otherwise the stop dialog says how many. Review on PR #1240. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/main.rs | 61 ++++++++++++++++++++++++++++++++----- docs/gpu-pipeline.md | 7 +++-- 2 files changed, 59 insertions(+), 9 deletions(-) diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 9a19559c7dc..7fc4bf7c7ed 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -90,6 +90,8 @@ impl eframe::App for App { } self.0.logic(ctx); self.1.tick(&mut self.0, ctx); + // for a device lost in the middle of a frame, when this app can't save any more (`main`) + UNSAVED_CHANGES.store(unsaved_changes(&self.0.session), std::sync::atomic::Ordering::Relaxed); } /// Forwards the host's raw-input pass to the app's hook before egui processes it, keeping /// modal/prompt input barriers and queued synthetic or dropped input ahead of the panels. @@ -212,6 +214,25 @@ enum LostDevice { Ask, } +/// How many changes the running app couldn't write to disk, as of its latest frame: a device lost +/// in the middle of a frame stops the app before it can save again, and it only starts again +/// when there are none ([`relaunch_after_lost_frame`]). +static UNSAVED_CHANGES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// How many changes `session` couldn't write to disk (the journal failed); they stay queued. +fn unsaved_changes(session: &Session) -> usize { + session.unsaved().map_or(0, |(changes, _)| changes) +} + +/// `run_native` ended while the window was up: whether to start LightCraft again, with renders on +/// a device of their own. Only when it stopped on an error after the device renders share with the +/// window was lost while a frame was drawn (egui-wgpu panics there before `logic` can stop +/// drawing), and only with every change saved: edits that couldn't be written are never left +/// behind by a restart that says nothing; the stop dialog says so instead. +fn relaunch_after_lost_frame(stopped_with_error: bool, window_device_lost: bool, unsaved_changes: usize) -> bool { + stopped_with_error && window_device_lost && unsaved_changes == 0 +} + /// The running app's lost-device steps (it has one window). static LOST_STAGE: std::sync::Mutex = std::sync::Mutex::new(LostDevice::Save); @@ -1232,6 +1253,15 @@ fn main() -> eframe::Result { Ok(r) => r, Err(_) => Err(eframe::Error::AppCreation("its window stopped drawing (the renderer panicked)".into())), }; + // the device renders share with the window was lost while a frame was being drawn: start + // again the same way as after the lost-device dialog (no marker: the GPU stays on) + let unsaved = UNSAVED_CHANGES.load(std::sync::atomic::Ordering::Relaxed); + if relaunch_after_lost_frame(stopped.is_err(), lightcraft_engine::gpu::window_device_lost(), unsaved) + && window_gpu::relaunch_with_own_render_device() + { + log::error!("LightCraft lost its graphics device while drawing; starting again"); + return Ok(()); + } if let Err(e) = &stopped { let lost = gpu_lost_reason(); if let Some(reason) = &lost @@ -1240,10 +1270,13 @@ fn main() -> eframe::Result { record_gpu_lost(gpu_lost_marker_path().as_deref(), reason); } // (not "app creation error: …": the app had been created) - let what = match e { + let mut what = match e { eframe::Error::AppCreation(m) => m.to_string(), e => e.to_string(), }; + if unsaved > 0 { + what = format!("{what}; {unsaved} change(s) couldn't be saved to disk before it stopped"); + } stopped_while_running(&stopped_text(&what, lost.as_deref()), log_file.as_deref()); } return stopped; @@ -1251,12 +1284,6 @@ fn main() -> eframe::Result { // a panic that still escaped the renderer's start (the probe and error handler should // prevent it): an error like any other failed start let started = started.unwrap_or_else(|_| Err(eframe::Error::AppCreation("the window's renderer panicked while starting".into()))); - // the device renders share with the window was lost while a frame was being drawn (egui-wgpu - // panics there): not a failed start — start again, with renders on a device of their own - if started.is_err() && lightcraft_engine::gpu::window_device_lost() && window_gpu::relaunch_with_own_render_device() { - log::error!("LightCraft lost its graphics device while drawing; starting again"); - return Ok(()); - } if let Err(e) = &started { // the renderer never came up: start again, which tries the next one in the chain if window_gpu::relaunch_after_failure(&win_files) { @@ -1473,6 +1500,26 @@ mod tests { assert_eq!(answers.restart_asked, 2); } + /// PR #1240 review: a device lost in the middle of a frame (after the window came up) starts + /// LightCraft again instead of stopping with "LightCraft stopped" and the GPU off next time, + /// but never while edits couldn't be saved, and never for any other way the app ended. + #[test] + fn a_device_lost_mid_frame_starts_again_only_with_everything_saved() { + let disk = FailingDisk::default(); + let mut session = disk.session(); + session.execute("photo.rate", &serde_json::json!({"rating": 3})).unwrap(); + assert_eq!(unsaved_changes(&session), 0); + assert!(relaunch_after_lost_frame(true, true, unsaved_changes(&session)), "lost mid-frame, all saved: start again"); + // another error, or a window closed normally: no restart + assert!(!relaunch_after_lost_frame(true, false, 0)); + assert!(!relaunch_after_lost_frame(false, true, 0)); + // an edit the journal couldn't take: stop and say so, never a silent restart + disk.set_failing(true); + assert!(session.execute("photo.rate", &serde_json::json!({"rating": 4})).is_err()); + assert_eq!(unsaved_changes(&session), 1); + assert!(!relaunch_after_lost_frame(true, true, unsaved_changes(&session))); + } + /// Issue #374: launch arguments that would walk a whole drive or home folder are reported, /// not imported; empty ones are ignored; the rest are imported as absolute paths. #[test] diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 15b6e9dd645..7ff84410e74 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -287,8 +287,11 @@ closing snapshot both), the edits stay in memory and a native dialog says how ma offers Try Again; the app ends without them only on Quit Anyway (tested by `tests::a_lost_device_never_quits_with_edits_that_could_not_be_saved` in `apps/lightcraft`). A loss in the middle of a frame (the panic happens before the app can stop drawing) ends `run_native` with an error, and the app -starts again the same way; the library has written every command to its journal, so only a -slider drag in progress is lost. Tested by `crates/gpu/tests/texture_lost.rs` and +starts again the same way, without `gpu-lost.marker`; the library has written every command to its +journal, so only a slider drag in progress is lost. If the journal had failed (changes the app +couldn't save as of its last frame), it doesn't start again: the "LightCraft stopped" dialog says +how many changes couldn't be saved (`tests::a_device_lost_mid_frame_starts_again_only_with_everything_saved`). +Tested by `crates/gpu/tests/texture_lost.rs` and `window_gpu::tests::a_lost_window_device_draws_empty_frames_without_a_panic`; seen end to end with `LIGHTCRAFT_GPU_LOSE_AFTER=`, which destroys the device after n GPU renders. From e26d37144b459cb3958a841f840579d291696946 Mon Sep 17 00:00:00 2001 From: Matthew James Sivak Date: Mon, 19 Oct 2026 10:43:11 +0200 Subject: [PATCH 13/13] LR-VIEW-ZOOM: GPU tests never share a GL instance; the unsaved count is taken after the UI pass FreeBSD CI segfaulted in the app's tests: wgpu's GL backend shares one EGL display between instances and terminates it when one is dropped, so the lost-window-device test (which opened a GL instance only to skip it) could pull the display from under pipeline_errors_are_captured_not_panics drawing on Mesa GL. The GPU tests now run one at a time, and the lost-device test never opens GL at all. CodeRabbit (PR #1240): UNSAVED_CHANGES was only refreshed at the end of `logic`, so a widget's failed edit in the UI pass wasn't counted when the device was lost while that frame was painted. The UI pass now notes it too. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft/src/main.rs | 54 ++++++++++++++++++++++++++----- apps/lightcraft/src/window_gpu.rs | 22 ++++++++++--- 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 7fc4bf7c7ed..0b0156595c8 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -90,8 +90,7 @@ impl eframe::App for App { } self.0.logic(ctx); self.1.tick(&mut self.0, ctx); - // for a device lost in the middle of a frame, when this app can't save any more (`main`) - UNSAVED_CHANGES.store(unsaved_changes(&self.0.session), std::sync::atomic::Ordering::Relaxed); + self.note_unsaved(); } /// Forwards the host's raw-input pass to the app's hook before egui processes it, keeping /// modal/prompt input barriers and queued synthetic or dropped input ahead of the panels. @@ -100,12 +99,7 @@ impl eframe::App for App { } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.0.perf.host_frame_ms = frame.info().cpu_usage.map(|s| f64::from(s) * 1000.0); - // on a lost device, a frame with anything in it panics in egui-wgpu (its staging buffers - // can't be made): draw nothing until the restart (see `logic`) - if lightcraft_engine::gpu::window_device_lost() { - return; - } - self.0.ui(ui); + self.draw(ui); } fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) { // (closing the window went through `may_close`, which offers to keep unsaved changes) @@ -124,6 +118,24 @@ impl eframe::App for App { } impl App { + /// The frame's UI pass. On a lost device, a frame with anything in it panics in egui-wgpu (its + /// staging buffers can't be made): draw nothing until the restart (see `logic`). + fn draw(&mut self, ui: &mut egui::Ui) { + if lightcraft_engine::gpu::window_device_lost() { + return; + } + self.0.ui(ui); + // (widgets run commands too: counted before the frame is painted, where the device can be lost) + self.note_unsaved(); + } + + /// For a device lost in the middle of a frame, when this app can't save any more (`main`): + /// how many changes couldn't be written to disk, as of the end of `logic` and of the UI pass, + /// the two places the session changes in a frame. + fn note_unsaved(&self) { + UNSAVED_CHANGES.store(unsaved_changes(&self.0.session), std::sync::atomic::Ordering::Relaxed); + } + /// Save settings and the library, then wait for background work: closing the window or Quit /// from the macOS menu bar (which must not end the process here, so the macOS exit stays in /// `on_exit`). Returns what [`App::save`] returns. @@ -1520,6 +1532,32 @@ mod tests { assert!(!relaunch_after_lost_frame(true, true, unsaved_changes(&session))); } + /// PR #1240 review: the change count a device lost mid-frame decides by is the one at the + /// end of the frame's UI pass, where widgets run commands too, not the one `logic` saw before. + #[test] + fn a_change_that_fails_in_the_ui_pass_is_counted_before_the_frame_is_painted() { + let disk = FailingDisk::default(); + let mut app = app_on(disk.session()); + let ctx = egui::Context::default(); + let pass = |app: &mut App| { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.draw(ui)); + out.textures_delta.clear(); + }; + pass(&mut app); + assert_eq!(UNSAVED_CHANGES.load(std::sync::atomic::Ordering::Relaxed), 0); + // a widget's command the journal can't take, run after `logic` noted the count + disk.set_failing(true); + assert!(app.0.session.execute("photo.rate", &serde_json::json!({"rating": 5})).is_err()); + pass(&mut app); + assert_eq!(UNSAVED_CHANGES.load(std::sync::atomic::Ordering::Relaxed), 1, "the frame's own failed edit is counted"); + assert!(!relaunch_after_lost_frame(true, true, UNSAVED_CHANGES.load(std::sync::atomic::Ordering::Relaxed))); + // saved again: a restart is fine + disk.set_failing(false); + app.save().unwrap(); + pass(&mut app); + assert_eq!(UNSAVED_CHANGES.load(std::sync::atomic::Ordering::Relaxed), 0); + } + /// Issue #374: launch arguments that would walk a whole drive or home folder are reported, /// not imported; empty ones are ignored; the rest are imported as absolute paths. #[test] diff --git a/apps/lightcraft/src/window_gpu.rs b/apps/lightcraft/src/window_gpu.rs index 0d5cb4ff132..5d11ddb75b1 100644 --- a/apps/lightcraft/src/window_gpu.rs +++ b/apps/lightcraft/src/window_gpu.rs @@ -427,6 +427,16 @@ mod tests { assert_eq!(rx.recv().unwrap(), expected, "dialog shown in {other:?}"); } + /// Held by every test here that opens a wgpu instance, for its whole run. wgpu's GL backend + /// shares one EGL display between instances and terminates it when one is dropped, so a GL + /// instance opened and dropped by one test segfaults another drawing on Mesa GL meanwhile + /// (the FreeBSD CI runner, which has no Vulkan driver). + static GPU_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + fn one_gpu_test_at_a_time() -> std::sync::MutexGuard<'static, ()> { + GPU_TESTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) + } + fn dir(tag: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("app-window-gpu-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); @@ -474,6 +484,7 @@ mod tests { /// wgpu's default panic. Needs an adapter; skipped where there is none (CI without a GPU). #[test] fn pipeline_errors_are_captured_not_panics() { + let _gpu = one_gpu_test_at_a_time(); let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends: backend::window_backends(), ..wgpu::InstanceDescriptor::new_without_display_handle() @@ -524,17 +535,18 @@ mod tests { #[test] fn a_lost_window_device_draws_empty_frames_without_a_panic() { use eframe::egui_wgpu::{Renderer, RendererOptions, ScreenDescriptor}; + let _gpu = one_gpu_test_at_a_time(); + // Software adapters and wgpu's GL backend (Mesa GL on the FreeBSD CI runner, which has no + // Vulkan driver) segfault when a destroyed device is used, where Metal, DX12 and hardware + // Vulkan report the loss: nothing to learn there. GL isn't even opened (see `GPU_TESTS`). let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { - backends: backend::window_backends(), + backends: backend::window_backends() - Backends::GL, ..wgpu::InstanceDescriptor::new_without_display_handle() }); let Ok(adapter) = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) else { - lightcraft_testkit::skip!(Gpu, "no GPU adapter"); + lightcraft_testkit::skip!(Gpu, "no GPU adapter but GL's"); return; }; - // Software adapters and wgpu's GL backend (Mesa GL on the FreeBSD CI runner, which has no - // Vulkan driver) segfault when a destroyed device is used, where Metal, DX12 and hardware - // Vulkan report the loss: nothing to learn there. let info = adapter.get_info(); if info.device_type == wgpu::DeviceType::Cpu || info.backend == wgpu::Backend::Gl { lightcraft_testkit::skip!(Gpu, "{} adapter {} crashes on a destroyed device", info.backend, info.name);