PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Large documents: a gigapixel New Document draws without freezing (#4017)
David Mannebd3c1227008
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex f1625b7a2..67a349b8a 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -29,6 +29,7 @@ pub mod pattern;pub mod proxy;pub mod psblend;pub mod shape_split;+mod uniform;use photocraft_color::blend::BlendMode;use photocraft_doc::{Document, Fill, Layer, LayerContent, Pattern};@@ -377,6 +378,38 @@ pub fn render_reduced_damage(doc: &Document, w: u32, h: u32, damage: Rect) -> Bu/// [`render_reduced_rect`] (or, with `damage`, [`render_reduced_damage`]) of area `b` with an/// explicit band height (see [`render_bands`]).fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Option<Rect>, band_rows: i32) -> Buffer {+ render_reduced_with(doc, b, w, h, damage, band_rows, true, &mut ReducedStats::default())+}++/// What a reduced render composited (tests check that one-colour areas are not composited).+#[derive(Debug, Default)]+struct ReducedStats {+ /// Whether one-colour areas were looked for ([`uniform::UniformAreas`]).+ uniform: bool,+ /// Document pixels composited one by one.+ composited: u64,+}++/// A tile of a reduced render: one colour (premultiplied), or its composited pixels.+enum Part {+ Solid([f32; 4]),+ Px(Buffer),+}++/// A column of document tiles in a reduced render (`b`-relative source columns).+struct TileColumn {+ /// The columns rendered: the tile's, within the source area.+ x0: usize,+ x1: usize,+ /// The whole tile's columns within `b`, whose values decide whether it is one colour.+ whole: (i64, i64),+ /// Runs of (output column, how many of the rendered columns it averages).+ runs: Vec<(usize, f32)>,+}++/// [`render_reduced_in_bands`]; `uniform` off composites every pixel (the reference in tests).+#[allow(clippy::too_many_arguments)]+fn render_reduced_with(doc: &Document, b: Rect, w: u32, h: u32, damage: Option<Rect>, band_rows: i32, uniform: bool, stats: &mut ReducedStats) -> Buffer {let (fw, fh) = (b.width() as usize, b.height() as usize);let (w, h) = (w.clamp(1, b.width().max(1)) as usize, h.clamp(1, b.height().max(1)) as usize);let full = Rect::from_xywh(0, 0, w as u32, h as u32);@@ -420,22 +453,14 @@ fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Optilet (cols, rows) = (map(fw, w), map(fh, h));let cols = &cols[sx0..sx1];let mut acc = vec![[0.0f32; 4]; ow * oh];- let ok: Result<(), ()> = render_bands(doc, src, band_rows, |band| {- let (by0, by1) = ((band.rect.y0 - b.y0) as usize, (band.rect.y1 - b.y0) as usize);+ // Each output row sums its source rows in a band (in order, top to bottom), each row's pixels+ // left to right: `row(y, out)` adds source row `y` (band-relative) to output row `out`.+ let sum_band = |acc: &mut [[f32; 4]], by0: usize, by1: usize, row: &(dyn Fn(usize, &mut [[f32; 4]]) + Sync)| {let (t0, t1) = (rows[by0] as usize, rows[by1 - 1] as usize + 1);- let sw = sx1 - sx0;- // Each output row sums its source rows in this band (in order, top to bottom).let sum_row = |t: usize, out: &mut [[f32; 4]]| {let (a, z) = span(t, fh, h);for y in a.max(by0)..z.min(by1) {- let src = &band.px[(y - by0) * sw..(y - by0 + 1) * sw];- for (p, &c) in src.iter().zip(cols) {- let o = &mut out[c as usize - ox0];- for i in 0..3 {- o[i] += p[i] * p[3];- }- o[3] += p[3];- }+ row(y - by0, out);}};let part = &mut acc[(t0 - oy0) * ow..(t1 - oy0) * ow];@@ -448,9 +473,110 @@ fn render_reduced_in_bands(doc: &Document, b: Rect, w: u32, h: u32, damage: Optifor (i, out) in part.chunks_mut(ow).enumerate() {sum_row(t0 + i, out);}- Ok(())- });- debug_assert!(ok.is_ok());+ };+ let add = |o: &mut [f32; 4], p: &[f32; 4]| {+ for i in 0..3 {+ o[i] += p[i] * p[3];+ }+ o[3] += p[3];+ };+ if let Some(uniform) = uniform.then(|| uniform::UniformAreas::new(doc)).flatten() {+ stats.uniform = true;+ // One-colour tiles (a new document's background, the empty parts of a sparse one) are+ // composited once per colour and summed per run of source columns, not per pixel+ // (#4017). Tiles lie on the document's tile grid whatever `damage` is, so a damage+ // render sums exactly what the whole reduction does.+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);+ let cx = Ctx::for_doc(doc, &patterns);+ let t = RENDER_TILE as usize;+ // The document tile grid (the surfaces' own), in `b`-relative coordinates: the start of+ // the tile holding `v` (negative when `b` starts inside a tile).+ let grid = |v: usize, o: i32| (i64::from(o) + v as i64).div_euclid(t as i64) * t as i64 - i64::from(o);+ let tile_cols: Vec<TileColumn> = (grid(sx0, b.x0)..sx1 as i64)+ .step_by(t)+ .map(|gx| {+ let (x0, x1) = ((gx.max(0) as usize).max(sx0), ((gx + t as i64) as usize).min(sx1));+ let mut runs: Vec<(usize, f32)> = Vec::new();+ for &c in &cols[x0 - sx0..x1 - sx0] {+ match runs.last_mut() {+ Some((last, n)) if *last == c as usize - ox0 => *n += 1.0,+ _ => runs.push((c as usize - ox0, 1.0)),+ }+ }+ TileColumn { x0, x1, whole: (gx.max(0), (gx + t as i64).min(fw as i64)), runs }+ })+ .collect();+ let band_h = band_rows_for(src.width(), band_rows).max(RENDER_TILE) as usize;+ let mut y = grid(sy0, b.y0);+ while y < sy1 as i64 {+ let y1 = (y + band_h as i64).min(sy1 as i64);+ let tiles: Vec<(Rect, Rect)> = (y..y1)+ .step_by(t)+ .flat_map(|gy| {+ tile_cols.iter().map(move |&TileColumn { x0, x1, whole: (gx0, gx1), .. }| {+ let at = |x0: i64, y0: i64, x1: i64, y1: i64| Rect::new(b.x0 + x0 as i32, b.y0 + y0 as i32, b.x0 + x1 as i32, b.y0 + y1 as i32);+ let (gy0, gy1) = (gy.max(0), (gy + t as i64).min(fh as i64));+ (at(gx0, gy0, gx1, gy1), at(x0 as i64, gy0.max(sy0 as i64), x1 as i64, gy1.min(sy1 as i64)))+ })+ })+ .collect();+ let one = |(whole, part): &(Rect, Rect)| -> Part {+ let render = |r: Rect| render_tiled_with(doc, r, RENDER_TILE, &cx);+ match uniform.color(*whole, |r| render(r).px.first().copied()) {+ Some(p) => Part::Solid([p[0] * p[3], p[1] * p[3], p[2] * p[3], p[3]]),+ None => Part::Px(render(*part)),+ }+ };+ #[cfg(not(target_arch = "wasm32"))]+ let parts: Vec<Part> = {+ use rayon::prelude::*;+ tiles.par_iter().map(one).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let parts: Vec<Part> = tiles.iter().map(one).collect();+ stats.composited += parts.iter().map(|p| if let Part::Px(b) = p { b.px.len() as u64 } else { 0 }).sum::<u64>();+ let (by0, by1) = (y.max(sy0 as i64) as usize, y1 as usize);+ let n = tile_cols.len();+ let band_y = y;+ sum_band(&mut acc, by0, by1, &|row: usize, out: &mut [[f32; 4]]| {+ let y = (by0 + row) as i64;+ let j = (y - band_y) as usize / t;+ let ty = (y - (band_y + (j * t) as i64).max(sy0 as i64)) as usize;+ for (TileColumn { x0, x1, runs, .. }, part) in tile_cols.iter().zip(parts.iter().skip(j * n).take(n)) {+ match part {+ Part::Solid(pa) => {+ for &(c, k) in runs {+ let o = &mut out[c];+ for i in 0..4 {+ o[i] += pa[i] * k;+ }+ }+ }+ Part::Px(buf) => {+ let tw = x1 - x0;+ for (p, &c) in buf.px.iter().skip(ty * tw).take(tw).zip(&cols[x0 - sx0..x1 - sx0]) {+ add(&mut out[c as usize - ox0], p);+ }+ }+ }+ }+ });+ y = y1;+ }+ } else {+ let ok: Result<(), ()> = render_bands(doc, src, band_rows, |band| {+ stats.composited += band.px.len() as u64;+ let (by0, by1) = ((band.rect.y0 - b.y0) as usize, (band.rect.y1 - b.y0) as usize);+ let sw = sx1 - sx0;+ sum_band(&mut acc, by0, by1, &|y: usize, out: &mut [[f32; 4]]| {+ for (p, &c) in band.px[y * sw..(y + 1) * sw].iter().zip(cols) {+ add(&mut out[c as usize - ox0], p);+ }+ });+ Ok(())+ });+ debug_assert!(ok.is_ok());+ }for (i, p) in acc.iter_mut().enumerate() {let ((x0, x1), (y0, y1)) = (span(ox0 + i % ow, fw, w), span(oy0 + i / ow, fh, h));let n = ((y1 - y0) * (x1 - x0)).max(1) as f32;diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex 69504e4a9..a41ddfa62 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -2570,3 +2570,105 @@ fn effect_cache_follows_a_group_childs_blend_if() {assert!(before.px != cold.px, "Blend If should change the group's shadow");assert!(warm.px == cold.px, "stale group effect maps after a child's Blend If changed");}++/// A document whose one-colour areas are found: shared background tiles, a painted patch over+/// tile edges, a uniform mask tile, an adjustment, a group, a 16-bit layer and a hidden one.+fn sparse_doc(w: u32, h: u32) -> Document {+ let mut d = doc_white(w, h);+ let mut paint = Layer::raster("paint", PixelFormat::RGBA8);+ let s = paint.surface_mut().unwrap();+ for y in 200..330 {+ s.fill_rect(Rect::new(240, y, 520, y + 1), &[(y - 200) as f32 / 130.0, 0.4, 0.7, 0.8]);+ }+ s.fill_rect(Rect::new(0, 600, w as i32 / 2, 900), &[0.2, 0.9, 0.1, 0.5]);+ let mut m = LayerMask::reveal_all();+ m.surface.fill_rect(Rect::new(0, 512, 256, 768), &[0.25]);+ m.surface.fill_rect(Rect::new(300, 700, 310, 710), &[0.0]);+ paint.mask = Some(m);+ paint.blend = BlendMode::Multiply;+ let mut deep = solid_layer("deep", Rect::new(100, 100, 700, 400), [0.3, 0.3, 0.9, 0.6]);+ deep.content = LayerContent::Raster(deep.surface().unwrap().convert(PixelFormat::new(ColorMode::Rgb, SampleType::U16, true)));+ let mut hidden = solid_layer("hidden", Rect::new(0, 0, 50, 50), [1.0, 0.0, 0.0, 1.0]);+ hidden.visible = false;+ d.layers.push(Layer::group("g", vec![paint, deep, hidden]));+ d.layers.push(Layer::new("levels", LayerContent::Adjustment(Adjustment::Exposure { exposure: 0.4, offset: 0.0, gamma: 1.1 })));+ d+}++#[test]+fn one_colour_areas_reduce_like_composited_ones() {+ // #4017: one-colour tiles are composited once and summed per run of columns: the same+ // averages as compositing every pixel (to float rounding), and a damage render gives exactly+ // the whole reduction's pixels, so a reduced canvas updated in parts shows no seams.+ let d = sparse_doc(2000, 2100);+ for (b, w, h, band) in [+ (d.bounds(), 37, 41, 0),+ (d.bounds(), 250, 2100, 256),+ (d.bounds(), 1999, 3, 512),+ (Rect::new(-300, -77, 2200, 2300), 61, 29, 0),+ (Rect::new(13, 5, 2000, 2100), 1, 1, 256),+ ] {+ let reference = render_reduced_with(&d, b, w, h, None, band, false, &mut ReducedStats::default());+ let mut stats = ReducedStats::default();+ let all = render_reduced_with(&d, b, w, h, None, band, true, &mut stats);+ assert!(stats.uniform);+ assert!(stats.composited < u64::from(b.width()) * u64::from(b.height()) / 2, "{b:?}: {stats:?}");+ assert_eq!(all.rect, reference.rect);+ for (p, q) in all.px.iter().zip(&reference.px) {+ assert!(p.iter().zip(q).all(|(a, b)| (a - b).abs() < 1e-4), "{b:?} {w}x{h} band {band}: {p:?} vs {q:?}");+ }+ for dmg in [Rect::new(250, 210, 260, 220), Rect::new(0, 0, 2000, 2100), Rect::new(-50, 640, 3000, 641), Rect::new(1500, 1500, 1600, 1900)] {+ let part = render_reduced_with(&d, b, w, h, Some(dmg), band, true, &mut ReducedStats::default());+ for y in part.rect.y0..part.rect.y1 {+ for x in part.rect.x0..part.rect.x1 {+ assert_eq!(part.get(x, y), all.get(x, y), "{b:?} {w}x{h} band {band} {dmg:?} at {x},{y}");+ }+ }+ }+ }+}++#[test]+fn layers_that_read_other_pixels_are_composited_pixel_by_pixel() {+ let base = sparse_doc(300, 300);+ let edits: [fn(&mut Layer); 4] = [+ |l| l.blend = BlendMode::Dissolve,+ |l| l.mask.get_or_insert_with(LayerMask::reveal_all).feather = 3.0,+ |l| l.effects.items.push(stroke(2.0, StrokePosition::Outside)),+ |l| l.content = LayerContent::Fill(Fill::Solid(Color::BLACK)),+ ];+ for edit in edits {+ let mut d = base.clone();+ edit(&mut d.layers[0]);+ let mut stats = ReducedStats::default();+ render_reduced_with(&d, d.bounds(), 30, 30, None, 0, true, &mut stats);+ assert!(!stats.uniform);+ assert_eq!(stats.composited, 300 * 300);+ }+ let mut d = base.clone();+ d.layers.push(Layer::new("map", LayerContent::Adjustment(Adjustment::GradientMap { stops: vec![], reverse: false, dither: true })));+ let mut stats = ReducedStats::default();+ render_reduced_with(&d, d.bounds(), 30, 30, None, 0, true, &mut stats);+ assert!(!stats.uniform);+}++#[test]+fn a_gigapixel_new_document_reduces_without_compositing_its_canvas() {+ // #4017: the reduced canvas of a 10 x 5 m, 200 ppi document (3.1 GP) composited every pixel+ // (25 s on 32 threads, all cores busy). Only the partial tiles at its right and bottom edges+ // hold two values; the rest is one shared white tile.+ let (w, h) = (78_740u32, 39_370u32);+ for fill in [Some(Color::WHITE), Some(Color::rgba(0.2, 0.4, 0.6, 1.0)), None] {+ let mut d = match fill {+ Some(c) => Document::with_background("big", Size::new(w, h), ColorMode::Rgb, SampleType::U8, c),+ None => Document::new("big", Size::new(w, h), ColorMode::Rgb, SampleType::U8),+ };+ d.layers.push(Layer::raster("Layer 1", PixelFormat::RGBA8));+ let mut stats = ReducedStats::default();+ let r = render_reduced_with(&d, d.bounds(), 3937, 1969, None, 0, true, &mut stats);+ let edge_tiles = u64::from(w.div_ceil(256) + h.div_ceil(256) - 1);+ assert!(stats.composited <= edge_tiles * 256 * 256, "{fill:?}: {stats:?}");+ let want = fill.map_or([0.0; 4], |c| [c.c[0], c.c[1], c.c[2], 1.0]);+ assert!(r.px.iter().all(|p| close4(*p, want)), "{fill:?}");+ }+}diff --git a/crates/compose/src/uniform.rs b/crates/compose/src/uniform.rsnew file mode 100644index 000000000..e9423d0e6--- /dev/null+++ b/crates/compose/src/uniform.rs@@ -0,0 +1,107 @@+//! One-colour areas of a composite, known without compositing them pixel by pixel.+//!+//! A new document is a canvas of one shared white tile (or no tiles at all), and a sparse one is+//! mostly that. When every layer composites pixel by pixel from its own pixels (no effects,+//! feathered masks, dissolve, dithering or layer kinds laid out on the canvas), an area over which+//! every surface holds one value composites to one colour: one pixel of it is composited and+//! stands for the rest. The reduced canvas of a gigapixel document (#4017) then costs what its+//! painted tiles cost, not a composite of every document pixel.++use std::collections::HashMap;+use std::sync::{Mutex, PoisonError};++use photocraft_color::blend::BlendMode;+use photocraft_doc::{Adjustment, Document, LayerContent};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++/// The surfaces a document composites from, when its composite at each pixel depends only on+/// their values at that pixel.+pub(crate) struct UniformAreas<'a> {+ surfaces: Vec<&'a Surface>,+ /// One value per tile (by address), or `None` when its pixels differ: each tile is scanned once.+ tile_values: Mutex<HashMap<usize, Option<Box<[u8]>>>>,+ /// The composite colour of each combination of surface values met so far.+ colors: Mutex<HashMap<Vec<u8>, [f32; 4]>>,+}++impl<'a> UniformAreas<'a> {+ /// `None` when some layer's composite depends on more than its pixels at the same place.+ pub(crate) fn new(doc: &'a Document) -> Option<Self> {+ if doc.mode == photocraft_color::ColorMode::Multichannel {+ return None;+ }+ let mut surfaces = Vec::new();+ for (_, _, l) in doc.walk() {+ let effects = l.effects.enabled && !l.effects.items.is_empty();+ if effects || l.vector_mask.is_some() || l.video.is_some() || l.blend == BlendMode::Dissolve {+ return None;+ }+ if let Some(m) = &l.mask {+ if m.feather != 0.0 {+ return None;+ }+ surfaces.push(&m.surface);+ }+ match &l.content {+ LayerContent::Raster(s) => surfaces.push(s),+ LayerContent::Group(g) if g.artboard.is_none() => {}+ LayerContent::Adjustment(a) if per_pixel(a) => {}+ _ => return None,+ }+ }+ Some(Self { surfaces, tile_values: Mutex::default(), colors: Mutex::default() })+ }++ /// The colour every pixel of `r` composites to, when every surface holds one value over it;+ /// `composite` renders one pixel the first time a combination of values is met.+ pub(crate) fn color(&self, r: Rect, composite: impl FnOnce(Rect) -> Option<[f32; 4]>) -> Option<[f32; 4]> {+ if r.is_empty() {+ return None;+ }+ let mut key = Vec::new();+ for s in &self.surfaces {+ key.extend_from_slice(&self.value_over(s, r)?);+ }+ if let Some(c) = self.colors.lock().unwrap_or_else(PoisonError::into_inner).get(&key) {+ return Some(*c);+ }+ let c = composite(Rect::from_xywh(r.x0, r.y0, 1, 1))?;+ self.colors.lock().unwrap_or_else(PoisonError::into_inner).insert(key, c);+ Some(c)+ }++ /// The one encoded value `s` holds over `r`, if it holds one.+ fn value_over(&self, s: &Surface, r: Rect) -> Option<Box<[u8]>> {+ let mut found: Option<Box<[u8]>> = None;+ for c in r.tiles() {+ let v = match s.tile(c) {+ None => Some(Box::from(s.default_bytes())),+ Some(t) => {+ let id = std::sync::Arc::as_ptr(t) as usize;+ let cached = self.tile_values.lock().unwrap_or_else(PoisonError::into_inner).get(&id).cloned();+ match cached {+ Some(v) => v,+ None => {+ let bpp = s.default_bytes().len().max(1);+ let mut px = t.bytes().chunks_exact(bpp);+ let v = px.next().filter(|p0| px.all(|p| p == *p0)).map(Box::from);+ self.tile_values.lock().unwrap_or_else(PoisonError::into_inner).insert(id, v.clone());+ v+ }+ }+ }+ }?;+ if found.as_ref().is_some_and(|f| *f != v) {+ return None;+ }+ found = Some(v);+ }+ found+ }+}++/// Whether adjustment `a` maps each pixel on its own (dithered ones vary with the position).+fn per_pixel(a: &Adjustment) -> bool {+ !matches!(a, Adjustment::GradientMap { dither: true, .. } | Adjustment::ColorLookup { dither: true, .. })+}diff --git a/crates/ui-egui/examples/perf_scenarios.rs b/crates/ui-egui/examples/perf_scenarios.rsindex 1b7125847..1ac4c8ea8 100644--- a/crates/ui-egui/examples/perf_scenarios.rs+++ b/crates/ui-egui/examples/perf_scenarios.rs@@ -252,6 +252,8 @@ struct Sizes {big_photo: (u32, u32),/// A4 at 300 ppi.a4: (u32, u32),+ /// A new 10 × 5 m document at 200 ppi (3.1 GP, #4017).+ huge_new: (u32, u32),}const FULL: Sizes = Sizes {@@ -263,6 +265,7 @@ const FULL: Sizes = Sizes {ten_mp: (3872, 2592),big_photo: (6000, 4000),a4: (2480, 3508),+ huge_new: (78_740, 39_370),};const QUICK: Sizes = Sizes {@@ -274,6 +277,7 @@ const QUICK: Sizes = Sizes {ten_mp: (1200, 800),big_photo: (1600, 1066),a4: (1240, 1754),+ huge_new: (20_000, 10_000),};/// The layered document of #209: a background, six pixel layers with a drop shadow and a stroke,@@ -866,6 +870,7 @@ fn algorithm_scenarios(b: &mut Bench, sz: &Sizes) {}}liquify_preview_scenario(b);+ huge_new_scenario(b, sz);let cmyk = "brush dab on A4 300 ppi CMYK + refresh";if b.wanted(cmyk) {let (w, h) = sz.a4;@@ -929,6 +934,30 @@ fn algorithm_scenarios(b: &mut Bench, sz: &Sizes) {}}+/// #4017: File > New at 10 × 5 m, 200 ppi (3.1 GP), and the first refresh of the canvas that+/// draws a document too large for GPU textures (the reduced CPU canvas, `canvas::ensure_texture`).+fn huge_new_scenario(b: &mut Bench, sz: &Sizes) {+ let name = "new 3 GP document + first reduced canvas refresh";+ if !b.wanted(name) {+ return;+ }+ let (w, h) = sz.huge_new;+ let reps = b.reps.min(3);+ b.time(name, &mut Session::new(), reps, false, |_, s, _| {+ let t = Instant::now();+ exec(s, "file.new", json!({"width": w, "height": h, "resolution": 200, "background": "white"}))?;+ let doc = &s.active().ok_or("no document")?.doc;+ let factor = w.max(h).div_ceil(photocraft_ui_egui::canvas::MAX_TEXTURE).max(1);+ let reduced = photocraft_compose::render_reduced(doc, w / factor, h / factor);+ if reduced.px.first() != Some(&[1.0; 4]) {+ return Err("the new document is not white".into());+ }+ let v = ms(t);+ exec(s, "file.close", json!({}))?;+ Ok(v)+ });+}+/// A source-resolution Liquify brush update on the visible part of a 3500×2200 layer./// Reports the old whole-document proxy cost alongside the full-resolution cropped update.fn liquify_preview_scenario(b: &mut Bench) {diff --git a/crates/ui-egui/src/gpu_canvas.rs b/crates/ui-egui/src/gpu_canvas.rsindex bcf0e6951..0126f5aaf 100644--- a/crates/ui-egui/src/gpu_canvas.rs+++ b/crates/ui-egui/src/gpu_canvas.rs@@ -1553,11 +1553,34 @@ fn init_buffer(device: &wgpu::Device, label: &str, contents: &[u8], usage: wgpu:impl DocTextures {/// The texture set for a `size` canvas, or `None` (nothing created) when it doesn't fit- /// the canvas budget.- fn new(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Option<Self> {- if canvas_texture_bytes(size, tile, texel_bytes(format)) > res.canvas_budget {+ /// the canvas budget or the GPU's memory. A set the GPU can't hold (a 3 GP canvas is 16 GB+ /// of textures, #4017) lowers the budget below it, so that canvas and larger ones are drawn+ /// on the CPU canvas instead of the out-of-memory error disabling the GPU for the session.+ fn new(device: &wgpu::Device, res: &mut Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Option<Self> {+ let bytes = canvas_texture_bytes(size, tile, texel_bytes(format));+ if bytes > res.canvas_budget {return None;}+ let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);+ let memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);+ let set = Self::create(device, res, size, tile, format);+ // Native wgpu reports these synchronously; where they arrive later (WebGPU) none is seen.+ let mut cx = std::task::Context::from_waker(std::task::Waker::noop());+ let mut error = None;+ for pop in [memory.pop(), validation.pop()] {+ if let std::task::Poll::Ready(Some(e)) = std::pin::pin!(pop).poll(&mut cx) {+ error.get_or_insert(e);+ }+ }+ if let Some(e) = error {+ log::warn!("{} MB of canvas textures failed ({e}); larger canvases are drawn on the CPU", bytes >> 20);+ res.canvas_budget = res.canvas_budget.min(bytes.saturating_sub(1));+ return None;+ }+ Some(set)+ }++ fn create(device: &wgpu::Device, res: &Resources, size: [u32; 2], tile: u32, format: wgpu::TextureFormat) -> Self {let mut tiles = Vec::new();for ty in (0..size[1]).step_by(tile as usize) {for tx in (0..size[0]).step_by(tile as usize) {@@ -1592,7 +1615,7 @@ impl DocTextures {tiles.push(Tile { rect: [tx, ty, w, h], texture, levels, bind_group, _uniform: uniform });}}- Some(Self { size, format, tiles })+ Self { size, format, tiles }}/// Write `size` pixels at document `origin` from `texels` (in the texture format, row stridediff --git a/crates/ui-egui/src/gpu_canvas_mip_tests.rs b/crates/ui-egui/src/gpu_canvas_mip_tests.rsindex a1c3e8ee1..b61b77ff1 100644--- a/crates/ui-egui/src/gpu_canvas_mip_tests.rs+++ b/crates/ui-egui/src/gpu_canvas_mip_tests.rs@@ -63,6 +63,30 @@ fn canvas_mips_preserve_opaque_pixels_and_partial_updates() {gpu.rs.renderer.write().callback_resources.get_mut::<Resources>().unwrap().separate_mip_targets = separate;check_mips(&gpu);}+ // On the same device (see the top of the file).+ canvas_textures_the_gpu_refuses_leave_it_working(&gpu);+}++/// #4017: a 3 GP canvas's 16 GB of textures failed with Out of Memory, and the uncaptured error+/// disabled the GPU for the session. A refused set is now caught: nothing is kept, the budget+/// drops below it (that canvas goes to the CPU canvas) and the device stays usable. A texture+/// wider than the device allows is refused the same way, synchronously, on any adapter.+fn canvas_textures_the_gpu_refuses_leave_it_working(gpu: &GpuCanvas) {+ let max = gpu.rs.device.limits().max_texture_dimension_2d;+ let (size, tile) = ([max + 1, 1], max + 1);+ let bytes = canvas_texture_bytes(size, tile, texel_bytes(FORMAT));+ {+ let mut renderer = gpu.rs.renderer.write();+ let res = renderer.callback_resources.get_mut::<Resources>().unwrap();+ res.canvas_budget = u64::MAX;+ assert!(DocTextures::new(&gpu.rs.device, res, size, tile, FORMAT).is_none());+ assert!(res.canvas_budget < bytes, "{} >= {bytes}", res.canvas_budget);+ }+ assert!(gpu.health.is_ok(), "{:?}", gpu.fault());+ // Smaller canvases still get GPU textures.+ gpu.upload_buffer_full(3, &Buffer::filled(Rect::from_xywh(0, 0, 64, 64), [0.5, 0.5, 0.5, 1.0]), SampleType::U8);+ assert!(gpu.rs.renderer.read().callback_resources.get::<Resources>().unwrap().docs.contains_key(&3));+ assert!(gpu.health.is_ok(), "{:?}", gpu.fault());}fn check_mips(gpu: &GpuCanvas) {diff --git a/docs/scorecard.md b/docs/scorecard.mdindex af13a3f26..1e038f161 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -6,7 +6,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| Area | Done | Partial | Missing | Key numbers ||---|---:|---:|---:|---|-| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |+| [Performance](#performance) | 3 | 22 | 23 | 57 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 18 not run, 5 not measurable yet (baseline 2026-10-05) || [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 || [Tools](#tools) | 28 | 14 | 1 | || [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) |@@ -75,6 +75,7 @@ Baseline: 2026-10-05, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pr| P57 | Chisel bevel size change, 12 MP text paragraph, size 250 (GPU) | track only | – | – | – | – | – | not run | || P58 | Chisel bevel size change, 12 MP ellipse, size 8 (CPU) | track only | – | – | – | – | – | not run | || P59 | Chisel bevel size change, 12 MP text paragraph, size 8 (CPU) | track only | – | – | – | – | – | not run | |+| P61 | File > New 10 x 5 m at 200 ppi (3.1 GP) + first reduced canvas refresh | track only | – | – | – | – | – | not run | [#4017](https://github.com/storytold/photocraft/issues/4017) |**Not measurable yet** (the code can't do it yet; no number is recorded):diff --git a/perf/budgets.toml b/perf/budgets.tomlindex a95c1c83d..d02f7d1ce 100644--- a/perf/budgets.toml+++ b/perf/budgets.toml@@ -518,3 +518,10 @@ id = "P59"title = "Chisel bevel size change, 12 MP text paragraph, size 8 (CPU)"bench = "bevel_bench"row = "bevel size change to 8, text (CPU)"++[[scenario]]+id = "P61"+title = "File > New 10 x 5 m at 200 ppi (3.1 GP) + first reduced canvas refresh"+issue = 4017+bench = "perf_scenarios"+row = "new 3 GP document + first reduced canvas refresh"