GPU compositor: page layer surfaces beyond 16384 px with a memory budget (#187)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Brandon ThomasandClaude Opus 5.5 committed 2026-10-05 07:49:28 -04:00
1 parent b22deaa944
commit 851e605d98
7 files changed
+1138 -195

No files matched your search

+22 -9
View File
@@ -92,15 +92,7 @@ impl MapProgram {
/// the reach each field was computed with.
pub fn windows(&self, d: Rect, region: Rect, field_reach: &dyn Fn(FieldKind) -> i32) -> Vec<Rect> {
let n = self.stages.len();
let reach_of = |reach: &[i32], i: Option<In>| match i {
Some(In::Val(k)) => reach[k],
Some(In::Field(f)) => field_radius(f, field_reach(f)),
_ => 0,
};
let mut reach = vec![0i32; n];
for (i, s) in self.stages.iter().enumerate() {
reach[i] = reach_of(&reach, s.a).max(reach_of(&reach, s.b)).max(reach_of(&reach, s.s)) + s.radius;
}
let reach = self.stage_reach(field_reach);
let mut need = vec![Rect::EMPTY; n];
for (i, s) in self.stages.iter().enumerate() {
if s.out.is_some() {
@@ -123,6 +115,27 @@ impl MapProgram {
need
}
/// Per stage, how far (px) its output depends on the shape.
fn stage_reach(&self, field_reach: &dyn Fn(FieldKind) -> i32) -> Vec<i32> {
let mut reach: Vec<i32> = Vec::with_capacity(self.stages.len());
for s in &self.stages {
let of = |i: Option<In>| match i {
Some(In::Val(k)) => reach.get(k).copied().unwrap_or(0),
Some(In::Field(f)) => field_radius(f, field_reach(f)),
_ => 0,
};
let r = of(s.a).max(of(s.b)).max(of(s.s)) + s.radius;
reach.push(r);
}
reach
}
/// How far (px) any final map depends on the shape: maps computed over a window are exact
/// at least this far inside it.
pub fn reach(&self, field_reach: &dyn Fn(FieldKind) -> i32) -> i32 {
self.stage_reach(field_reach).into_iter().zip(&self.stages).filter(|(_, s)| s.out.is_some()).map(|(r, _)| r).max().unwrap_or(0)
}
/// Physical temporary index per stage (None for final maps), reusing temporaries after
/// their last read; returns (assignment, temporaries needed).
pub fn temps(&self) -> (Vec<Option<usize>>, usize) {
+566 -155
View File
File diff suppressed because it is too large. Load diff
+156 -27
View File
@@ -13,8 +13,14 @@ struct Gpu {
device: wgpu::Device,
queue: wgpu::Queue,
comp: Compositor,
/// The same device with a simulated texture limit of [`PAGED_LIMIT`]: every check also runs
/// through layer pages and per-cell effect maps.
paged: Compositor,
}
/// Simulated texture limit (pages and chunks of 256 px).
const PAGED_LIMIT: u32 = 256;
fn gpu() -> Option<Gpu> {
let instance = wgpu::Instance::default();
let adapter = match pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) {
@@ -38,7 +44,9 @@ fn gpu() -> Option<Gpu> {
return None;
}
};
Some(Gpu { device, queue, comp })
let mut paged = Compositor::try_new_with_format(&device, wgpu::TextureFormat::Rgba32Float).ok()?;
paged.set_texture_limit(PAGED_LIMIT);
Some(Gpu { device, queue, comp, paged })
}
/// Any adapter and device, for the fallback-path tests (which don't need 32-bit float targets).
@@ -88,11 +96,10 @@ fn base_doc(w: u32, h: u32) -> Document {
d
}
fn check(g: &mut Gpu, doc: &Document, what: &str) {
let cpu = photocraft_compose::flatten(doc);
let out = render_to_vec(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).unwrap_or_else(|e| panic!("{what}: {e}"));
/// Largest premultiplied difference between `cpu` and `gpu` pixels, and its index.
fn worst_diff(cpu: &[[f32; 4]], gpu: &[[f32; 4]]) -> (f32, usize) {
let mut worst = (0.0f32, 0usize);
for (i, (c, o)) in cpu.px.iter().zip(&out).enumerate() {
for (i, (c, o)) in cpu.iter().zip(gpu).enumerate() {
let pc = [c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3]];
let po = [o[0] * o[3], o[1] * o[3], o[2] * o[3], o[3]];
for k in 0..4 {
@@ -102,9 +109,29 @@ fn check(g: &mut Gpu, doc: &Document, what: &str) {
}
}
}
let w = doc.size.width as usize;
let (x, y) = (worst.1 % w, worst.1 / w);
assert!(worst.0 <= TOL, "{what}: max diff {:.2}/255 at ({x},{y}): cpu {:?} gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1]);
worst
}
/// GPU (whole textures, then pages) vs CPU over `rect`: Err with the worst pixel if over the
/// tolerance, else the stats of the unpaged render.
fn diff_rect(g: &mut Gpu, doc: &Document, rect: Rect, what: &str) -> Result<photocraft_gpu::Stats, String> {
let cpu = photocraft_compose::render(doc, rect);
let mut first = None;
for (label, comp) in [("", &mut g.comp), (" (paged)", &mut g.paged)] {
let (out, stats) = photocraft_gpu::render_to_vec_stats(comp, &g.device, &g.queue, doc, rect).map_err(|e| format!("{what}{label}: {e}"))?;
let worst = worst_diff(&cpu.px, &out);
let w = rect.width() as usize;
let (x, y) = (rect.x0 + (worst.1 % w) as i32, rect.y0 + (worst.1 / w) as i32);
if worst.0 > TOL {
return Err(format!("{what}{label}: max diff {:.2}/255 at ({x},{y}): cpu {:?} gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1]));
}
first.get_or_insert(stats);
}
first.ok_or_else(|| format!("{what}: no render"))
}
fn check(g: &mut Gpu, doc: &Document, what: &str) {
diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}"));
}
#[test]
@@ -673,25 +700,7 @@ fn effect_cases() -> Vec<(&'static str, Vec<Effect>)> {
/// GPU vs CPU over the whole document: Err with the worst pixel if over the tolerance.
fn fx_diff(g: &mut Gpu, doc: &Document, what: &str) -> Result<photocraft_gpu::Stats, String> {
let cpu = photocraft_compose::flatten(doc);
let (out, stats) = photocraft_gpu::render_to_vec_stats(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).map_err(|e| format!("{what}: {e}"))?;
let mut worst = (0.0f32, 0usize);
for (i, (c, o)) in cpu.px.iter().zip(&out).enumerate() {
let pc = [c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3]];
let po = [o[0] * o[3], o[1] * o[3], o[2] * o[3], o[3]];
for k in 0..4 {
let d = (pc[k] - po[k]).abs();
if d.is_nan() || d > worst.0 {
worst = (if d.is_nan() { 9.0 } else { d }, i);
}
}
}
let w = doc.size.width as usize;
let (x, y) = (worst.1 % w, worst.1 / w);
if worst.0 > TOL {
return Err(format!("{what}: max diff {:.2}/255 at ({x},{y}): cpu {:?} gpu {:?}", worst.0 * 255.0, cpu.px[worst.1], out[worst.1]));
}
Ok(stats)
diff_rect(g, doc, doc.bounds(), what)
}
fn fx_check(g: &mut Gpu, doc: &Document, what: &str) -> photocraft_gpu::Stats {
@@ -927,8 +936,13 @@ fn as_text(src: Layer) -> Layer {
l
}
/// Held by tests that change the process-wide text gamma, and by tests with type layers that
/// run long enough to see such a change.
static TEXT_GAMMA: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[test]
fn type_layers_blend_with_text_gamma() {
let _gamma = TEXT_GAMMA.lock().unwrap_or_else(|e| e.into_inner());
let Some(mut g) = gpu() else { return };
for mode in [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Color] {
let mut d = base_doc(64, 48);
@@ -1168,3 +1182,118 @@ fn unbuildable_pipelines_are_an_error_not_a_panic() {
assert!(Compositor::try_new_with_format(&device, f).is_ok());
}
}
// ---- documents larger than the texture limit ------------------------------------------------
/// A document several pages wide under [`PAGED_LIMIT`]: pixel layers crossing page borders (one
/// masked, one off-canvas), a big effect layer whose region exceeds the limit (maps built per
/// page cell), a type layer with a shadow, an adjustment, a clipped group and a gradient fill.
fn big_doc() -> Document {
let (w, h) = (1100, 900);
let mut d = fx_doc(w, h, SampleType::U8);
// Right over the background: adjustment results round to 8 bits, which would turn sub-LSB
// float differences of blends beneath into whole steps.
let mut adj = Layer::new("invert", LayerContent::Adjustment(Adjustment::Invert));
adj.opacity = 0.6;
adj.mask = Some(mask(Rect::new(240, 0, 800, 520), 83, 0.0));
d.layers.push(adj);
let mut top = noise_layer("top", PixelFormat::RGBA8, Rect::new(-30, 200, 700, 820), 81, 0.0);
top.blend = BlendMode::Multiply;
top.mask = Some(mask(Rect::new(100, 240, 600, 700), 82, 1.0));
d.layers.push(top);
let stack = effect_cases().into_iter().find(|(n, _)| *n == "full stack").unwrap().1;
let mut big = blob("big", d.pixel_format(), 520.0, 450.0, 330.0, [0.9, 0.4, 0.2]);
big.effects.items = stack;
big.effects.items.push(Effect::OuterGlow(glow(FxPaint::Color(Color::rgb(0.2, 1.0, 0.6)), GlowTechnique::Softer, 40.0, 0.2, GlowSource::Edge)));
d.layers.push(big);
let mut text = as_text(blob("type", d.pixel_format(), 900.0, 150.0, 90.0, [0.1, 0.2, 0.9]));
text.effects.items = vec![Effect::DropShadow(shadow(BlendMode::Multiply, 0.8, 135.0, 12.0, 20.0, 0.0))];
d.layers.push(text);
let a = noise_layer("ga", PixelFormat::RGBA8, Rect::new(200, 500, 1000, 880), 84, 0.6);
let mut c = noise_layer("gc", PixelFormat::RGBA8, Rect::new(0, 600, 1100, 700), 85, 0.0);
c.clipped = true;
c.blend = BlendMode::Screen;
let mut grp = Layer::group("g", vec![a, c]);
grp.opacity = 0.9;
d.layers.push(grp);
let stops = vec![(0.0, Color::rgb(1.0, 0.0, 0.0)), (0.6, Color::rgb(0.0, 1.0, 0.2)), (1.0, Color::rgb(0.1, 0.1, 0.9))];
let mut grad = Layer::new("grad", LayerContent::Fill(Fill::Gradient { stops, angle: 30.0, scale: 0.8, style: GradientStyle::Radial, reverse: false }));
grad.opacity = 0.3;
grad.blend = BlendMode::Overlay;
d.layers.push(grad);
d
}
#[test]
fn documents_larger_than_the_texture_limit() {
let _gamma = TEXT_GAMMA.lock().unwrap_or_else(|e| e.into_inner());
let Some(mut g) = gpu() else { return };
let mut d = big_doc();
assert!(g.paged.supports(&d).is_ok());
// Every pass sees page borders, and effect maps and blurs crossing them.
check(&mut g, &d, "big document");
let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds()).unwrap().1;
assert!(s.cells >= 20 && s.chunks == s.cells, "{s:?}");
// A viewport off the page grid covers only its cells.
let view = Rect::new(300, 330, 790, 610);
diff_rect(&mut g, &d, view, "viewport").unwrap_or_else(|e| panic!("{e}"));
let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, view).unwrap().1;
assert_eq!(s.cells, 6, "{s:?}");
// A dab across a page corner on the effect layer, and an edit elsewhere.
d.layers[3].surface_mut().unwrap().fill_rect(Rect::new(500, 490, 530, 530), &[0.1, 0.1, 0.9, 1.0]);
d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(250, 250, 270, 270), &[0.0, 0.0, 0.0, 0.0]);
check(&mut g, &d, "after dabs");
let s = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds()).unwrap().1;
assert_eq!((s.tiles_uploaded, s.fx_shapes), (0, 0), "nothing changed since the last render: {s:?}");
}
#[test]
fn pages_are_evicted_under_the_budget() {
let _gamma = TEXT_GAMMA.lock().unwrap_or_else(|e| e.into_inner());
let Some(mut g) = gpu() else { return };
let mut d = big_doc();
check(&mut g, &d, "warm");
let all = g.paged.resident_bytes();
// A budget of one page: everything but the cell being drawn is evicted as the render goes.
let page = u64::from(g.paged.page_size()).pow(2) * 4;
g.paged.set_resident_budget(page);
for round in 0..3 {
let cpu = photocraft_compose::flatten(&d);
let (out, s) = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, &d, d.bounds()).unwrap();
let worst = worst_diff(&cpu.px, &out);
assert!(worst.0 <= TOL, "round {round}: max diff {:.2}/255 at {}", worst.0 * 255.0, worst.1);
assert!(s.evicted > 0, "round {round}: {s:?}");
assert!(g.paged.resident_bytes() < all / 4, "{} of {all}", g.paged.resident_bytes());
// Evicted pages come back with the edits made meanwhile.
d.layers[2].surface_mut().unwrap().fill_rect(Rect::new(10 + round * 300, 300, 60 + round * 300, 340), &[0.9, 0.9, 0.1, 1.0]);
d.layers[3].surface_mut().unwrap().fill_rect(Rect::new(200 + round * 200, 420, 240 + round * 200, 470), &[0.0, 0.0, 0.0, 0.0]);
}
check(&mut g, &d, "after eviction");
}
#[test]
fn the_focused_view_stays_resident_after_a_full_refresh() {
let _gamma = TEXT_GAMMA.lock().unwrap_or_else(|e| e.into_inner());
let Some(g) = gpu() else { return };
let d = big_doc();
let mut comp = Compositor::try_new_with_format(&g.device, wgpu::TextureFormat::Rgba32Float).unwrap();
comp.set_texture_limit(PAGED_LIMIT);
let view = Rect::new(520, 300, 760, 500);
photocraft_gpu::render_to_vec(&mut comp, &g.device, &g.queue, &d, view).unwrap();
// A budget holding just the view's pages: a full refresh evicts as it goes, and draws the
// view's cells last, so the next edit in the view uploads nothing.
// The working set of a region is what rendering it makes resident.
assert_eq!(comp.working_set(&d, view), comp.resident_bytes());
assert!(comp.working_set(&d, d.bounds()) > 4 * comp.resident_bytes());
comp.set_resident_budget(comp.resident_bytes());
assert!(comp.fits_budget(&d, view) && !comp.fits_budget(&d, d.bounds()));
comp.set_focus(Some(view));
for _ in 0..2 {
let s = photocraft_gpu::render_to_vec_stats(&mut comp, &g.device, &g.queue, &d, d.bounds()).unwrap().1;
assert!(s.evicted > 0, "{s:?}");
let (out, s) = photocraft_gpu::render_to_vec_stats(&mut comp, &g.device, &g.queue, &d, view).unwrap();
assert_eq!(s.tiles_uploaded, 0, "{s:?}");
let cpu = photocraft_compose::render(&d, view);
assert!(worst_diff(&cpu.px, &out).0 <= TOL);
}
}
+9
View File
@@ -123,6 +123,14 @@ impl History {
self.undo.iter().chain(self.redo.iter()).map(|s| tile_bytes(&s.doc, &mut seen)).sum()
}
/// Pixel bytes of `current` plus the tiles only history holds (what [`History::trim`]
/// bounds by [`History::max_bytes`]).
pub fn pixel_bytes(&self, current: &Document) -> usize {
let mut seen = HashSet::new();
let own = tile_bytes(current, &mut seen);
self.undo.iter().chain(self.redo.iter()).fold(own, |n, s| n.saturating_add(tile_bytes(&s.doc, &mut seen)))
}
/// Keep pixel memory within [`History::max_bytes`]: the current document's tiles plus the
/// tiles only history holds (newest states first). The oldest undo states that don't fit are
/// dropped; the most recent one is always kept so the last step can be undone. Returns how
@@ -262,6 +270,7 @@ mod tests {
assert_eq!(h.trim(&cur), 3);
assert_eq!(h.past_len(), 3);
assert_eq!(h.unique_bytes(&cur), 3 * tile);
assert_eq!(h.pixel_bytes(&cur), 4 * tile, "the current tile plus history's");
assert_eq!(h.entries()[0], "paint 2");
// A budget smaller than one state still keeps the last step undoable.
h.max_bytes = 1;
+254
View File
@@ -0,0 +1,254 @@
//! Huge-document benchmark (issue #49): canvas refreshes of a 20000×20000 (or `--size`) 8-bit
//! RGB document with eleven layers (full-canvas pixel layers, soft blobs, an adjustment, type
//! layers with effects, a full-width band whose effect region is wider than the GPU texture
//! limit, a group with a clipped layer), on a device created the way the app creates it.
//!
//! One operation per run, so the process's peak memory is that operation's (plus building the
//! document):
//!
//! ```sh
//! cargo build --release -p photocraft-ui-egui --example huge_doc_bench
//! for op in full view; do
//! /usr/bin/time -l target/release/examples/huge_doc_bench --size 20000x20000 --op $op 2>&1 | grep -E 'ms|MB|maximum resident|peak memory'
//! done
//! # The CPU fallback, for comparison:
//! PHOTOCRAFT_CPU_COMPOSE=1 /usr/bin/time -l target/release/examples/huge_doc_bench --op full
//! ```
//!
//! `full`: the first refresh (every page uploaded, every effect map built) and three repeats.
//! `view`: refreshes of a 2560×1440 viewport (zoomed in) at three places, after the first
//! refresh, then the same after a brush dab in each.
use std::time::Instant;
use eframe::egui_wgpu::RenderState;
use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
use photocraft_doc::{Adjustment, Document, Effect, FxCommon, FxPaint, Layer, LayerContent, Shadow, StrokeFx, StrokePosition, TextLayer};
use photocraft_geom::{Rect, Size};
use photocraft_ui_egui::gpu_canvas::GpuCanvas;
use rayon::prelude::*;
fn arg(args: &[String], name: &str) -> Option<String> {
args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned())
}
fn ms(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1000.0
}
/// A layer over `r` whose RGBA8 pixels are `f(x, y)`, written in parallel-generated bands.
fn layer_from(name: &str, r: Rect, f: impl Fn(i32, i32) -> [u8; 4] + Sync) -> Layer {
let mut l = Layer::raster(name, PixelFormat::RGBA8);
let s = l.surface_mut().expect("raster");
let mut y = r.y0;
while y < r.y1 {
let band = Rect::new(r.x0, y, r.x1, (y + 256).min(r.y1));
let w = band.width() as usize;
let mut bytes = vec![0u8; w * band.height() as usize * 4];
bytes.par_chunks_mut(w * 4).enumerate().for_each(|(row, px)| {
for (i, p) in px.as_chunks_mut::<4>().0.iter_mut().enumerate() {
p.copy_from_slice(&f(band.x0 + i as i32, band.y0 + row as i32));
}
});
s.write_interleaved(band, &bytes);
y = band.y1;
}
l
}
fn hash(x: i32, y: i32) -> u8 {
((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) as u32 % 251) as u8
}
/// A soft-edged disc of colour `c` centred in `r`.
fn blob(name: &str, r: Rect, c: [u8; 3]) -> Layer {
let (cx, cy, rad) = ((r.x0 + r.x1) as f32 / 2.0, (r.y0 + r.y1) as f32 / 2.0, r.width().min(r.height()) as f32 / 2.0 - 8.0);
layer_from(name, r, |x, y| {
let d = ((x as f32 + 0.5 - cx).powi(2) + (y as f32 + 0.5 - cy).powi(2)).sqrt();
let a = ((rad - d) / 6.0).clamp(0.0, 1.0);
[c[0], c[1].wrapping_add(hash(x, y) / 16), c[2], (a * 255.0) as u8]
})
}
/// A type layer: rows of glyph-like blocks rasterised into its cache.
fn text(name: &str, r: Rect) -> Layer {
let glyphs = layer_from(name, r, |x, y| {
let (gx, gy) = ((x - r.x0) % 90, (y - r.y0) % 160);
let on = gx < 70 && gy < 120 && !(gx > 20 && gx < 50 && gy > 30 && gy < 90);
[20, 30, 200, if on { 255 } else { 0 }]
});
let mut l = Layer::new(name, LayerContent::Text(TextLayer { cache: glyphs.surface().cloned(), ..Default::default() }));
l.effects.items = vec![
Effect::DropShadow(Shadow {
common: FxCommon::new(BlendMode::Multiply, 0.75),
color: Color::rgb(0.0, 0.0, 0.0),
angle: 120.0,
use_global_light: false,
distance: 12.0,
spread: 0.0,
size: 16.0,
contour: photocraft_doc::Contour::Linear,
anti_alias: false,
noise: 0.0,
knocks_out: true,
}),
Effect::Stroke(StrokeFx {
common: FxCommon::new(BlendMode::Normal, 1.0),
size: 4.0,
position: StrokePosition::Outside,
paint: FxPaint::Color(Color::rgb(1.0, 1.0, 1.0)),
}),
];
l
}
fn build(w: u32, h: u32) -> Document {
let (wi, hi) = (w as i32, h as i32);
let mut d = Document::new("huge", Size::new(w, h), ColorMode::Rgb, SampleType::U8);
d.layers.push(layer_from("background", Rect::new(0, 0, wi, hi), |x, y| {
let (fx, fy) = (x as f32 / wi as f32, y as f32 / hi as f32);
let n = hash(x, y) / 8;
[(80.0 + 120.0 * fx) as u8 + n, (60.0 + 140.0 * fy) as u8 + n, (150.0 - 60.0 * fx * fy) as u8 + n, 255]
}));
let mut over = layer_from("texture", Rect::new(0, 0, wi * 3 / 5, hi), |x, y| [200, 180u8.wrapping_add(hash(x, y) / 4), 120, 90 + hash(y, x) / 2]);
over.blend = BlendMode::Multiply;
over.opacity = 0.7;
d.layers.push(over);
let mut adj = Layer::new("exposure", LayerContent::Adjustment(Adjustment::Exposure { exposure: 0.3, offset: 0.0, gamma: 1.05 }));
adj.opacity = 0.8;
d.layers.push(adj);
for (i, (x, y)) in [(0.15, 0.2), (0.55, 0.35), (0.3, 0.7)].into_iter().enumerate() {
let (x, y) = ((wi as f32 * x) as i32, (hi as f32 * y) as i32);
let mut b = blob(&format!("blob {i}"), Rect::new(x, y, x + wi / 6, y + wi / 6), [220, 60 + 60 * i as u8, 40]);
b.blend = if i == 1 { BlendMode::Screen } else { BlendMode::Normal };
d.layers.push(b);
}
// A full-width band with effects: its effect region is wider than a 16384 px texture.
let mut band = layer_from("band", Rect::new(40, hi / 2, wi - 40, hi / 2 + 1200), |x, y| [240, 240, 230, if (x / 64 + y / 64) % 5 == 0 { 0 } else { 230 }]);
band.effects.items = vec![
Effect::DropShadow(Shadow {
common: FxCommon::new(BlendMode::Multiply, 0.6),
color: Color::rgb(0.0, 0.0, 0.1),
angle: 90.0,
use_global_light: false,
distance: 20.0,
spread: 0.0,
size: 24.0,
contour: photocraft_doc::Contour::Linear,
anti_alias: false,
noise: 0.0,
knocks_out: true,
}),
Effect::Stroke(StrokeFx {
common: FxCommon::new(BlendMode::Normal, 1.0),
size: 3.0,
position: StrokePosition::Outside,
paint: FxPaint::Color(Color::rgb(0.1, 0.1, 0.1)),
}),
];
d.layers.push(band);
d.layers.push(text("title", Rect::new(wi / 10, hi / 12, wi / 10 + 6000, hi / 12 + 900)));
d.layers.push(text("caption", Rect::new(wi / 2, hi * 5 / 6, wi / 2 + 4000, hi * 5 / 6 + 500)));
let a = blob("group base", Rect::new(wi * 2 / 3, hi / 10, wi * 2 / 3 + wi / 4, hi / 10 + wi / 4), [40, 160, 90]);
let mut c = layer_from("clipped", Rect::new(wi * 2 / 3, hi / 10, wi, hi / 10 + wi / 8), |x, y| [250, 230, 40, 120 + hash(x, y) / 3]);
c.clipped = true;
c.blend = BlendMode::Overlay;
let mut g = Layer::group("group", vec![a, c]);
g.opacity = 0.9;
d.layers.push(g);
d
}
/// A headless GPU canvas on a device created like the app's.
fn canvas() -> Option<(GpuCanvas, RenderState)> {
let setup = photocraft_ui_egui::gpu_canvas::wgpu_setup();
let rs = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| egui_kittest::wgpu::create_render_state(setup, Default::default()))).ok()?;
let l = rs.device.limits();
eprintln!("adapter: {} (max texture {})", rs.adapter.get_info().name, l.max_texture_dimension_2d);
Some((GpuCanvas::new(&rs), rs))
}
/// One canvas refresh (everything, or `damage`), waiting for the GPU. Returns the path taken.
fn refresh(g: &GpuCanvas, rs: &RenderState, doc: &Document, damage: Option<Rect>) -> (String, Option<String>) {
let r = g.refresh(doc.id.0, doc, damage, None);
let _ = rs.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: None });
let kind = if r.kind.starts_with("gpu") { format!("{}, {} tiles up", r.kind, r.uploads) } else { r.kind.to_string() };
(kind, r.fallback)
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let (w, h) =
arg(&args, "--size").and_then(|s| s.split_once('x').map(|(a, b)| (a.parse().unwrap_or(20000), b.parse().unwrap_or(20000)))).unwrap_or((20000, 20000));
let op = arg(&args, "--op").unwrap_or_else(|| "full".into());
let Some((g, rs)) = canvas() else {
eprintln!("no GPU adapter");
return;
};
let t = Instant::now();
let mut doc = build(w, h);
println!("document {w}×{h} ({:.0} MP), {} layers, built in {:.0} ms", (w as f64 * h as f64) / 1e6, doc.walk().len(), ms(t));
// The compositor budget the app would use: Memory Usage (default 8 GB, `--memory-mb`) less
// the document's pixels, within a quarter of RAM (`PHOTOCRAFT_RAM_MB` simulates a smaller
// machine). The view is the first viewport (`view`) or the whole document (`full`).
let allowance = arg(&args, "--memory-mb").and_then(|v| v.parse::<u64>().ok()).unwrap_or(8192) << 20;
let pixels: u64 = doc
.walk()
.iter()
.flat_map(|(_, _, l)| l.surface().into_iter().chain(l.mask.as_ref().map(|m| &m.surface)))
.map(|s| s.tiles().map(|(_, t)| t.bytes().len() as u64).sum::<u64>())
.sum();
let ram = photocraft_ui_egui::gpu_canvas::physical_memory();
let budget = photocraft_ui_egui::gpu_canvas::memory_budget(allowance, pixels, ram);
g.set_memory_budget(budget);
println!("RAM {} MB, document pixels {} MB, Memory Usage {} MB -> GPU budget {} MB", ram.unwrap_or(0) >> 20, pixels >> 20, allowance >> 20, budget >> 20);
let first_view = Rect::from_xywh((w as f32 * 0.1) as i32, (h as f32 * 0.1) as i32, 2560, 1440);
g.set_focus(Some(if op == "view" { first_view } else { doc.bounds() }));
let t = Instant::now();
let (kind, fallback) = refresh(&g, &rs, &doc, None);
println!("first refresh ({kind:<8}) {:>9.0} ms{}", ms(t), fallback.map_or(String::new(), |f| format!(" [fallback: {f}]")));
let report = |g: &GpuCanvas| {
if let Some((format, bytes)) = g.texture_info(doc.id.0) {
println!("canvas texture {format:?}: {} MB with mips", bytes >> 20);
}
if let Some((pages, fx)) = g.compositor_bytes() {
println!("compositor: {} MB resident pages, {} MB effect maps", pages >> 20, fx >> 20);
}
};
report(&g);
match op.as_str() {
"full" => {
for _ in 0..3 {
let t = Instant::now();
let (kind, _) = refresh(&g, &rs, &doc, None);
println!("full refresh ({kind:<8}) {:>9.0} ms", ms(t));
}
}
"view" => {
let views: Vec<Rect> = [(0.1, 0.1), (0.45, 0.48), (0.7, 0.8)]
.into_iter()
.map(|(x, y)| Rect::from_xywh((w as f32 * x) as i32, (h as f32 * y) as i32, 2560, 1440).intersect(&doc.bounds()))
.collect();
for v in &views {
let t = Instant::now();
let (kind, _) = refresh(&g, &rs, &doc, Some(*v));
println!("viewport refresh ({kind:<8}) {:>9.0} ms at {v:?}", ms(t));
}
// A dab on the band (an effect layer) inside each viewport, then its refresh.
let band = doc.layers.iter().position(|l| l.name == "band").unwrap_or(0);
for v in &views {
let c = Rect::from_xywh(v.x0 + 600, h as i32 / 2 + 300, 120, 120);
if let Some(s) = doc.layers.get_mut(band).and_then(Layer::surface_mut) {
s.fill_rect(c, &[0.1, 0.3, 0.9, 1.0]);
}
let t = Instant::now();
let (kind, _) = refresh(&g, &rs, &doc, Some(*v));
println!("dab + viewport refresh ({kind:<8}) {:>6.0} ms", ms(t));
}
}
other => eprintln!("unknown --op {other}"),
}
report(&g);
}
+18
View File
@@ -460,6 +460,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize, visible: DRect) -> bool {
return true;
}
let partial = present && damage.is_some();
gpu_budget(app, &gpu, idx, partial, visible);
let r = gpu.refresh(id.0, &doc, if partial { damage } else { None }, display.as_deref());
if let Some(e) = &r.fallback
&& app.perf.gpu_fallback.as_deref() != Some(e.as_str())
@@ -480,6 +481,23 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize, visible: DRect) -> bool {
true
}
/// Point the wgpu compositor at what the view shows, and size its memory budget from Memory
/// Usage, the document's pixels and History, and physical memory: on full refreshes (pixels
/// counted once per structural change, not per brush dab) and whenever the preference changes.
fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx: usize, partial: bool, visible: DRect) {
gpu.set_focus(Some(visible));
let allowance = u64::from(app.session.prefs().performance.memory_usage_mb).saturating_mul(1 << 20);
if partial && app.perf.gpu_budget_allowance == allowance && gpu.memory_budget().is_some() {
return;
}
let Some(st) = app.session.documents().get(idx) else { return };
let pixels = st.history.pixel_bytes(&st.doc) as u64;
let budget = crate::gpu_canvas::memory_budget(allowance, pixels, crate::gpu_canvas::physical_memory());
gpu.set_memory_budget(budget);
app.perf.gpu_budget_mb = budget >> 20;
app.perf.gpu_budget_allowance = allowance;
}
/// Live preview for an open filter dialog: run the filter on the proxy and upload it.
fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize) -> Option<(u32, u64)> {
if crate::adjust_preview::on_layer(app, idx) {
+113 -4
View File
@@ -152,6 +152,37 @@ impl GpuCanvas {
Some((d.format, bytes))
}
/// Set the GPU memory the wgpu compositor may hold for layer pages and effect maps (see
/// [`memory_budget`]); pages beyond it are evicted least recently used first.
pub fn set_memory_budget(&self, bytes: u64) {
let mut r = self.rs.renderer.write();
if let Some(res) = r.callback_resources.get_mut::<Resources>() {
res.compositor_budget = Some(bytes);
}
}
/// The compositor's memory budget (`None` until [`GpuCanvas::set_memory_budget`]).
pub fn memory_budget(&self) -> Option<u64> {
let r = self.rs.renderer.read();
r.callback_resources.get::<Resources>()?.compositor_budget
}
/// The document area the view shows: full refreshes composite it last, so its layer pages
/// are the ones still resident for the edits that follow.
pub fn set_focus(&self, focus: Option<photocraft_geom::Rect>) {
let mut r = self.rs.renderer.write();
if let Some(res) = r.callback_resources.get_mut::<Resources>() {
res.compositor_focus = focus;
}
}
/// GPU bytes the wgpu compositor holds: resident layer pages and cached effect maps.
pub fn compositor_bytes(&self) -> Option<(u64, usize)> {
let r = self.rs.renderer.read();
let c = r.callback_resources.get::<Resources>()?.compositor.as_ref()?;
Some((c.resident_bytes(), c.fx_cache_bytes()))
}
/// Set the checkerboard and gamut warning colours.
pub fn set_style(&self, style: CanvasStyle) {
let mut r = self.rs.renderer.write();
@@ -179,10 +210,8 @@ impl GpuCanvas {
}
match &res.compositor {
Some(c) => c.supports(doc).is_ok(),
None => {
let max = self.rs.device.limits().max_texture_dimension_2d;
doc.size.width <= max && doc.size.height <= max && photocraft_gpu::plan(doc).is_ok()
}
// Layers larger than the texture limit are stored in pages, so any size qualifies.
None => photocraft_gpu::plan(doc).is_ok(),
}
}
@@ -291,6 +320,10 @@ impl GpuCanvas {
}
},
};
if let Some(b) = res.compositor_budget {
comp.set_memory_budget(b);
}
comp.set_focus(res.compositor_focus);
let key = doc.id.0;
let format = self.format_for(doc.depth, size);
let fresh = res.docs.get(&key).is_none_or(|d| d.size != size || d.format != format);
@@ -299,6 +332,13 @@ impl GpuCanvas {
res.compositor = Some(comp);
return Err(e);
}
// A full refresh whose layer pages don't fit the memory budget would re-upload the
// evicted ones every time (no faster than the CPU, and more memory): the banded CPU
// compositor does it, and edits in the view (damage rects) stay on the GPU.
if region == doc.bounds() && !comp.fits_budget(doc, region) {
res.compositor = Some(comp);
return Err(photocraft_gpu::Unsupported("layers exceed the GPU memory budget; full refresh on the CPU".into()));
}
if fresh {
let tex = DocTextures::new(device, res, size, self.tile, format);
res.docs.insert(key, tex);
@@ -647,6 +687,12 @@ pub struct Perf {
pub gpu_uploads: u64,
/// Why the last refresh fell back to the CPU compositor (None = GPU composited).
pub gpu_fallback: Option<String>,
/// GPU memory the compositor may hold for layer pages and effect maps (MB; see
/// [`memory_budget`]).
pub gpu_budget_mb: u64,
/// The Memory Usage allowance (bytes) `gpu_budget_mb` was computed from.
#[serde(skip)]
pub gpu_budget_allowance: u64,
/// Last command run through the app and its duration (ms).
pub last_command: String,
pub command_ms: f64,
@@ -809,6 +855,50 @@ fn texel_to_f32(format: wgpu::TextureFormat, b: &[u8]) -> [f32; 4] {
// ---------------------------------------------------------------------------------------------
// GPU resources
/// Floor of the compositor's memory budget: enough for a viewport's pages of a dozen layers.
pub const MIN_GPU_BUDGET: u64 = 512 << 20;
/// GPU memory the wgpu compositor may hold for layer pages and effect maps: what Memory Usage
/// (`allowance`, Preferences › Performance) leaves after the document's pixels and History
/// (`pixels`), at most a quarter of physical memory (`ram`; 16 GB assumed when unknown), and at
/// least [`MIN_GPU_BUDGET`]. On unified-memory machines these textures share RAM with the
/// document, so a huge document keeps its layers on the GPU only as far as memory allows; the
/// rest is uploaded per refresh as the view needs it.
pub fn memory_budget(allowance: u64, pixels: u64, ram: Option<u64>) -> u64 {
let ram = ram.unwrap_or(16 << 30);
allowance.saturating_sub(pixels).min(ram / 4).max(MIN_GPU_BUDGET)
}
/// Physical memory of this machine in bytes, if known. `PHOTOCRAFT_RAM_MB` overrides it (to
/// simulate a smaller machine).
pub fn physical_memory() -> Option<u64> {
static RAM: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
*RAM.get_or_init(|| {
if let Some(mb) = std::env::var("PHOTOCRAFT_RAM_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()) {
return mb.checked_mul(1 << 20);
}
detect_physical_memory()
})
}
#[cfg(target_os = "macos")]
fn detect_physical_memory() -> Option<u64> {
let out = std::process::Command::new("/usr/sbin/sysctl").args(["-n", "hw.memsize"]).output().ok()?;
String::from_utf8(out.stdout).ok()?.trim().parse().ok()
}
#[cfg(target_os = "linux")]
fn detect_physical_memory() -> Option<u64> {
let info = std::fs::read_to_string("/proc/meminfo").ok()?;
let kb: u64 = info.lines().find_map(|l| l.strip_prefix("MemTotal:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
kb.checked_mul(1024)
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn detect_physical_memory() -> Option<u64> {
None
}
struct Resources {
view_bgl: wgpu::BindGroupLayout,
tile_bgl: wgpu::BindGroupLayout,
@@ -828,6 +918,10 @@ struct Resources {
compositor: Option<photocraft_gpu::Compositor>,
/// Why the wgpu compositor couldn't be created (then the CPU compositor is used).
compositor_failed: Option<photocraft_gpu::Unsupported>,
/// GPU memory the compositor may hold (`None`: its default), and the document area the
/// view shows; applied before every composite.
compositor_budget: Option<u64>,
compositor_focus: Option<photocraft_geom::Rect>,
encode_bgl: wgpu::BindGroupLayout,
encode_pipeline: wgpu::RenderPipeline,
lut_bgl: wgpu::BindGroupLayout,
@@ -1087,6 +1181,8 @@ impl Resources {
out_linear: target.is_srgb(),
compositor: None,
compositor_failed: None,
compositor_budget: None,
compositor_focus: None,
encode_bgl,
encode_pipeline,
}
@@ -1579,6 +1675,19 @@ fn fs(in: V) -> @location(0) vec4<f32> {
mod tests {
use super::*;
#[test]
fn gpu_budget_follows_memory_usage_and_ram() {
const G: u64 = 1 << 30;
// What Memory Usage leaves after the document, within a quarter of RAM.
assert_eq!(memory_budget(8 * G, 3 * G, Some(48 * G)), 5 * G);
assert_eq!(memory_budget(8 * G, 3 * G, Some(16 * G)), 4 * G);
assert_eq!(memory_budget(64 * G, 3 * G, Some(16 * G)), 4 * G);
// Never below the floor, even with nothing left; 16 GB assumed when RAM is unknown.
assert_eq!(memory_budget(8 * G, 10 * G, Some(48 * G)), MIN_GPU_BUDGET);
assert_eq!(memory_budget(64 * G, 0, None), 4 * G);
assert!(physical_memory().is_none_or(|b| b >= 256 << 20));
}
#[test]
fn filter_modes() {
assert_eq!(filter_mode(0.25), (0.0, 2.0));