Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Filter Gallery: preview at the scale OK applies (#2502) (#2524)

David Mann6f5e16a0c482
diff --git a/crates/ui-egui/src/gallery_ui.rs b/crates/ui-egui/src/gallery_ui.rs
index 642957b89..80afe652c 100644
--- a/crates/ui-egui/src/gallery_ui.rs
+++ b/crates/ui-egui/src/gallery_ui.rs
@@ -3,10 +3,13 @@
//! selected effect's filter and settings, and the effect-layer stack (new, delete, reorder,
//! show/hide). The stack is applied bottom to top.
//!
-//! The preview runs the same algorithm as the command on the visible part of the layer
-//! (downsampled when zoomed out). OK runs `filter.filterGallery {effects:[...]}`, one history
-//! step (a smart filter on smart objects). Everything is drivable over the control channel with
-//! `filter.filterGallery {"ui": {...}}` while the dialog is open.
+//! The preview shows what OK applies at the preview's zoom, like Photoshop's: the stack runs at
+//! full resolution on the visible part of the layer (plus the filters' reach), and is then
+//! averaged down to the zoom (#2502). On the desktop it renders off the UI thread with a progress
+//! bar, so a 24 MP layer at Fit in View never freezes the window. OK runs
+//! `filter.filterGallery {effects:[...]}`, one history step (a smart filter on smart objects).
+//! Everything is drivable over the control channel with `filter.filterGallery {"ui": {...}}`
+//! while the dialog is open.
use std::hash::{Hash, Hasher};
@@ -14,7 +17,7 @@ use egui::{Align2, Color32, FontId, Rect as ERect, Sense, Stroke, TextureHandle,
use photocraft_algo::{FilterParams, GALLERY_CATEGORIES, GalleryFilter};
use photocraft_doc::LayerId;
use photocraft_geom::Rect;
-use photocraft_raster::Surface;
+use photocraft_raster::{Interrupt, Surface};
use serde_json::{Map, Value, json};
use crate::PhotocraftApp;
@@ -73,7 +76,15 @@ pub struct GalleryDialog {
pub zoom: f32,
center: [f32; 2],
tex: Option<TextureHandle>,
- shown: Option<(u64, ERect)>,
+ /// The key of the preview in `tex` and the document rect it covers.
+ shown: Option<(u64, Rect)>,
+ /// The preview rendering off the UI thread (desktop), and the latest wanted key with when it
+ /// was first wanted (ms), to cancel a stale render once the settings settle.
+ #[cfg(not(target_arch = "wasm32"))]
+ job: Option<PreviewJob>,
+ latest: Option<(u64, f64)>,
+ /// A key whose render failed: not retried until the settings or view change.
+ failed: Option<u64>,
thumb_src: Surface,
thumbs: Vec<Option<TextureHandle>>,
pub preview_ms: f64,
@@ -87,6 +98,7 @@ impl GalleryDialog {
"selected": self.selected,
"zoom": if self.zoom > 0.0 { json!(self.zoom) } else { json!("fit") },
"previewMs": self.preview_ms,
+ "rendering": self.rendering().is_some(),
})
}
@@ -95,6 +107,15 @@ impl GalleryDialog {
json!({"effects": self.effects.iter().map(EffectLayer::to_json).collect::<Vec<_>>(), "foreground": self.foreground, "background": self.background})
}
+ /// The progress (`0.0..=1.0`) of a preview still rendering.
+ fn rendering(&self) -> Option<f32> {
+ #[cfg(not(target_arch = "wasm32"))]
+ if let Some(j) = &self.job {
+ return Some(j.ctl.fraction());
+ }
+ None
+ }
+
fn cur(&mut self) -> &mut EffectLayer {
let i = self.selected.min(self.effects.len() - 1);
&mut self.effects[i]
@@ -160,6 +181,74 @@ fn render(src: &Surface, params: &Value) -> Surface {
photocraft_algo::apply_in(src, &FilterParams::FilterGallery { effects }, b, b, None, b)
}
+/// The preview of `vis` at 1/`k` (#2502): the stack runs at full resolution exactly as OK runs it
+/// (same bounds, same canvas-edge handling, textures and noise seeded by document position), so
+/// the pixels equal the same crop of the applied result; then `k`×`k` blocks are averaged.
+/// `None` when cancelled.
+fn preview_pixels(src: &Surface, canvas: Rect, params: &Value, vis: Rect, k: u32, ctl: &Interrupt) -> Option<Surface> {
+ let effects = photocraft_engine::gallery_cmds::effects_from_json(params).unwrap_or_default();
+ let fp = FilterParams::FilterGallery { effects };
+ let content = src.content_bounds();
+ let area = photocraft_algo::output_area(&fp, content, canvas, None).intersect(&vis);
+ let full = if area.is_empty() { src.clone() } else { photocraft_algo::apply_in_with(src, &fp, area, canvas, None, canvas.union(&content), ctl)? };
+ Some(reduce(&full, vis, k))
+}
+
+/// `r` of `surf` scaled down by `k`, each pixel the average of a `k`×`k` block (colour weighted by
+/// alpha), placed at the origin.
+fn reduce(surf: &Surface, r: Rect, k: u32) -> Surface {
+ let k = k.clamp(1, 1 << 16) as usize;
+ let (bw, bh) = (r.width() as usize, r.height() as usize);
+ let (w, h) = (bw.div_ceil(k), bh.div_ceil(k));
+ let mut out = Surface::new(surf.format());
+ if w == 0 || h == 0 {
+ return out;
+ }
+ let n = surf.channels().max(1);
+ let alpha = surf.format().alpha;
+ let colours = if alpha { n - 1 } else { n };
+ // One output row from a band of `k` source rows.
+ let row = |j: usize, out: &mut [f32]| {
+ let y0 = r.y0.saturating_add((j * k) as i32);
+ let band = surf.read_region(Rect::new(r.x0, y0, r.x1, y0.saturating_add(k as i32).min(r.y1)));
+ let mut acc = vec![0.0f64; w * n];
+ let mut count = vec![0u32; w];
+ for (i, px) in band.chunks_exact(n).enumerate() {
+ let x = (i % bw) / k;
+ let (Some(sum), Some(c)) = (acc.get_mut(x * n..x * n + n), count.get_mut(x)) else { continue };
+ let a = if alpha { px[n - 1] as f64 } else { 1.0 };
+ for (s, v) in sum.iter_mut().zip(&px[..colours]) {
+ *s += *v as f64 * a;
+ }
+ if alpha {
+ sum[n - 1] += a;
+ }
+ *c += 1;
+ }
+ for ((sum, c), o) in acc.chunks_exact(n).zip(&count).zip(out.chunks_exact_mut(n)) {
+ let a = if alpha { sum[n - 1] } else { *c as f64 };
+ for (o, v) in o.iter_mut().zip(&sum[..colours]) {
+ *o = if a > 0.0 { (v / a) as f32 } else { 0.0 };
+ }
+ if alpha {
+ o[n - 1] = (a / (*c).max(1) as f64) as f32;
+ }
+ }
+ };
+ let mut data = vec![0.0f32; w * h * n];
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ use rayon::prelude::*;
+ data.par_chunks_mut(w * n).enumerate().for_each(|(j, out)| row(j, out));
+ }
+ #[cfg(target_arch = "wasm32")]
+ for (j, out) in data.chunks_mut(w * n).enumerate() {
+ row(j, out);
+ }
+ out.write_region(Rect::new(0, 0, w as i32, h as i32), &data);
+ out
+}
+
fn image(surf: &Surface, w: usize, h: usize) -> egui::ColorImage {
let mut px = vec![[0u8; 4]; w * h];
for y in 0..h {
@@ -217,6 +306,10 @@ pub fn open(app: &mut PhotocraftApp) -> Result<(), String> {
center: [(canvas.x0 + canvas.x1) as f32 / 2.0, (canvas.y0 + canvas.y1) as f32 / 2.0],
tex: None,
shown: None,
+ #[cfg(not(target_arch = "wasm32"))]
+ job: None,
+ latest: None,
+ failed: None,
thumb_src,
thumbs: vec![None; GalleryFilter::ALL.len()],
preview_ms: 0.0,
@@ -284,9 +377,27 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result<Value, String> {
Ok(d.describe())
}
-/// Recomputes the preview texture when the stack or the view changed.
-fn update_preview(d: &mut GalleryDialog, ctx: &egui::Context, area: ERect) {
- let (cw, ch) = (d.canvas.width() as f32, d.canvas.height() as f32);
+/// A preview rendering on a worker thread: what it shows, its result and its cancellation.
+#[cfg(not(target_arch = "wasm32"))]
+struct PreviewJob {
+ key: u64,
+ vis: Rect,
+ rx: std::sync::mpsc::Receiver<Result<Option<(egui::ColorImage, f64)>, String>>,
+ ctl: photocraft_engine::jobs::JobCtx,
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+impl Drop for PreviewJob {
+ /// A closed dialog or a superseded render stops at its next tile.
+ fn drop(&mut self) {
+ self.ctl.cancel();
+ }
+}
+
+/// The preview's zoom (screen px per document px), the visible document rect and the factor the
+/// texture is reduced by. Fit in View also recentres the view.
+fn view(d: &mut GalleryDialog, area: ERect) -> (f32, Rect, u32) {
+ let (cw, ch) = (d.canvas.width().max(1) as f32, d.canvas.height().max(1) as f32);
let zoom = if d.zoom > 0.0 { d.zoom } else { ((area.width() - 24.0) / cw).min((area.height() - 24.0) / ch).clamp(0.005, 1.0) };
if d.zoom <= 0.0 {
d.center = [d.canvas.x0 as f32 + cw / 2.0, d.canvas.y0 as f32 + ch / 2.0];
@@ -295,34 +406,112 @@ fn update_preview(d: &mut GalleryDialog, ctx: &egui::Context, area: ERect) {
let vis =
Rect::new((d.center[0] - hw).floor() as i32, (d.center[1] - hh).floor() as i32, (d.center[0] + hw).ceil() as i32, (d.center[1] + hh).ceil() as i32)
.intersect(&d.canvas);
- let k = (1.0 / zoom).ceil().max(1.0) as u32;
+ // At least one texture pixel per screen pixel; the GPU's linear filter does the rest.
+ let k = (1.0 / zoom + 1e-3).floor().clamp(1.0, 4096.0) as u32;
+ (zoom, vis, k)
+}
+
+/// Keeps the preview texture current with the stack and the view; returns where it is drawn.
+/// With `background` the render runs off the UI thread and the last preview stays up (moving
+/// with the view) until it is done; otherwise it renders inline (web, tests, inline sessions).
+fn update_preview(d: &mut GalleryDialog, ctx: &egui::Context, area: ERect, background: bool) -> Option<ERect> {
+ let (zoom, vis, k) = view(d, area);
let params = d.params();
let mut h = std::collections::hash_map::DefaultHasher::new();
params.to_string().hash(&mut h);
(vis.x0, vis.y0, vis.x1, vis.y1, k).hash(&mut h);
let key = h.finish();
- let screen = ERect::from_min_max(
- area.center() + vec2((vis.x0 as f32 - d.center[0]) * zoom, (vis.y0 as f32 - d.center[1]) * zoom),
- area.center() + vec2((vis.x1 as f32 - d.center[0]) * zoom, (vis.y1 as f32 - d.center[1]) * zoom),
- );
- if d.shown.is_some_and(|(k0, _)| k0 == key) {
- d.shown = Some((key, screen));
- return;
+ let now = crate::gpu_canvas::now_ms();
+ if d.latest.is_none_or(|(k0, _)| k0 != key) {
+ d.latest = Some((key, now));
}
- if vis.is_empty() {
- return;
+ #[cfg(not(target_arch = "wasm32"))]
+ poll_job(d, ctx);
+ let wanted = d.shown.is_none_or(|(k0, _)| k0 != key) && !vis.is_empty() && d.failed != Some(key);
+ #[cfg(not(target_arch = "wasm32"))]
+ if wanted && background {
+ start_job(d, ctx, key, vis, k, &params, now);
+ } else if d.job.as_ref().is_some_and(|j| j.key != key) {
+ // Back to what is already shown: the render for other settings is no longer needed.
+ d.job = None;
}
- let t0 = crate::gpu_canvas::now_ms();
- let small = sample(&d.src, vis, k);
- let out = render(&small, &params);
- let (w, hgt) = (vis.width().div_ceil(k) as usize, vis.height().div_ceil(k) as usize);
- let img = image(&out, w, hgt);
+ if wanted && !background {
+ let t0 = crate::gpu_canvas::now_ms();
+ if let Some(out) = preview_pixels(&d.src, d.canvas, &params, vis, k, &Interrupt::NONE) {
+ let img = image(&out, reduced(vis.width(), k), reduced(vis.height(), k));
+ show_image(d, ctx, img, key, vis, crate::gpu_canvas::now_ms() - t0);
+ }
+ }
+ let (_, r) = d.shown?;
+ let at = |x: i32, y: i32| area.center() + vec2((x as f32 - d.center[0]) * zoom, (y as f32 - d.center[1]) * zoom);
+ Some(ERect::from_min_max(at(r.x0, r.y0), at(r.x1, r.y1)))
+}
+
+/// A length of `n` document pixels reduced by `k` (partial blocks count).
+fn reduced(n: u32, k: u32) -> usize {
+ (n as usize).div_ceil(k.max(1) as usize)
+}
+
+fn show_image(d: &mut GalleryDialog, ctx: &egui::Context, img: egui::ColorImage, key: u64, vis: Rect, ms: f64) {
match &mut d.tex {
Some(t) => t.set(img, egui::TextureOptions::LINEAR),
None => d.tex = Some(ctx.load_texture("gallery-preview", img, egui::TextureOptions::LINEAR)),
}
- d.preview_ms = crate::gpu_canvas::now_ms() - t0;
- d.shown = Some((key, screen));
+ d.preview_ms = ms;
+ d.shown = Some((key, vis));
+}
+
+/// Takes a finished render: shown when it completed, dropped when cancelled, remembered when it
+/// failed (so a failing stack isn't retried every frame).
+#[cfg(not(target_arch = "wasm32"))]
+fn poll_job(d: &mut GalleryDialog, ctx: &egui::Context) {
+ let Some(job) = &d.job else { return };
+ let result = match job.rx.try_recv() {
+ Ok(r) => r,
+ Err(std::sync::mpsc::TryRecvError::Empty) => return,
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("the Filter Gallery preview stopped".into()),
+ };
+ let Some(job) = d.job.take() else { return };
+ match result {
+ Ok(Some((img, ms))) => show_image(d, ctx, img, job.key, job.vis, ms),
+ Ok(None) => {}
+ Err(_) => d.failed = Some(job.key),
+ }
+}
+
+/// One render at a time: a running render for older settings finishes (so a slider drag keeps
+/// updating) unless the settings have been unchanged for a moment, then it is cancelled.
+#[cfg(not(target_arch = "wasm32"))]
+fn start_job(d: &mut GalleryDialog, ctx: &egui::Context, key: u64, vis: Rect, k: u32, params: &Value, now: f64) {
+ if let Some(job) = &d.job {
+ let settled = d.latest.is_some_and(|(k0, t)| k0 == key && now - t >= crate::filter_preview_worker::SETTLE_MS);
+ if job.key != key && settled {
+ job.ctl.cancel();
+ }
+ ctx.request_repaint_after(std::time::Duration::from_millis(30));
+ return;
+ }
+ let (tx, rx) = std::sync::mpsc::sync_channel(1);
+ let ctl = photocraft_engine::jobs::JobCtx::new();
+ let (work, src, canvas, params, repaint) = (ctl.clone(), d.src.clone(), d.canvas, params.clone(), ctx.clone());
+ let spawned = std::thread::Builder::new().name("gallery-preview".into()).spawn(move || {
+ let run = || {
+ let t0 = crate::gpu_canvas::now_ms();
+ let out = work.stage(0.0, 1.0, "", |ctl| preview_pixels(&src, canvas, &params, vis, k, ctl))?;
+ let img = image(&out, reduced(vis.width(), k), reduced(vis.height(), k));
+ Some((img, crate::gpu_canvas::now_ms() - t0))
+ };
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(run)).map_err(|_| "the Filter Gallery preview failed".to_string());
+ let _ = tx.send(result);
+ repaint.request_repaint();
+ });
+ match spawned {
+ Ok(_) => {
+ d.job = Some(PreviewJob { key, vis, rx, ctl });
+ ctx.request_repaint_after(std::time::Duration::from_millis(30));
+ }
+ Err(_) => d.failed = Some(key),
+ }
}
/// Renders up to `budget` missing thumbnails (spread over frames so opening stays instant).
@@ -350,6 +539,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
let t = Tokens::get(ctx);
let screen = ctx.content_rect();
let mut action: Option<&str> = None;
+ let background = app.background_jobs;
egui::Area::new(egui::Id::new("gallery-dialog")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {
let Some(d) = app.distort.gallery.as_mut() else { return };
let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover());
@@ -369,9 +559,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
// ---- Preview ----
painter.rect_filled(area, 0.0, t.canvas);
- update_preview(d, ctx, area);
+ let shown = update_preview(d, ctx, area, background);
let clip = painter.with_clip_rect(area);
- if let (Some(tex), Some((_, r))) = (&d.tex, d.shown) {
+ if let (Some(tex), Some(r)) = (&d.tex, shown) {
widgets::checker(&clip, r.intersect(area), 8.0);
clip.image(tex.id(), r, ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
clip.rect_stroke(r, 0.0, Stroke::new(1.0, t.separator), egui::StrokeKind::Outside);
@@ -397,7 +587,13 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
if widgets::dropdown(&mut zb, "gallery-zoom", &mut z, &opts, 110.0) {
d.zoom = z;
}
- zb.label(egui::RichText::new(format!("{} {:.0} ms", tl!("Preview"), d.preview_ms)).color(t.text_faint).size(11.0));
+ if let Some(p) = d.rendering() {
+ // Like Photoshop's: a progress bar while the preview renders (the last one stays up).
+ let (br, _) = zb.allocate_exact_size(vec2(90.0, 6.0), Sense::hover());
+ crate::jobs_ui::bar(&zb, br, (p > 0.0).then_some(p), &t);
+ } else {
+ zb.label(egui::RichText::new(format!("{} {:.0} ms", tl!("Preview"), d.preview_ms)).color(t.text_faint).size(11.0));
+ }
// ---- Category folders with thumbnails ----
painter.rect_filled(mid, 0.0, t.dock);
@@ -652,7 +848,7 @@ mod tests {
let mut app = app();
open(&mut app).unwrap();
let d = app.distort.gallery.as_mut().unwrap();
- update_preview(d, &ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)));
+ update_preview(d, &ctx, ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)), false);
assert!(d.tex.is_some() && d.shown.is_some());
d.open = [true; 6];
update_thumbs(d, &ctx, 100);
@@ -669,4 +865,185 @@ mod tests {
let worst = a.read_region(d.canvas).iter().zip(&b).map(|(x, y)| (x - y).abs()).fold(0.0, f32::max);
assert!(worst < 2e-3, "preview differs from the result by {worst}");
}
+
+ /// A 240×160 layer with gradients, edges and fine detail, so every gallery filter has
+ /// something to draw.
+ fn photo_app() -> PhotocraftApp {
+ let (w, h) = (240, 160);
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.session.execute("file.new", json!({"width": w, "height": h, "depth": 16})).unwrap();
+ app.session.execute("layer.new.layer", json!({})).unwrap();
+ app.session
+ .edit("paint", |doc, active| {
+ let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();
+ for y in 0..h {
+ for x in 0..w {
+ let (u, v) = (x as f32 / w as f32, y as f32 / h as f32);
+ let disc = (((x - 150) * (x - 150) + (y - 70) * (y - 70)) < 45 * 45) as i32 as f32;
+ let stripes = ((x + y) / 11 % 2) as f32;
+ s.write_pixel(x, y, &[u * 0.8 + disc * 0.2, 0.25 + 0.5 * stripes * (1.0 - disc), v * (1.0 - disc) + disc * 0.9, 1.0]);
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ app.sync_views();
+ app
+ }
+
+ /// What OK applies: `filter.filterGallery` with the dialog's stack on a copy of the document.
+ fn applied(app: &PhotocraftApp, d: &GalleryDialog) -> Surface {
+ let mut s2 = photocraft_engine::Session::new();
+ s2.add_document(app.session.active().unwrap().doc.as_ref().clone(), None);
+ s2.select_layer(d.layer).unwrap();
+ s2.execute("filter.filterGallery", d.params()).unwrap();
+ s2.active().unwrap().doc.layer(d.layer).unwrap().surface().unwrap().clone()
+ }
+
+ /// Mean of `k`×`k` blocks (opaque layers), written independently of [`reduce`].
+ fn box_mean(surf: &Surface, r: Rect, k: i32) -> Vec<f32> {
+ let mut out = Vec::new();
+ let mut px = [0.0f32; 4];
+ for by in (r.y0..r.y1).step_by(k as usize) {
+ for bx in (r.x0..r.x1).step_by(k as usize) {
+ let mut sum = [0.0f32; 4];
+ let mut n = 0.0;
+ for y in by..(by + k).min(r.y1) {
+ for x in bx..(bx + k).min(r.x1) {
+ surf.read_pixel(x, y, &mut px);
+ sum.iter_mut().zip(px).for_each(|(s, v)| *s += v);
+ n += 1.0;
+ }
+ }
+ out.extend(sum.map(|s| s / n));
+ }
+ }
+ out
+ }
+
+ /// Mean absolute RGB difference.
+ fn mean_diff(a: &[f32], b: &[f32]) -> f32 {
+ assert_eq!(a.len(), b.len());
+ let (sum, n) = a.chunks(4).zip(b.chunks(4)).fold((0.0, 0.0), |(s, n), (p, q)| (s + (0..3).map(|c| (p[c] - q[c]).abs()).sum::<f32>(), n + 3.0));
+ sum / n
+ }
+
+ #[test]
+ fn zoomed_out_preview_matches_the_applied_result_scaled_down() {
+ // #2502: below 100 % the preview filtered every k-th pixel with the same params, so
+ // strokes, grain and textures showed several times too large.
+ let ctx = egui::Context::default();
+ let mut app = photo_app();
+ open(&mut app).unwrap();
+ let area = ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
+ for f in ["graphicPen", "charcoal", "reticulation", "stainedGlass", "spatter", "chalkCharcoal"] {
+ control(&mut app, &json!({"filter": f, "zoom": 0.25})).unwrap();
+ let reference = {
+ let d = app.distort.gallery.as_ref().unwrap();
+ box_mean(&applied(&app, d), d.canvas, 4)
+ };
+ let d = app.distort.gallery.as_mut().unwrap();
+ let (_, vis, k) = view(d, area);
+ assert_eq!((vis, k), (d.canvas, 4), "{f}: at 25 % the whole layer shows, averaged 4×4");
+ assert!(update_preview(d, &ctx, area, false).is_some());
+ let shown = preview_pixels(&d.src, d.canvas, &d.params(), vis, k, &Interrupt::NONE).unwrap();
+ let (w, h) = (reduced(vis.width(), k) as i32, reduced(vis.height(), k) as i32);
+ let diff = mean_diff(&shown.read_region(Rect::new(0, 0, w, h)), &reference);
+ // The old preview (every 4th pixel, filtered at that size) for comparison.
+ let old = mean_diff(&render(&sample(&d.src, vis, k), &d.params()).read_region(Rect::new(0, 0, w, h)), &reference);
+ assert!(diff < 1e-3, "{f}: preview differs from the applied result by {diff}");
+ assert!(old > 20.0 * diff.max(1e-3), "{f}: the old preview differed by only {old}");
+ }
+ }
+
+ #[test]
+ fn a_region_renders_the_same_pixels_as_the_full_result() {
+ // Zoomed in, only the visible part renders: noise, cells and textures are seeded by
+ // document position, and the filters read their reach around the region.
+ let mut app = photo_app();
+ open(&mut app).unwrap();
+ let region = Rect::new(37, 21, 151, 117);
+ for f in GalleryFilter::ALL {
+ control(&mut app, &json!({"filter": f.key()})).unwrap();
+ let d = app.distort.gallery.as_ref().unwrap();
+ let full = applied(&app, d).read_region(region);
+ let part = preview_pixels(&d.src, d.canvas, &d.params(), region, 1, &Interrupt::NONE).unwrap();
+ let part = part.read_region(Rect::new(0, 0, region.width() as i32, region.height() as i32));
+ let worst = full.iter().zip(&part).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max);
+ assert!(worst < 1e-3, "{}: region differs from the full result by {worst}", f.key());
+ }
+ }
+
+ #[test]
+ fn reduce_averages_blocks_weighted_by_alpha() {
+ let mut s = Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::F32, true));
+ s.write_pixel(0, 0, &[1.0, 0.0, 0.0, 1.0]);
+ s.write_pixel(1, 0, &[0.0, 1.0, 0.0, 0.0]); // transparent: its colour doesn't count
+ s.write_pixel(2, 0, &[0.2, 0.4, 0.6, 1.0]); // a partial block at the edge
+ let r = reduce(&s, Rect::new(0, 0, 3, 2), 2).read_region(Rect::new(0, 0, 2, 1));
+ assert_eq!(r, [1.0, 0.0, 0.0, 0.25, 0.2, 0.4, 0.6, 0.5]);
+ assert_eq!(reduce(&s, Rect::EMPTY, 2).content_bounds(), Rect::EMPTY);
+ }
+
+ #[test]
+ fn background_preview_renders_off_the_ui_thread() {
+ let ctx = egui::Context::default();
+ let mut app = photo_app();
+ open(&mut app).unwrap();
+ control(&mut app, &json!({"filter": "graphicPen"})).unwrap();
+ let d = app.distort.gallery.as_mut().unwrap();
+ let area = ERect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
+ assert!(update_preview(d, &ctx, area, true).is_none(), "nothing to show until the first render is done");
+ assert!(d.describe()["rendering"].as_bool().unwrap());
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
+ while d.rendering().is_some() {
+ assert!(std::time::Instant::now() < deadline, "the preview never finished");
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ update_preview(d, &ctx, area, true);
+ }
+ assert!(d.tex.is_some() && update_preview(d, &ctx, area, true).is_some());
+ // A new setting starts a new render; the last preview stays up meanwhile.
+ let before = d.cur().params.get("strokeLength").cloned().unwrap();
+ d.cur().params.insert("strokeLength".into(), json!(5));
+ assert!(update_preview(d, &ctx, area, true).is_some());
+ assert!(d.rendering().is_some());
+ // Back to the settings on screen: that render is dropped (and cancelled).
+ d.cur().params.insert("strokeLength".into(), before);
+ assert!(update_preview(d, &ctx, area, true).is_some());
+ assert!(d.rendering().is_none());
+ d.cur().params.insert("strokeLength".into(), json!(5));
+ update_preview(d, &ctx, area, true);
+ // Closing the dialog cancels it.
+ app.distort.gallery = None;
+ }
+
+ /// Preview cost on 24 MP: `cargo test -p photocraft-ui-egui --lib bench_gallery_preview -- --ignored --nocapture`.
+ #[test]
+ #[ignore]
+ fn bench_gallery_preview() {
+ let (w, h) = (6000, 4000);
+ let canvas = Rect::new(0, 0, w, h);
+ let mut s = Surface::new(photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, true));
+ s.fill_rect(canvas, &[0.5, 0.4, 0.3, 1.0]);
+ for y in (0..h).step_by(9) {
+ s.fill_rect(Rect::new(0, y, w, y + 3), &[0.9, 0.8, 0.2, 1.0]);
+ }
+ let ms = |t: std::time::Instant| t.elapsed().as_secs_f64() * 1000.0;
+ let t = std::time::Instant::now();
+ std::hint::black_box(reduce(&s, canvas, 8));
+ println!("{:>14}: {:>7.0} ms", "reduce 1/8", ms(t));
+ for f in ["graphicPen", "charcoal", "reticulation", "stainedGlass", "spatter", "roughPastels"] {
+ let p = json!({"effects": [{"filter": f}]});
+ let t = std::time::Instant::now();
+ std::hint::black_box(render(&sample(&s, canvas, 8), &p));
+ let old = ms(t);
+ let t = std::time::Instant::now();
+ std::hint::black_box(preview_pixels(&s, canvas, &p, canvas, 8, &Interrupt::NONE));
+ let fit = ms(t);
+ let t = std::time::Instant::now();
+ std::hint::black_box(preview_pixels(&s, canvas, &p, Rect::new(2400, 1600, 3500, 2400), 1, &Interrupt::NONE));
+ let screen = ms(t);
+ println!("{f:>14}: old fit {old:>5.0} ms, new fit {fit:>6.0} ms, new 100 % (1100x800) {screen:>5.0} ms");
+ }
+ }
}