From e2ed5cdcb7e53586fdf5ad9e44abc0dee64cd285 Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Wed, 14 Oct 2026 12:41:22 +0800 Subject: [PATCH 01/34] Limit blend mode hover refresh to the visible canvas --- crates/ui-egui/src/blend_preview.rs | 31 +++- crates/ui-egui/src/canvas.rs | 14 +- .../src/canvas/blend_viewport_tests.rs | 142 ++++++++++++++++++ 3 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 crates/ui-egui/src/canvas/blend_viewport_tests.rs diff --git a/crates/ui-egui/src/blend_preview.rs b/crates/ui-egui/src/blend_preview.rs index e9f010613a..b73ddd553b 100644 --- a/crates/ui-egui/src/blend_preview.rs +++ b/crates/ui-egui/src/blend_preview.rs @@ -29,6 +29,8 @@ pub(crate) struct BlendPreview { area: Option, /// The document shown for `mode`, with its key. shown: Option<(u64, Arc)>, + /// GPU preview key, affected region (including effects), and the area last refreshed. + covered: Option<(u64, Rect, Rect)>, } /// The Layers panel, each frame it draws `layer`'s blend-mode dropdown: the mode under the @@ -47,7 +49,7 @@ pub(crate) fn hover(app: &mut PhotocraftApp, layer: LayerId, mode: Option Rect { + let Some(p) = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision) else { return region }; + if !p.shown.as_ref().is_some_and(|(shown, _)| *shown == key) { + p.covered = None; + return region; + } + let shown = region.intersect(&visible); + p.covered = Some((key, region, shown)); + shown +} + +/// A pan or zoom can expose pixels not yet rendered for the current preview key. +pub(crate) fn uncovered(app: &mut PhotocraftApp, doc: DocId, revision: u64, key: u64, visible: Rect) -> Option { + let p = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision)?; + let (covered_key, region, covered) = p.covered?; + if covered_key != key { + return None; + } + let want = region.intersect(&visible); + if want.is_empty() || covered.contains_rect(&want) { + return None; + } + p.covered = Some((key, region, want)); + Some(want) +} + fn is_preview_key(key: u64) -> bool { (BASE..BASE << 1).contains(&key) } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 676d068070..f2cc88f074 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1545,6 +1545,9 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: let display_key = texture_key(display.as_deref()); let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key)); let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage)); + if let Some(region) = damage { + damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, visible)); + } // To an adjustment dialog's preview: only what the view shows now (the rest as it moves there). if damage.is_some() && let Some(r) = seen.filter(|s| s.0 == revision).and_then(|s| crate::adjust_preview::switch_region(app, id, revision, s.1 ^ display_key, raw_key)) @@ -1580,7 +1583,12 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: let r = gpu.refresh(id.0, &doc, Some(r), display.as_deref()); app.perf.record(r.kind, r.px, r.composite_ms, r.upload_ms); } - return true; + // Blend previews keep offscreen pixels untouched until the view reaches them. + // Use the normal refresh path so CPU fallback and pending redraws stay synchronized. + damage = crate::blend_preview::uncovered(app, id, revision, raw_key, visible); + if damage.is_none() { + return true; + } } // Display textures for a canvas this large would not fit the GPU: the reduced CPU canvas // draws it (checked before the memory budget, which walks the history, every frame). @@ -8003,3 +8011,7 @@ mod rotation_preview_isolation_tests { #[cfg(test)] #[path = "canvas_display_memo_tests.rs"] mod display_memo_tests; + +#[cfg(test)] +#[path = "canvas/blend_viewport_tests.rs"] +mod blend_viewport_regression; diff --git a/crates/ui-egui/src/canvas/blend_viewport_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_tests.rs new file mode 100644 index 0000000000..fe06c0ba72 --- /dev/null +++ b/crates/ui-egui/src/canvas/blend_viewport_tests.rs @@ -0,0 +1,142 @@ +use super::*; +use photocraft_color::BlendMode; +use serde_json::json; + +fn render_state() -> Option { + match std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) { + Ok(rs) => Some(rs), + Err(error) => { + if std::env::var_os("PHOTOCRAFT_REQUIRE_GPU_TESTS").is_some() { + std::panic::resume_unwind(error); + } + eprintln!("skipping blend viewport regression: no GPU adapter"); + None + } + } +} + +#[test] +fn blend_hover_refresh_is_limited_to_visible_canvas() { + check_blend_viewport(false); +} + +#[test] +fn blend_hover_cpu_fallback_refresh_tracks_visible_canvas() { + check_blend_viewport(true); +} + +#[test] +fn blend_hover_during_background_redraw_restores_committed_pixels() { + let _guard = photocraft_testkit::gpu_lock(); + let Some(rs) = render_state() else { return }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.background_jobs = true; + app.run("file.new", json!({"width":2600,"height":1700,"background":"#336699"})).unwrap(); + let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); + app.run("layer.layerStyle.blendingOptions", json!({"knockout":"shallow"})).unwrap(); + let ctx = egui::Context::default(); + let visible = DRect::new(256, 256, 512, 512); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert!(!app.redraws.is_empty(), "fixture must start a deferred full redraw"); + crate::blend_preview::hover(&mut app, photocraft_doc::LayerId(layer), Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + let panned = DRect::new(2048, 1024, 2304, 1280); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + settle_redraw(&mut app); + assert_visible_pixels(&mut app, panned); + crate::blend_preview::hover(&mut app, photocraft_doc::LayerId(layer), None); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + settle_redraw(&mut app); + let bounds = app.session.active().unwrap().doc.bounds(); + assert_visible_pixels(&mut app, bounds); +} + +fn settle_redraw(app: &mut PhotocraftApp) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60); + let gpu = app.gpu.clone().unwrap(); + let id = app.session.active().unwrap().doc.id; + while !app.redraws.is_empty() { + crate::background_redraw::poll(app, &gpu, id); + assert!(std::time::Instant::now() < deadline, "background redraw did not finish"); + std::thread::sleep(std::time::Duration::from_millis(2)); + } +} + +fn assert_visible_pixels(app: &mut PhotocraftApp, visible: DRect) { + let (doc, _) = display_doc(app, 0); + let gpu = app.gpu.clone().unwrap(); + let reference = doc.id.0 ^ (1u64 << 60); + let (display, _) = canvas_display(app, &doc, None); + gpu.upload_composite(reference, &doc, display.as_deref()); + let (_, size, shown) = gpu.read_texels(doc.id.0).unwrap(); + let (_, _, want) = gpu.read_texels(reference).unwrap(); + for y in visible.y0..visible.y1 { + for x in visible.x0..visible.x1 { + let index = y as usize * size[0] as usize + x as usize; + for channel in 0..4 { + assert!((shown[index][channel] - want[index][channel]).abs() <= 2.0 / 255.0, "preview differs at ({x},{y}) channel{channel}"); + } + } + } +} + +fn check_blend_viewport(cpu_fallback: bool) { + let _guard = photocraft_testkit::gpu_lock(); + let Some(rs) = render_state() else { return }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap(); + let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); + if cpu_fallback { + app.run("layer.layerStyle.blendingOptions", json!({"knockout":"shallow"})).unwrap(); + } + let ctx = egui::Context::default(); + let visible = DRect::new(256, 256, 512, 512); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert!(app.redraws.is_empty(), "small fixture must finish synchronously"); + if cpu_fallback { + assert!(!app.perf.last_refresh.starts_with("gpu"), "fixture must exercise CPU composition fallback"); + } + let id = app.session.active().unwrap().doc.id; + let gpu = app.gpu.clone().unwrap(); + let original = gpu.read_texels(id.0).unwrap(); + crate::blend_preview::hover(&mut app, photocraft_doc::LayerId(layer), Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + println!("BLEND_VIEWPORT kind={} pixels={} expected={} adapter={:?}", app.perf.last_refresh, app.perf.last_refresh_px, 256 * 256, app.perf.gpu_info); + assert_eq!(app.perf.last_refresh_px, 256 * 256, "hover must not recomposite offscreen pixels of a full-canvas layer"); + assert_visible_pixels(&mut app, visible); + app.perf.last_refresh_px = 0; + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(app.perf.last_refresh_px, 0, "unchanged view and mode must reuse the texture"); + let zoomed_out = DRect::new(128, 128, 640, 640); + assert!(ensure_gpu(&mut app, &ctx, 0, zoomed_out)); + assert_eq!(app.perf.last_refresh_px, 512 * 512, "zooming out catches up the larger visible area"); + let panned = DRect::new(640, 256, 896, 512); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + assert_eq!(app.perf.last_refresh_px, 256 * 256, "newly exposed pixels must catch up without a mode change"); + crate::blend_preview::hover(&mut app, photocraft_doc::LayerId(layer), Some(BlendMode::Screen)); + assert!(ensure_gpu(&mut app, &ctx, 0, panned)); + assert_eq!(app.perf.last_refresh_px, 256 * 256); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(app.perf.last_refresh_px, 256 * 256, "returning view must show the current mode"); + assert_visible_pixels(&mut app, visible); + assert_visible_pixels(&mut app, panned); + crate::blend_preview::hover(&mut app, photocraft_doc::LayerId(layer), None); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(gpu.read_texels(id.0).unwrap(), original, "cancel must restore the whole texture, including previously previewed offscreen pixels"); + crate::blend_preview::hover(&mut app, photocraft_doc::LayerId(layer), Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + app.run("layer.setProps", json!({"layer":layer,"blend":"Multiply"})).unwrap(); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + let bounds = app.session.active().unwrap().doc.bounds(); + assert_visible_pixels(&mut app, bounds); + app.run("file.new", json!({"width":1024,"height":768,"background":"white"})).unwrap(); + assert!(ensure_gpu(&mut app, &ctx, 1, visible)); + app.session.set_active(0); + app.sync_views(); + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_visible_pixels(&mut app, bounds); +} From fbaf6795cfdc087b8343e7b1c351e7ddc8c8662d Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Wed, 14 Oct 2026 22:50:34 +0100 Subject: [PATCH 02/34] refactor(engine): drop the second damage pass after single-edit duplicates and pastes Session::edit has reported a new layer's bounds as damage since #3847, so Duplicate Layer, Duplicate Layers and Paste no longer need to keep the document from before the edit and work the damage out again with note_insert. Paste Into still does: it is three edits. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/commands.rs | 2 -- crates/engine/src/edit_cmds.rs | 4 +--- crates/engine/src/layer_multi_cmds.rs | 18 +++++++++++------- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 68d00a7da3..924f6e5f8f 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -648,7 +648,6 @@ fn build() -> Vec { return crate::layer_multi_cmds::duplicate_selected(s, in_place, "Duplicate Layers"); } let id = layer_param(s, p)?; - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let nid = s.edit("Duplicate Layer", |doc, active| { let mut dup = layer_copy(doc, id)?; if let Some(name) = &name { @@ -661,7 +660,6 @@ fn build() -> Vec { *active = Some(nid); Ok(nid) })?; - crate::layer_multi_cmds::note_insert(s, &before); Ok(json!({ "layer": nid.0 })) } ), diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index dcb89aa980..1340c70946 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -390,7 +390,6 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { let moved = shifted(&clip.surface, dx, dy); let target = PixelFormat::new(fmt.mode, fmt.sample, true); let surf = if moved.format() == target { moved } else { moved.convert(target) }; - let before = d.doc.clone(); let id = s.edit("Paste", |doc, active| { let mut l = Layer::raster(doc.next_layer_name("Layer"), target); *crate::pixels_mut(&mut l)? = surf; @@ -399,8 +398,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result { doc.selection = None; Ok(id) })?; - // Only where the pasted pixels land needs recompositing, not the whole document (#2901). - crate::layer_multi_cmds::note_insert(s, &before); + // `edit` reports only where the pasted pixels land as damage, not the whole document (#2901). Ok(json!({"layer": id.0, "offset": [dx, dy]})) } diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs index 9a79a72050..31733f12eb 100644 --- a/crates/engine/src/layer_multi_cmds.rs +++ b/crates/engine/src/layer_multi_cmds.rs @@ -884,9 +884,9 @@ pub(crate) fn note_inert_insert(s: &mut Session, id: LayerId) { } } -/// Report the pixels an edit from `before` that added layers changed ([`step_damage`]), for -/// commands made of more than one edit, so the canvas recomposites only where the new layers -/// draw instead of the whole document. +/// Report the pixels a command made of more than one edit changed since `before` ([`step_damage`]), +/// so the canvas recomposites only where its new layers draw instead of the whole document. +/// A single [`Session::edit`] already reports its own damage: don't call this after one (#5695). pub(crate) fn note_insert(s: &mut Session, before: &Document) { let Some(st) = s.active_mut() else { return }; st.last_damage = step_damage(before, &st.doc); @@ -1378,7 +1378,6 @@ pub fn delete_selected(s: &mut Session) -> Result { /// this path, #2777). pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Result { let sel = selected(s); - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); let old_active = s.active().and_then(|d| d.active_layer); let (copies, active) = s.edit(label, |doc, active| { let mut copies = Vec::new(); @@ -1400,7 +1399,6 @@ pub fn duplicate_selected(s: &mut Session, in_place: bool, label: &str) -> Resul *active = a; Ok((copies, a)) })?; - note_insert(s, &before); let out = copies.iter().map(|l| l.0).collect::>(); reselect(s, copies, active); Ok(json!({"layers": out, "layer": active.map(|l| l.0)})) @@ -1807,8 +1805,8 @@ mod tests { x.px.iter().zip(&y.px).enumerate().all(|(i, (p, q))| p == q || damage.contains(i as i32 % w, i as i32 / w)) } - /// Duplicate, paste and delete, and their undo and redo, recomposite only where the layer - /// draws; undoing a duplicate used to recomposite the whole document. + /// Duplicate (one layer or several), paste and delete, and their undo and redo, recomposite + /// only where the layers draw; undoing a duplicate used to recomposite the whole document. #[test] fn duplicate_paste_and_delete_report_where_the_layer_draws() { let mut s = session(8); @@ -1831,6 +1829,12 @@ mod tests { s.execute("edit.copy", json!({})).unwrap(); s.execute("select.deselect", json!({})).unwrap(); step(&mut s, "edit.paste", json!({})); + // Duplicating several selected layers reports where the copies draw, too. + let b = rect_layer(&mut s, Rect::new(30, 30, 40, 40)); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + step(&mut s, "layer.duplicate", json!({})); + assert_eq!(damage(&s), Some(Rect::new(10, 10, 40, 40)), "both copies, nothing else"); step(&mut s, "layer.delete", json!({"layer": a.0})); } From f8cc7fca50f6a378a154e6cebb4b449c25268650 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 14 Oct 2026 20:07:49 -0700 Subject: [PATCH 03/34] Brushes: importing an .abr file numbers repeated brush names in linear time brush.presets.importAbr named each imported preset with unique, which compared a candidate name with the names of the presets one by one and tried "Name", "Name 2", "Name 3" and so on until one was free. A version 1 or 2 brush with a computed tip and no name is named after its tip ("9 px Round"), so a file of n such brushes of one diameter cost about n^3/6 string comparisons. In a test build, importing 10,000 of them took 25 minutes (22 minutes of CPU time). The import now builds the set of preset names once and keeps the next number to try for each repeated name, as swatches.import does for swatch and group names. Names still compare case-insensitively, and every preset gets the same name as before. brush.presets.importImage names its one preset with the same code. repeated_brush_names_are_numbered_in_linear_time imports 10,000 such brushes on a thread of its own and fails when the import takes more than 20 seconds. repeated_brush_names_take_the_first_free_number checks the names when the file repeats a name in other letter cases, when a preset already holds one of the numbers, when the file has a name that the import already gave to an earlier brush, and when a name clashes with a built-in preset. --- crates/engine/src/preset_import_cmds.rs | 90 +++++++++++++++++++++---- 1 file changed, 76 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/preset_import_cmds.rs b/crates/engine/src/preset_import_cmds.rs index 8da6cee8a0..51ce9bf078 100644 --- a/crates/engine/src/preset_import_cmds.rs +++ b/crates/engine/src/preset_import_cmds.rs @@ -49,13 +49,32 @@ pub(crate) fn file_bytes(p: &Value, cmd: &str, what: &str) -> Result<(Vec, S Ok((bytes, stem)) } -/// A name not used by any preset in `taken` (case-insensitive): `name`, `name 2`, `name 3`… -fn unique(name: &str, taken: &[String]) -> String { - let free = |n: &str| !taken.iter().any(|t| t.eq_ignore_ascii_case(n)); - if free(name) { - return name.to_string(); +/// The preset names in use, for naming new presets. +struct UniqueNames { + /// Every name in use, ASCII-lowercased. + taken: std::collections::HashSet, + /// The next number to try for each repeated name (lowercased). + next: std::collections::HashMap, +} + +impl UniqueNames { + fn new<'a>(names: impl IntoIterator) -> Self { + UniqueNames { taken: names.into_iter().map(str::to_ascii_lowercase).collect(), next: std::collections::HashMap::new() } + } + + /// A name not in use (case-insensitive): `name`, `name 2`, `name 3`… It is in use from then on. + fn unique(&mut self, name: &str) -> String { + let key = name.to_ascii_lowercase(); + if self.taken.insert(key.clone()) { + return name.to_string(); + } + // Resume numbering per name, so a file of identical names stays linear. + let from = self.next.get(&key).copied().unwrap_or(2); + let i = (from..).find(|i| !self.taken.contains(&format!("{key} {i}"))).unwrap_or(from); + self.taken.insert(format!("{key} {i}")); + self.next.insert(key, i + 1); + format!("{name} {i}") } - (2..).map(|i| format!("{name} {i}")).find(|n| free(n)).unwrap_or_else(|| name.to_string()) } fn import_abr(s: &mut Session, p: &Value) -> Result { @@ -93,11 +112,10 @@ fn add_abr_presets(s: &mut Session, p: &Value, group: String, imp: photocraft_io if p.get("replace").and_then(Value::as_bool).unwrap_or(true) { s.tools.presets.retain(|x| x.builtin || x.group != group); } - let mut taken: Vec = s.tools.presets.iter().map(|x| x.name.clone()).collect(); + let mut taken = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())); let mut names = Vec::with_capacity(imp.presets.len()); for mut preset in imp.presets { - preset.name = unique(&preset.name, &taken); - taken.push(preset.name.clone()); + preset.name = taken.unique(&preset.name); names.push(preset.name.clone()); s.tools.presets.push(preset); } @@ -180,8 +198,7 @@ fn import_image(s: &mut Session, p: &Value) -> Result { let doc = crate::file_cmds::import(decode_name, &bytes)?; let (v, w, h) = image_paint(&doc, cmd)?; let (brush, tw, th) = crate::brush_cmds::sampled_brush(cmd, &v, w, h)?; - let taken: Vec = s.tools.presets.iter().map(|x| x.name.clone()).collect(); - let name = unique(&name, &taken); + let name = UniqueNames::new(s.tools.presets.iter().map(|x| x.name.as_str())).unique(&name); s.tools.presets.push(photocraft_paint::BrushPreset { name: name.clone(), brush: brush.clone(), @@ -526,10 +543,55 @@ mod tests { assert_eq!(s.tools.presets.len(), n, "a failed import adds nothing"); } + /// A version 1 brush with a computed tip and no name is named after its tip ("9 px Round"). The + /// import used to number each repeated name by searching the preset names once for every number + /// it tried, so importing 10,000 such brushes took minutes. The test fails when the import takes + /// more than 20 seconds. + #[test] + fn repeated_brush_names_are_numbered_in_linear_time() { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut s = Session::new(); + s.execute("brush.presets.save", json!({"name": "9 PX ROUND 3"})).unwrap(); + let round = LegacyBrush { + name: String::new(), + spacing: 25, + anti_alias: true, + tip: LegacyTip::Computed { diameter: 9, hardness: 100, angle: 0, roundness: 100 }, + }; + let data = photocraft_paint::tile::b64_encode(&write_v12(1, &vec![round; 10_000], false).unwrap()); + let r = s.execute("brush.presets.importAbr", json!({"data": data})).unwrap(); + let names: Vec = r["imported"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect(); + let _ = tx.send(names); + }); + let names = match rx.recv_timeout(std::time::Duration::from_secs(20)) { + Ok(names) => names, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!("importing the brushes did not finish"), + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => panic!("the import thread panicked"), + }; + // Numbering starts at 2 and skips the number a preset already uses, in any letter case. + assert_eq!(names[..4], ["9 px Round", "9 px Round 2", "9 px Round 4", "9 px Round 5"]); + assert_eq!(names.last(), Some(&format!("9 px Round {}", names.len() + 1))); + assert_eq!(names.iter().collect::>().len(), names.len()); + } + + #[test] + fn repeated_brush_names_take_the_first_free_number() { + let mut s = Session::new(); + s.execute("brush.presets.save", json!({"name": "speckle 3"})).unwrap(); + let tip = AbrSample { id: String::new(), width: 6, height: 4, depth: 8, data: vec![255; 24] }; + let brush = |name: &str| LegacyBrush { name: name.into(), spacing: 25, anti_alias: true, tip: LegacyTip::Sampled(tip.clone()) }; + let file = write_v12(2, &["Speckle", "SPECKLE", "speckle", "Speckle 2", "Speckle", "hard round"].map(brush), true).unwrap(); + let r = s.execute("brush.presets.importAbr", json!({"data": photocraft_paint::tile::b64_encode(&file)})).unwrap(); + // Names that differ only in letter case count as the same name. The file's "Speckle 2" comes + // after "SPECKLE" took that name, and "hard round" clashes with the built-in Hard Round. + assert_eq!(r["imported"], json!(["Speckle", "SPECKLE 2", "speckle 4", "Speckle 2 2", "Speckle 5", "hard round 2"])); + } + #[test] fn unique_names() { - let taken = vec!["A".to_string(), "a 2".to_string()]; - assert_eq!(unique("a", &taken), "a 3"); - assert_eq!(unique("B", &taken), "B"); + let mut taken = UniqueNames::new(["A", "a 2"]); + assert_eq!(taken.unique("a"), "a 3"); + assert_eq!(taken.unique("B"), "B"); } } From f49564d281bf8892db58ed154767717223aff4f6 Mon Sep 17 00:00:00 2001 From: Bram Heerink <1698441+bramheerink@users.noreply.github.com> Date: Thu, 15 Oct 2026 12:05:48 +0700 Subject: [PATCH 04/34] PSD: keep guide resources 1092/1097 only while they match the guides (#5966) Photoshop writes image resource 1092 (guides v2: 1032's guides plus a colour per guide) and 1097 (one GUID per guide) next to 1032. Export regenerated 1032 from the document but wrote 1092 and 1097 back verbatim, so after Clear Guides, New Guide, a move or a recolour the file carried two guide lists that disagree. Both are now written back only while 1092 still describes the document's guides (positions, directions and colours) and 1097 has as many entries; otherwise both are left out and the file carries 1032 alone, as files from before guides v2 do. Import takes the guides' own colours from 1092 (Photoshop's default Cyan stays with the preference colour), the read half of #5967. Co-Authored-By: Claude Opus 5.5 --- crates/io/src/guides_map.rs | 157 +++++++++++++++++++++++++++++++++++ crates/io/src/lib.rs | 1 + crates/io/src/psd_export.rs | 4 + crates/io/src/psd_import.rs | 1 + crates/io/tests/guides_v2.rs | 128 ++++++++++++++++++++++++++++ docs/file-format-parity.md | 1 + 6 files changed, 292 insertions(+) create mode 100644 crates/io/src/guides_map.rs create mode 100644 crates/io/tests/guides_v2.rs diff --git a/crates/io/src/guides_map.rs b/crates/io/src/guides_map.rs new file mode 100644 index 0000000000..6137011e2c --- /dev/null +++ b/crates/io/src/guides_map.rs @@ -0,0 +1,157 @@ +//! Guides ⇄ PSD beyond image resource 1032. +//! +//! Photoshop writes two undocumented resources next to 1032 (Grid and Guides), layout +//! inferred from the psd-tools, ag-psd and Photoshop-authored corpora (#5965): +//! +//! * 1092, Grid and Guides version 2: `u32` version 2, `u32` horizontal and vertical grid +//! cycle (576 = 18 px in 1/32 px, as in 1032), `u32` count, then per guide 9 bytes: `i32` +//! position in 1/32 px, `u8` direction (0 vertical, 1 horizontal), one `u8` that is always 0 +//! in the corpora, and the guide's colour as `u8` R, G, B. In every corpus file its guides +//! equal 1032's, in the same order. +//! * 1097: `u32` count (1092's), then per guide a length-prefixed ASCII GUID, a `u32` 0 and a +//! second length-prefixed GUID, always all zeros. +//! +//! Import takes the guides' own colours from 1092 (a guide in Photoshop's default colour keeps +//! following the preference colour). Export keeps both resources only while 1092 still +//! describes the document's guides and colours; otherwise it leaves both out, so the file +//! carries 1032 alone, as Photoshop files before version 2 did (#5966). + +use photocraft_doc::{Document, Guides}; + +/// Grid and Guides, version 2 (positions, directions and colours). +pub const GUIDES_V2: u16 = 1092; +/// One GUID per guide, in 1092's order. +pub const GUIDE_IDS: u16 = 1097; +/// Photoshop's default guide colour (Cyan, `#4affff`), which 1092 also stores for guides +/// that use the preference colour. +pub const DEFAULT_GUIDE_RGB: [u8; 3] = [0x4a, 0xff, 0xff]; + +/// One guide of a 1092 resource. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct GuideV2 { + /// Position in 1/32 px. + pub location: i32, + pub vertical: bool, + pub rgb: [u8; 3], +} + +fn be_u32(data: &[u8], at: usize) -> Option { + let b = data.get(at..at.checked_add(4)?)?; + Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) +} + +/// The guides of a 1092 resource, or `None` when it is not version 2 or is cut short. +pub fn parse_v2(data: &[u8]) -> Option> { + if be_u32(data, 0)? != 2 { + return None; + } + let count = usize::try_from(be_u32(data, 12)?).ok()?; + // Each guide takes 9 bytes: a count the data can't hold is not a 1092 we understand. + if count > data.len().saturating_sub(16) / 9 { + return None; + } + (0..count) + .map(|i| { + let at = 16 + i * 9; + let g = data.get(at..at + 9)?; + Some(GuideV2 { location: i32::from_be_bytes([g[0], g[1], g[2], g[3]]), vertical: g[4] != 1, rgb: [g[6], g[7], g[8]] }) + }) + .collect() +} + +/// The number of entries a 1097 resource declares. +pub fn ids_count(data: &[u8]) -> Option { + be_u32(data, 0) +} + +/// The document's guides as 1092 would store them, sorted. +fn expected(guides: &Guides) -> Vec { + let mut v: Vec = [(&guides.vertical, true), (&guides.horizontal, false)] + .into_iter() + .flat_map(|(list, vertical)| { + list.iter().map(move |&p| GuideV2 { location: (p * 32.0).round() as i32, vertical, rgb: guides.color(vertical, p).unwrap_or(DEFAULT_GUIDE_RGB) }) + }) + .collect(); + v.sort(); + v +} + +/// Whether an imported 1092 still describes the document's guides: the same positions, +/// directions and colours, in any order. +pub fn describes(doc: &Document, data: &[u8]) -> bool { + let Some(mut stored) = parse_v2(data) else { return false }; + stored.sort(); + stored == expected(&doc.guides) +} + +/// Whether to write back an imported 1092 or 1097: only while 1092 describes the guides +/// (and, for 1097, holds as many entries as 1092). +pub fn keep_resource(doc: &Document, id: u16, data: &[u8]) -> bool { + match id { + GUIDES_V2 => describes(doc, data), + GUIDE_IDS => { + let v2 = doc.metadata.psd_resources.iter().find(|(rid, _, _)| *rid == GUIDES_V2); + v2.is_some_and(|(_, _, d)| describes(doc, d) && parse_v2(d).map(|g| g.len()).and_then(|n| u32::try_from(n).ok()) == ids_count(data)) + } + _ => true, + } +} + +/// Gives the document's guides the colours an imported 1092 stores. Only guides that 1032 +/// also has are coloured, and Photoshop's default colour is left to the preference. +pub fn apply_colors(doc: &mut Document) { + let Some(stored) = doc.metadata.psd_resources.iter().find(|(id, _, _)| *id == GUIDES_V2).and_then(|(_, _, d)| parse_v2(d)) else { + return; + }; + for g in stored { + if g.rgb == DEFAULT_GUIDE_RGB { + continue; + } + let pos = f64::from(g.location) / 32.0; + let list = if g.vertical { &doc.guides.vertical } else { &doc.guides.horizontal }; + if list.contains(&pos) { + doc.guides.set_color(g.vertical, pos, Some(g.rgb)); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v2(guides: &[(i32, u8, [u8; 3])]) -> Vec { + let mut v = Vec::new(); + for n in [2u32, 576, 576, guides.len() as u32] { + v.extend_from_slice(&n.to_be_bytes()); + } + for (loc, dir, rgb) in guides { + v.extend_from_slice(&loc.to_be_bytes()); + v.extend_from_slice(&[*dir, 0]); + v.extend_from_slice(rgb); + } + v + } + + #[test] + fn parses_corpus_layout() { + // clipping-mask4.psd (psd-tools): one vertical and one horizontal guide at 16 px. + let d = v2(&[(512, 0, DEFAULT_GUIDE_RGB), (512, 1, DEFAULT_GUIDE_RGB)]); + let g = parse_v2(&d).unwrap(); + assert_eq!(g.len(), 2); + assert!(g[0].vertical && !g[1].vertical); + assert_eq!(g[1].location, 512); + } + + #[test] + fn rejects_other_versions_and_short_or_hostile_data() { + let mut d = v2(&[(512, 0, DEFAULT_GUIDE_RGB)]); + assert!(parse_v2(&d[..d.len() - 1]).is_none()); + d[3] = 1; + assert!(parse_v2(&d).is_none()); + let mut huge = v2(&[]); + huge[12..16].copy_from_slice(&u32::MAX.to_be_bytes()); + assert!(parse_v2(&huge).is_none()); + assert!(parse_v2(&[]).is_none()); + assert!(ids_count(&[0, 0]).is_none()); + } +} diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 378122986e..646a824364 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -44,6 +44,7 @@ pub mod effects_map; pub mod exr_parts; mod flat; mod gradient_bake; +pub mod guides_map; pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient}; mod kra; pub mod linked; diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 8ba30d83c4..8d99a9d895 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -1253,6 +1253,10 @@ pub(crate) fn keep_imported_resource(doc: &Document, id: u16, data: &[u8]) -> bo if !crate::annotations_map::keep_resource(doc, id) { return false; } + // Guides v2 and guide GUIDs: only while they still describe the document's guides. + if !crate::guides_map::keep_resource(doc, id, data) { + return false; + } // A preserved clipping-path resource is only valid while it names the current one. if id == crate::vector_map::CLIPPING_PATH { let n = usize::from(data.first().copied().unwrap_or(0)); diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs index c20c1b7fe7..ae4e15d9b4 100644 --- a/crates/io/src/psd_import.rs +++ b/crates/io/src/psd_import.rs @@ -830,6 +830,7 @@ pub(crate) fn psd_to_document_decoded( id => doc.metadata.psd_resources.push((id, String::from_utf8_lossy(&r.name).into_owned(), Arc::new(r.data.clone()))), } } + crate::guides_map::apply_colors(&mut doc); for b in &file.global_blocks { doc.metadata.psd_global_blocks.push((b.signature, b.key, Arc::new(b.data.clone()))); } diff --git a/crates/io/tests/guides_v2.rs b/crates/io/tests/guides_v2.rs new file mode 100644 index 0000000000..73884f00f4 --- /dev/null +++ b/crates/io/tests/guides_v2.rs @@ -0,0 +1,128 @@ +//! Image resources 1092 (guides with colours) and 1097 (guide GUIDs) next to 1032 (#5966). + +use photocraft_io::guides_map::{DEFAULT_GUIDE_RGB, GUIDE_IDS, GUIDES_V2}; +use photocraft_io::*; +use photocraft_psd::testgen; +use photocraft_psd::{Compression, ImageResource, PsdFile, Version}; + +const RED: [u8; 3] = [0xff, 0x00, 0x00]; + +type Edit = fn(&mut photocraft_doc::Document); + +fn guides_v1(guides: &[(i32, u8)]) -> Vec { + let mut v = Vec::new(); + for n in [1u32, 576, 576, guides.len() as u32] { + v.extend_from_slice(&n.to_be_bytes()); + } + for (loc, dir) in guides { + v.extend_from_slice(&loc.to_be_bytes()); + v.push(*dir); + } + v +} + +fn guides_v2(guides: &[(i32, u8, [u8; 3])]) -> Vec { + let mut v = Vec::new(); + for n in [2u32, 576, 576, guides.len() as u32] { + v.extend_from_slice(&n.to_be_bytes()); + } + for (loc, dir, rgb) in guides { + v.extend_from_slice(&loc.to_be_bytes()); + v.extend_from_slice(&[*dir, 0]); + v.extend_from_slice(rgb); + } + v +} + +fn guide_ids(n: u32) -> Vec { + let mut v = n.to_be_bytes().to_vec(); + for i in 0..n { + let id = format!("0000000{i}-1111-2222-3333-444444444444"); + let zero = "00000000-0000-0000-0000-000000000000"; + v.extend_from_slice(&36u32.to_be_bytes()); + v.extend_from_slice(id.as_bytes()); + v.extend_from_slice(&0u32.to_be_bytes()); + v.extend_from_slice(&36u32.to_be_bytes()); + v.extend_from_slice(zero.as_bytes()); + } + v +} + +/// A file as Photoshop writes it: a vertical guide at 16 px in the default colour and a red +/// horizontal one at 10 px, in 1032, 1092 and 1097. +fn photoshop_file() -> PsdFile { + let mut f = testgen::small(Version::Psd, Compression::Raw); + f.resources.push(ImageResource::new(1032, guides_v1(&[(512, 0), (320, 1)]))); + f.resources.push(ImageResource::new(GUIDES_V2, guides_v2(&[(512, 0, DEFAULT_GUIDE_RGB), (320, 1, RED)]))); + f.resources.push(ImageResource::new(GUIDE_IDS, guide_ids(2))); + f +} + +fn resource(f: &PsdFile, id: u16) -> Option<&[u8]> { + f.resources.iter().find(|r| r.id == id).map(|r| r.data.as_slice()) +} + +#[test] +fn colours_come_from_guides_v2() { + let (d, _) = psd_to_document(&photoshop_file()); + assert_eq!(d.guides.vertical, [16.0]); + assert_eq!(d.guides.horizontal, [10.0]); + assert_eq!(d.guides.color(false, 10.0), Some(RED)); + // The default colour stays with the preference. + assert_eq!(d.guides.color(true, 16.0), None); +} + +#[test] +fn unchanged_guides_keep_both_resources_byte_exact() { + let f = photoshop_file(); + let (d, _) = psd_to_document(&f); + let out = document_to_psd(&d); + assert_eq!(resource(&out, GUIDES_V2), resource(&f, GUIDES_V2)); + assert_eq!(resource(&out, GUIDE_IDS), resource(&f, GUIDE_IDS)); +} + +#[test] +fn edited_guides_drop_both_resources() { + let (base, _) = psd_to_document(&photoshop_file()); + let edits: [(&str, Edit); 4] = [ + ("clear", |d| d.guides = Default::default()), + ("add", |d| d.guides.horizontal.push(40.0)), + ("move", |d| { + d.guides.vertical[0] = 20.0; + }), + ("recolour", |d| d.guides.set_color(true, 16.0, Some(RED))), + ]; + for (name, edit) in edits { + let mut d = base.clone(); + edit(&mut d); + let out = document_to_psd(&d); + assert!(resource(&out, GUIDES_V2).is_none(), "{name}: stale 1092 written"); + assert!(resource(&out, GUIDE_IDS).is_none(), "{name}: stale 1097 written"); + let (back, _) = psd_to_document(&out); + assert_eq!(back.guides.vertical, d.guides.vertical, "{name}"); + assert_eq!(back.guides.horizontal, d.guides.horizontal, "{name}"); + } +} + +#[test] +fn mismatched_ids_or_malformed_v2_are_not_kept() { + let mut f = photoshop_file(); + f.resources.retain(|r| r.id != GUIDE_IDS); + f.resources.push(ImageResource::new(GUIDE_IDS, guide_ids(3))); + let (d, _) = psd_to_document(&f); + let out = document_to_psd(&d); + assert!(resource(&out, GUIDES_V2).is_some()); + assert!(resource(&out, GUIDE_IDS).is_none()); + + let mut f = photoshop_file(); + for r in &mut f.resources { + if r.id == GUIDES_V2 { + r.data.truncate(20); + } + } + let (d, _) = psd_to_document(&f); + assert_eq!(d.guides.color(false, 10.0), None); + let out = document_to_psd(&d); + assert!(resource(&out, GUIDES_V2).is_none()); + assert!(resource(&out, GUIDE_IDS).is_none()); +} diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index b0771c4d62..5c362e922f 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) | | 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 | | 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) | | 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 | From 11e4b407356a9411a057cb9e1ba11cb755efe80c Mon Sep 17 00:00:00 2001 From: Persi Date: Thu, 15 Oct 2026 07:50:38 +0200 Subject: [PATCH 05/34] PSD export: check the Background's opacity from its tiles --- crates/io/src/flat.rs | 2 +- crates/io/src/psd_export.rs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 54fe96090d..3190c8e08c 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -482,7 +482,7 @@ fn drop_alpha(data: &mut Vec, color: usize, alpha: usize) { } /// Whether every pixel of `s` over `r` is fully opaque (read from the tiles, no copy). -fn opaque_surface(s: &Surface, r: Rect) -> bool { +pub(crate) fn opaque_surface(s: &Surface, r: Rect) -> bool { let fmt = s.format(); let (ch, bps) = (fmt.channels(), fmt.sample.bytes()); let a = ch - 1; diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rs index 4fb952ba25..93982bfa57 100644 --- a/crates/io/src/psd_export.rs +++ b/crates/io/src/psd_export.rs @@ -102,9 +102,7 @@ fn psd_background(doc: &Document) -> Option { if canvas.is_empty() || s.content_bounds() != canvas { return None; } - let n = s.channels(); - let opaque = s.read_region(canvas).chunks_exact(n).all(|p| p.last().is_some_and(|a| *a >= 1.0)); - opaque.then_some(l.id) + crate::flat::opaque_surface(s, canvas).then_some(l.id) } /// How deep embedded documents are exported inside each other before a smart object is written From d743c2532da53ac69a85da9fcf01a6663cb7481b Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 14 Oct 2026 17:07:13 +0800 Subject: [PATCH 06/34] perf(compose): bevel maps shade, chisel and mix rows on threads, results unchanged A chisel bevel size change rebuilds the bevel maps of the whole layer region. The distance fields already run on threads (#2119), but the passes after them still ran on one thread over every pixel: the chisel height from the two distances, the texture term, the highlight/shadow shading (once, or twice for emboss styles) and the emboss inside/outside mix. Each of these computes a pixel from its own inputs only (the height map, the shape, the distances), so they now go row by row through par_units / par_fill like the fields: the same arithmetic in the same order per pixel, so the maps are bit for bit the old ones whatever the thread count. Maps under 65536 pixels and wasm stay on the calling thread. Test: bevel_maps_do_not_depend_on_the_threads (4 shapes x 5 styles x 3 techniques, with soften and a texture, 1 vs 2, 5 and 16 threads, every map bit-equal). --- crates/compose/src/effects.rs | 136 ++++++++++++++++++++++++++-------- 1 file changed, 107 insertions(+), 29 deletions(-) diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index 5acdd79314..ad6b763136 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -1511,11 +1511,15 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern } else { let sharp = sharp_edges(shape); let (din, dout) = (bevel_dist_inside(shape, &sharp, size), bevel_dist_outside(shape, &sharp, size)); - let mut h = Map::new(shape.w, shape.h, 0.0); let soft = g.chisel_soft > 0.0; - for i in 0..h.v.len() { - h.v[i] = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); - } + let w = shape.w; + let v = par_fill(w, shape.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * w + x; + *o = bevel_chisel_h(g.paint, size, din[i], dout[i], soft); + } + }); + let mut h = Map { w, h: shape.h, v }; // Inner and outer Chisel Soft are not blurred in Photoshop (their facets equal Chisel // Hard's across a straight edge); emboss styles keep the blur until measured. if soft && g.paint == BevelPaint::Both { @@ -1536,14 +1540,23 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0); let k = t.depth / unit; let (x0, y0) = (tex.rect.x0, tex.rect.y0); - for y in 0..h.h { - for x in 0..h.w { - let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); - let p = tile.sample(u, v); - let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; - h.v[y * h.w + x] += k * if t.invert { 1.0 - l } else { l }; - } - } + let w = h.w; + par_units( + h.v.len(), + &mut h.v, + w, + &mut [] as &mut [()], + 0, + || (), + |_, y, row, _| { + for (x, o) in row.iter_mut().enumerate() { + let (u, v) = place.map(f64::from(x0 + x as i32) + 0.5, f64::from(y0 + y as i32) + 0.5); + let p = tile.sample(u, v); + let l = (0.299 * p[0] + 0.587 * p[1] + 0.114 * p[2]) * p[3]; + *o += k * if t.invert { 1.0 - l } else { l }; + } + }, + ); } if b.soften >= 1.0 { tent(&mut h, b.soften); @@ -1625,23 +1638,33 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat }; let shade_into = |depth: f32, region_kind: u8| -> (Map, Map) { let (mut hi, mut sh) = (Map::new(shape.w, shape.h, 0.0), Map::new(shape.w, shape.h, 0.0)); - for y in 0..shape.h as i64 { - for x in 0..shape.w as i64 { - let i = y as usize * shape.w + x as usize; - let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; - let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; - let n = [-gx, -gy, 1.0]; - let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); - let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; - let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; - let k = shade - se; - if k > 0.0 { - hi.v[i] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; - } else { - sh.v[i] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; + // Rows on threads: every pixel reads only `hmap` and `shape`. + par_units( + hi.v.len(), + &mut hi.v, + shape.w, + &mut sh.v, + shape.w, + || (), + |_, y, hi_row, sh_row| { + let y = y as i64; + for x in 0..shape.w as i64 { + let i = y as usize * shape.w + x as usize; + let gx = (hmap.get(x + 1, y) - hmap.get(x - 1, y)) * 0.5 * depth; + let gy = (hmap.get(x, y + 1) - hmap.get(x, y - 1)) * 0.5 * depth; + let n = [-gx, -gy, 1.0]; + let len = (n[0] * n[0] + n[1] * n[1] + 1.0).sqrt(); + let shade = (n[0] * light_v[0] + n[1] * light_v[1] + n[2] * light_v[2]) / len; + let region = if region_kind == 0 { shape.v[i] } else { f32::from(shape.v[i] < 1.0 - INSIDE_EPS && on_bevel(x, y)) }; + let k = shade - se; + if k > 0.0 { + hi_row[x as usize] = (k / (1.0 - se).max(1e-3)).clamp(0.0, 1.0) * region; + } else { + sh_row[x as usize] = (-k / se.max(1e-3)).clamp(0.0, 1.0) * region; + } } - } - } + }, + ); (apply_contour(hi, &b.gloss_contour), apply_contour(sh, &b.gloss_contour)) }; let maps = match g.paint { @@ -1657,7 +1680,13 @@ fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, pat let (hi, sh) = shade_into(g.depth, 0); let (ho, so) = shade_into(if g.pillow { -g.depth } else { g.depth }, 1); let mix = |a: Map, b: Map| -> Map { - let v = a.v.iter().zip(&b.v).zip(&shape.v).map(|((x, y), s)| if *s > INSIDE_EPS { *x } else { 0.0 } + y * (1.0 - s.min(1.0))).collect(); + let v = par_fill(a.w, a.h, 0.0, |y, row| { + for (x, o) in row.iter_mut().enumerate() { + let i = y * a.w + x; + let (x, y, s) = (a.v[i], b.v[i], shape.v[i]); + *o = if s > INSIDE_EPS { x } else { 0.0 } + y * (1.0 - s.min(1.0)); + } + }); Map { w: a.w, h: a.h, v } }; vec![mix(hi, ho), mix(sh, so)] @@ -2932,6 +2961,55 @@ mod tests { } } + #[test] + fn bevel_maps_do_not_depend_on_the_threads() { + // Every style and technique, softened or not, and a texture; one thread (in order) is the reference. + let mut patchy = aa_disc(101, 101, 40.0); + for (i, v) in patchy.v.iter_mut().enumerate() { + if (i % 101 / 13 + i / 101 / 17) % 5 == 0 { + *v *= 0.6; + } + } + let shapes = [aa_disc(97, 83, 30.0), aa_round_rect(131, 77, 9.0, 11.0, 120.0, 66.0, 14.0), aa_bar(90, 130, 60.0, 150.0, 25.0), patchy]; + let mut sf = photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8); + sf.fill_rect(Rect::new(0, 0, 4, 2), &[0.0, 0.0, 0.0, 1.0]); + sf.fill_rect(Rect::new(0, 2, 4, 4), &[1.0, 1.0, 1.0, 1.0]); + let pats = [Pattern::new("stripes", sf, 4, 4)]; + let light = GlobalLight::default(); + let styles = [BevelStyle::InnerBevel, BevelStyle::OuterBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]; + for (k, shape) in shapes.iter().enumerate() { + let tex = TextureCtx { rect: Rect::new(3, 5, 3 + shape.w as i32, 5 + shape.h as i32), patterns: &pats, anchor: (0.0, 0.0) }; + for style in styles { + for technique in [BevelTechnique::Smooth, BevelTechnique::ChiselHard, BevelTechnique::ChiselSoft] { + for (size, soften, textured) in [(5.0, 0.0, false), (12.0, 2.0, false), (8.0, 0.0, true)] { + let mut b = bevel_of(style, technique); + (b.size, b.soften) = (size, soften); + if textured { + b.texture = Some(photocraft_doc::BevelTexture { + name: "stripes".into(), + id: String::new(), + scale: 1.0, + depth: 1.0, + invert: false, + link: true, + phase: (0.0, 0.0), + }); + } + let run = || bevel_maps(shape, &b, &light, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES)).0; + let one = with_threads(1, run); + for threads in [2, 5, 16] { + let many = with_threads(threads, run); + assert_eq!(one.len(), many.len()); + for (j, (a, m)) in one.iter().zip(&many).enumerate() { + assert_eq!(bits(&a.v), bits(&m.v), "shape {k}, {style:?} {technique:?} size {size} map {j} on {threads} threads"); + } + } + } + } + } + } + } + /// The four fields that use the distance transform, of `m`. fn distance_field_of(m: &Map, reach: f32) -> Vec> { [FieldKind::Inside, FieldKind::Outside, FieldKind::BevelInside, FieldKind::BevelOutside] From 5a93e93a4481aff65d495bf49ac05adcfe0ea4bb Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 14 Oct 2026 19:13:21 +0800 Subject: [PATCH 07/34] perf(gpu): a chisel bevel's two fields find their sharp edges once On the GPU canvas a bevel size change recomputes BevelInside and BevelOutside on the CPU, one distance_field call each, and each call ran sharp_edges (edge pixels and refined normals) on the same window again; the CPU compositor already shares them (bevel_height). sharp_edges was ~17% of the CPU time of those size changes. When both fields are recomputed over the same rectangle at the same reach (a size change, a new shape), sync_fx now computes them together: compose::effects::bevel_distance_fields finds the sharp edges once and returns both. Same window, same functions, so both fields are bit for bit the ones computed one at a time; the chamfer fields, wasm and a single bevel field keep the old path. Test: paired_bevel_fields_equal_the_fields_one_at_a_time (reach 3, 9, 40; whole region and two parts; bit-equal to field() of each kind). --- crates/compose/src/effects.rs | 8 +++++++ crates/gpu/src/fx.rs | 39 +++++++++++++++++++++++++++++++++++ crates/gpu/src/lib.rs | 31 ++++++++++++++++++---------- 3 files changed, 67 insertions(+), 11 deletions(-) diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index ad6b763136..d4f65dcb40 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -2319,6 +2319,14 @@ pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reac } } +/// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its +/// [`distance_field`], with the sharp edges they both start from found once. +pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] { + let s = Map { w, h, v: alpha }; + let sharp = sharp_edges(&s); + [bevel_dist_inside(&s, &sharp, reach), bevel_dist_outside(&s, &sharp, reach)] +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 01e147d51a..4b4ae5d575 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -558,6 +558,21 @@ fn field_banded(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: R parts.concat() } +/// [`field`] of both bevel fields over the same `out`, `[BevelInside, BevelOutside]`: one window, +/// whose sharp edges are found once instead of once per field. +pub(crate) fn bevel_fields(reach: i32, shape: &[f32], region: Rect, out: Rect) -> [Vec; 2] { + let [inside, outside] = [FieldKind::BevelInside, FieldKind::BevelOutside]; + if !threaded_inside(inside) { + return [inside, outside].map(|k| field(k, reach, shape, region, out)); + } + let win = out.inflate(field_radius(inside, reach) + 1).intersect(®ion); + if win.is_empty() { + return [Vec::new(), Vec::new()]; + } + let f = photocraft_compose::effects::bevel_distance_fields(crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32); + if win == out { f } else { f.map(|f| crop(&f, win, out)) } +} + /// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands. pub(crate) fn shape(doc: &photocraft_doc::Document, layer: &Layer, r: Rect) -> Vec { if r.is_empty() { @@ -842,6 +857,30 @@ mod tests { assert!(too_small_noticed, "a 2 row halo went unnoticed, so this test guards nothing"); } + /// Both bevel fields from one window (sharp edges found once) are bit for bit the fields + /// computed one at a time, over the whole region and over a part of it. + #[test] + fn paired_bevel_fields_equal_the_fields_one_at_a_time() { + let region = Rect::new(-20, -10, 300, 290); + let (w, h) = (region.width() as usize, region.height() as usize); + let mut shape = vec![0.0f32; w * h]; + for y in 0..h { + for x in 0..w { + let (fx, fy) = (x as f32 - 150.0, y as f32 - 140.0); + let r = (fx * fx + fy * fy).sqrt() + 8.0 * (fy * 0.07).sin() * (fx * 0.05).cos(); + shape[y * w + x] = (90.0 - r).clamp(0.0, 1.0) * if (x / 13 + y / 17) % 5 == 0 { 0.6 } else { 1.0 }; + } + } + let bits = |v: &[f32]| v.iter().map(|x| x.to_bits()).collect::>(); + for reach in [3, 9, 40] { + for out in [region, Rect::new(40, 30, 170, 120), Rect::new(-20, 200, 300, 290)] { + let [inside, outside] = bevel_fields(reach, &shape, region, out); + assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}"); + assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}"); + } + } + } + /// #3646: a stroke's outer edge is the fitted 5 × 5 chamfer while it is narrow and the exact /// Euclidean transform once it is wide — the chamfer's octagon facets a wide stroke. The GPU /// builds it from the field its width picks (`stroke_outside_exact`), while the spread of drop diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 8f8839b9bd..a90258b4b3 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -1814,19 +1814,28 @@ impl Compositor { layer.effects.items.iter().filter(|e| e.enabled()).map(|e| fx::program_with(e, &doc.global_light, vector_shape, &doc.patterns, anchor)).collect(); let want = field_reaches(&progs); e.fields.retain(|k, _| want.contains_key(k)); - for (&kind, &reach) in &want { + // Each field to recompute: over which rectangle, exact up to which reach. + let jobs: Vec<(FieldKind, Rect, i32)> = want + .iter() + .filter_map(|(&kind, &reach)| match e.fields.get(&kind).map(|(r, _)| *r) { + Some(r) if r >= reach => (!damage.is_empty()).then(|| (kind, damage.inflate(fx::field_radius(kind, r)).intersect(®ion), r)), + _ => Some((kind, region, reach)), + }) + .collect(); + // A chiselled bevel's two fields over the same rectangle share their window's sharp edges. + let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2)); + let mut bevel = match (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)) { + (Some((out, reach)), b) if b == Some((out, reach)) => fx::bevel_fields(reach, &e.shape_cpu, region, out).map(Some), + _ => [None, None], + }; + for (kind, out, reach) in jobs { let have = e.fields.get(&kind).map(|(r, _)| *r); - let out = match have { - Some(r) if r >= reach => { - if damage.is_empty() { - continue; - } - damage.inflate(fx::field_radius(kind, r)).intersect(®ion) - } - _ => region, + let pair = match kind { + FieldKind::BevelInside => bevel[0].take(), + FieldKind::BevelOutside => bevel[1].take(), + _ => None, }; - let reach = have.filter(|r| *r >= reach).unwrap_or(reach); - let v = fx::field(kind, reach, &e.shape_cpu, region, out); + let v = pair.unwrap_or_else(|| fx::field(kind, reach, &e.shape_cpu, region, out)); if have.is_none_or(|r| r < reach) { e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); } From 900968367138c6ffb00fb5ca0114bab684dc61b3 Mon Sep 17 00:00:00 2001 From: xsvm <2479667226@qq.com> Date: Wed, 14 Oct 2026 19:27:16 +0800 Subject: [PATCH 08/34] refactor(gpu): bevel fields are asked for, windowed and checked as one pair - the bevel program asks for both fields with B::bevel_fields, so they always come with the same reach; - field and bevel_fields share one windowing (fields_in_windows: one window, or bands on wasm), so wasm pairs them per band instead of taking a separate path; - compose's bevel_height and bevel_distance_fields share bevel_dists; - sync_fx recomputes the pair together and returns Unsupported when the two are not over the same rectangle at the same reach, instead of falling back to one at a time. Test: paired_bevel_fields_equal_the_fields_one_at_a_time also checks the banded path. --- crates/compose/src/effects.rs | 13 +++--- crates/gpu/src/fx.rs | 82 ++++++++++++++++++++++++----------- crates/gpu/src/lib.rs | 54 +++++++++++++---------- 3 files changed, 94 insertions(+), 55 deletions(-) diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs index d4f65dcb40..650651e963 100644 --- a/crates/compose/src/effects.rs +++ b/crates/compose/src/effects.rs @@ -1509,8 +1509,7 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, pattern tent(&mut h, g.width); h } else { - let sharp = sharp_edges(shape); - let (din, dout) = (bevel_dist_inside(shape, &sharp, size), bevel_dist_outside(shape, &sharp, size)); + let [din, dout] = bevel_dists(shape, size); let soft = g.chisel_soft > 0.0; let w = shape.w; let v = par_fill(w, shape.h, 0.0, |y, row| { @@ -2322,9 +2321,13 @@ pub fn distance_field(kind: FieldKind, alpha: Vec, w: usize, h: usize, reac /// Both chiselled bevel fields of `alpha`, `[BevelInside, BevelOutside]`: each is its /// [`distance_field`], with the sharp edges they both start from found once. pub fn bevel_distance_fields(alpha: Vec, w: usize, h: usize, reach: f32) -> [Vec; 2] { - let s = Map { w, h, v: alpha }; - let sharp = sharp_edges(&s); - [bevel_dist_inside(&s, &sharp, reach), bevel_dist_outside(&s, &sharp, reach)] + bevel_dists(&Map { w, h, v: alpha }, reach) +} + +/// The inside and outside bevel distances of `s`, from one set of sharp edges. +fn bevel_dists(s: &Map, reach: f32) -> [Vec; 2] { + let sharp = sharp_edges(s); + [bevel_dist_inside(s, &sharp, reach), bevel_dist_outside(s, &sharp, reach)] } #[cfg(test)] diff --git a/crates/gpu/src/fx.rs b/crates/gpu/src/fx.rs index 4b4ae5d575..35691c2114 100644 --- a/crates/gpu/src/fx.rs +++ b/crates/gpu/src/fx.rs @@ -203,6 +203,11 @@ impl B { self.fields.push((kind, reach_for(width))); In::Field(kind) } + /// A chiselled bevel's inside and outside fields, always asked for together ([`bevel_fields`] + /// computes them as one). + fn bevel_fields(&mut self, width: f32) -> [In; 2] { + [FieldKind::BevelInside, FieldKind::BevelOutside].map(|k| self.field(k, width)) + } /// `Map::shifted` by whole pixels (`invert`: of `1 - a`); identity shifts of the plain map /// are skipped. fn shift(&mut self, src: In, dx: f32, dy: f32, outside: f32, invert: bool) -> In { @@ -374,8 +379,7 @@ pub(crate) fn program_with(e: &Effect, light: &GlobalLight, vector_shape: bool, let mut h = if bv.technique == BevelTechnique::Smooth { b.conv(In::Shape, photocraft_compose::effects::tent_kernel(g.width)) } else { - let din = b.field(FieldKind::BevelInside, size); - let dout = b.field(FieldKind::BevelOutside, size); + let [din, dout] = b.bevel_fields(size); let soft = g.chisel_soft > 0.0; let h = b.push(stage(Kernel::MBevelH, Some(din), Some(dout), [paint(g.paint), size, f32::from(u8::from(soft)), 0.0], 0)); // As `effects::bevel_height`: only emboss styles blur a Chisel Soft ramp. @@ -542,35 +546,51 @@ fn threaded_inside(kind: FieldKind) -> bool { /// fields run on all threads inside `distance_field`, from one window. That is also the window the CPU /// compositor computes them from, so a rebuilt field is exactly the one it gives. fn field_banded(kind: FieldKind, reach: i32, shape: &[f32], region: Rect, out: Rect, halo: i32) -> Vec { - if threaded_inside(kind) { - let win = out.inflate(halo).intersect(®ion); - if win.is_empty() { - return Vec::new(); - } - let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32); - return if win == out { f } else { crop(&f, win, out) }; - } - let parts = par_map(bands(out, BAND.max(halo)), |band| { - let win = band.inflate(halo).intersect(®ion); - let f = photocraft_compose::effects::distance_field(kind, crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32); - crop(&f, win, band) + let [f] = fields_in_windows(threaded_inside(kind), shape, region, out, halo, |s, w, h| { + [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] }); - parts.concat() + f } -/// [`field`] of both bevel fields over the same `out`, `[BevelInside, BevelOutside]`: one window, -/// whose sharp edges are found once instead of once per field. +/// [`field`] of both bevel fields over the same `out`, `[BevelInside, BevelOutside]`, with the +/// sharp edges of each window found once (the two kinds have the same radius and threading). pub(crate) fn bevel_fields(reach: i32, shape: &[f32], region: Rect, out: Rect) -> [Vec; 2] { - let [inside, outside] = [FieldKind::BevelInside, FieldKind::BevelOutside]; - if !threaded_inside(inside) { - return [inside, outside].map(|k| field(k, reach, shape, region, out)); + let kind = FieldKind::BevelInside; + fields_in_windows(threaded_inside(kind), shape, region, out, field_radius(kind, reach) + 1, |s, w, h| { + photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32) + }) +} + +/// The fields `compute` gives for a `w × h` window of the region-sized `shape`, over `out` (inside +/// `region`), each window grown by `halo`: `out` as one window when `whole` (the field spreads over +/// threads itself), else bands of it in parallel. +fn fields_in_windows( + whole: bool, + shape: &[f32], + region: Rect, + out: Rect, + halo: i32, + compute: impl Fn(Vec, usize, usize) -> [Vec; N] + Sync + Send, +) -> [Vec; N] { + let part = |r: Rect| -> [Vec; N] { + let win = r.inflate(halo).intersect(®ion); + if win.is_empty() { + return std::array::from_fn(|_| Vec::new()); + } + let f = compute(crop(shape, region, win), win.width() as usize, win.height() as usize); + if win == r { f } else { f.map(|f| crop(&f, win, r)) } + }; + if whole { + return part(out); } - let win = out.inflate(field_radius(inside, reach) + 1).intersect(®ion); - if win.is_empty() { - return [Vec::new(), Vec::new()]; - } - let f = photocraft_compose::effects::bevel_distance_fields(crop(shape, region, win), win.width() as usize, win.height() as usize, reach as f32); - if win == out { f } else { f.map(|f| crop(&f, win, out)) } + let parts = par_map(bands(out, BAND.max(halo)), part); + std::array::from_fn(|k| { + let mut f = Vec::with_capacity(parts.iter().map(|p| p[k].len()).sum()); + for p in &parts { + f.extend_from_slice(&p[k]); + } + f + }) } /// The layer's shape (`compose::layer_shape`) over `r`, in parallel bands. @@ -877,6 +897,16 @@ mod tests { let [inside, outside] = bevel_fields(reach, &shape, region, out); assert_eq!(bits(&inside), bits(&field(FieldKind::BevelInside, reach, &shape, region, out)), "inside, reach {reach}, {out:?}"); assert_eq!(bits(&outside), bits(&field(FieldKind::BevelOutside, reach, &shape, region, out)), "outside, reach {reach}, {out:?}"); + // The banded path (wasm) pairs them per band the same way. + let halo = field_radius(FieldKind::BevelInside, reach) + 1; + let banded = + fields_in_windows(false, &shape, region, out, halo, |s, w, h| photocraft_compose::effects::bevel_distance_fields(s, w, h, reach as f32)); + for (k, kind) in [FieldKind::BevelInside, FieldKind::BevelOutside].into_iter().enumerate() { + let [one] = fields_in_windows(false, &shape, region, out, halo, |s, w, h| { + [photocraft_compose::effects::distance_field(kind, s, w, h, reach as f32)] + }); + assert_eq!(bits(&banded[k]), bits(&one), "banded {kind:?}, reach {reach}, {out:?}"); + } } } } diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index a90258b4b3..87e7963d71 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -1073,7 +1073,7 @@ impl Compositor { let aprons: Vec = plan.fx.iter().zip(&paged).map(|(f, &pg)| if pg { Self::fx_apron(doc, f) } else { 0 }).collect(); for (f, &pg) in plan.fx.iter().zip(&paged) { if !pg { - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats); + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, None), f.region, &mut stats)?; } } let fr = self.frame_res(device, queue, canvas, &plan); @@ -1104,7 +1104,7 @@ impl Compositor { continue; } let window = pf.inflate(aprons.get(i).copied().unwrap_or(0)).intersect(&f.region); - self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats); + self.sync_fx(device, queue, encoder, doc, f, (f.layer.id, Some(cell)), window, &mut stats)?; } let chunks = grid_rects(part, self.chunk); stats.chunks += chunks.len(); @@ -1715,7 +1715,7 @@ impl Compositor { key: FxKey, region: Rect, stats: &mut Stats, - ) { + ) -> Result<(), Unsupported> { let layer = f.layer; let canvas = doc.bounds(); let is_group = matches!(layer.content, LayerContent::Group(_)); @@ -1786,13 +1786,13 @@ impl Compositor { } // Present: kept or (re)inserted above. let stamp = self.stamp; - let Some(e) = self.fx.get_mut(&key) else { return }; + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; e.last_used = frame; e.stamp = stamp; e.doc = doc.id; e.tiles = [content_src.map(fx::snapshot), mask_src.map(fx::snapshot)]; if region.is_empty() { - return; + return Ok(()); } let t_trace = web_time_now(); @@ -1822,28 +1822,33 @@ impl Compositor { _ => Some((kind, region, reach)), }) .collect(); - // A chiselled bevel's two fields over the same rectangle share their window's sharp edges. + // A chiselled bevel's two fields are asked for and kept together (`fx::bevel_fields`), so they + // are recomputed together, over one rectangle at one reach. let job = |k: FieldKind| jobs.iter().find(|j| j.0 == k).map(|j| (j.1, j.2)); - let mut bevel = match (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)) { - (Some((out, reach)), b) if b == Some((out, reach)) => fx::bevel_fields(reach, &e.shape_cpu, region, out).map(Some), - _ => [None, None], - }; + let (bevel_in, bevel_out) = (job(FieldKind::BevelInside), job(FieldKind::BevelOutside)); + if bevel_in != bevel_out { + return Err(Unsupported(format!("bevel fields of `{}` out of step: inside {bevel_in:?}, outside {bevel_out:?}", layer.name))); + } for (kind, out, reach) in jobs { - let have = e.fields.get(&kind).map(|(r, _)| *r); - let pair = match kind { - FieldKind::BevelInside => bevel[0].take(), - FieldKind::BevelOutside => bevel[1].take(), - _ => None, + let fields = match kind { + FieldKind::BevelInside => { + let [inside, outside] = fx::bevel_fields(reach, &e.shape_cpu, region, out); + vec![(FieldKind::BevelInside, inside), (FieldKind::BevelOutside, outside)] + } + // Computed with BevelInside, over the same rectangle at the same reach (checked above). + FieldKind::BevelOutside => continue, + _ => vec![(kind, fx::field(kind, reach, &e.shape_cpu, region, out))], }; - let v = pair.unwrap_or_else(|| fx::field(kind, reach, &e.shape_cpu, region, out)); - if have.is_none_or(|r| r < reach) { - e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); + for (kind, v) in fields { + if e.fields.get(&kind).is_none_or(|(r, _)| *r < reach) { + e.fields.insert(kind, (reach, Tex::map(device, "pc_fx_field", region, MAP32))); + } + if let Some((_, t)) = e.fields.get(&kind) { + t.write_r32(queue, region, out, &v); + } + staged += v.len() as u64 * 4; + stats.fx_pixels += out.width() as u64 * out.height() as u64; } - if let Some((_, t)) = e.fields.get(&kind) { - t.write_r32(queue, region, out, &v); - } - staged += v.len() as u64 * 4; - stats.fx_pixels += out.width() as u64 * out.height() as u64; } if let Some(t) = t_trace.filter(|_| !damage.is_empty()) { @@ -1858,7 +1863,7 @@ impl Compositor { if prog.maps == 0 { continue; } - let Some(e) = self.fx.get_mut(&key) else { return }; + let Some(e) = self.fx.get_mut(&key) else { return Ok(()) }; let same = e.progs[i].key == prog.key && e.progs[i].maps.len() == prog.maps; let d = if same { damage } else { region }; if d.is_empty() { @@ -1873,6 +1878,7 @@ impl Compositor { stats.fx_programs += 1; self.run_program(device, queue, encoder, key, i, prog, d, stats); } + Ok(()) } /// Record the passes of `prog` (maps of item `item` of `layer`) recomputing damage `d`. From 6b3a6ffd8b224479ee634d5c150e00d3cc8e0387 Mon Sep 17 00:00:00 2001 From: jonathanwxh-cell Date: Thu, 15 Oct 2026 21:52:28 +0800 Subject: [PATCH 09/34] Document conservative blend preview coverage Explain why clip_damage replaces the covered intersection, including an empty one, while retaining the affected region for uncovered to recompute. This is a comment-only follow-up to review on storytold/photocraft#5413. Existing controlled 24 MP release measurement: median refresh/upload- submission time was 734.677 ms for the full 6000x4000 region and 59.641 ms for a 1280x720 viewport, five measured samples per region after warmup. This compares regions in the same candidate binary on CPU fallback with Vulkan llvmpipe, not two revisions or physical-GPU completion latency. Evidence: https://github.com/jonathanwxh-cell/photocraft/actions/runs/38512473874 --- crates/ui-egui/src/blend_preview.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/blend_preview.rs b/crates/ui-egui/src/blend_preview.rs index b73ddd553b..b5a203727d 100644 --- a/crates/ui-egui/src/blend_preview.rs +++ b/crates/ui-egui/src/blend_preview.rs @@ -91,6 +91,9 @@ pub(crate) fn clip_damage(app: &mut PhotocraftApp, doc: DocId, revision: u64, ke return region; } let shown = region.intersect(&visible); + // `covered` records only this refresh, including an empty intersection; it is not cumulative. + // Keep `region` so `uncovered` can recompute the next visible area. Forgetting older coverage + // can cause a redundant refresh, but cannot skip newly exposed pixels for this key. p.covered = Some((key, region, shown)); shown } From 7d42b5c838fd77003e8495c3690a7d70363183a2 Mon Sep 17 00:00:00 2001 From: ersoynarin-code Date: Thu, 15 Oct 2026 18:38:34 +0300 Subject: [PATCH 10/34] fix(perf): validate regression minimum threshold --- xtask/src/perf.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/xtask/src/perf.rs b/xtask/src/perf.rs index d2a3a75b85..3e49514c1c 100644 --- a/xtask/src/perf.rs +++ b/xtask/src/perf.rs @@ -168,6 +168,9 @@ pub fn parse_budgets(text: &str) -> Result { if !(b.settings.regression_pct.is_finite() && b.settings.regression_pct > 0.0) { return Err(format!("{BUDGETS}: settings.regression_pct must be > 0")); } + if !(b.settings.regression_min_ms.is_finite() && b.settings.regression_min_ms >= 0.0) { + return Err(format!("{BUDGETS}: settings.regression_min_ms must be finite and >= 0")); + } Ok(b) } @@ -980,6 +983,8 @@ not_measurable = "needs a frame harness" .is_err() ); assert!(parse_budgets("[settings]\nregression_pct = 0\n").is_err()); + assert!(parse_budgets("[settings]\nregression_min_ms = -1\n").is_err()); + assert!(parse_budgets("[settings]\nregression_min_ms = 0\n").is_ok()); assert!(parse_budgets("bogus = 1\n").is_err()); assert!(parse_budgets("not toml [").is_err()); } From f22d08da8c55dee9885f83e6ace2756fd358045d Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Fri, 16 Oct 2026 09:32:47 +0800 Subject: [PATCH 11/34] style: apply rustfmt to upstream smart-filter regression --- crates/automation/tests/smart_filter_authorization.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/crates/automation/tests/smart_filter_authorization.rs b/crates/automation/tests/smart_filter_authorization.rs index a5c1681a52..30f17b795b 100644 --- a/crates/automation/tests/smart_filter_authorization.rs +++ b/crates/automation/tests/smart_filter_authorization.rs @@ -230,11 +230,9 @@ fn a_refresh_outside_command_execution_surfaces_the_denial_instead_of_rendering_ let before = h.session.active().unwrap().doc.clone(); // Session::edit is the outside-execute mutation path (an edit closure the UI or a // linked-file change runs); the stored filter must be denied there too. - assert_denied(h.session.edit("Re-render", |d, _| { - match smart_cmds::refresh(d, layer) { - Ok(_) => Ok(()), - Err(e) => Err(e), - } + assert_denied(h.session.edit("Re-render", |d, _| match smart_cmds::refresh(d, layer) { + Ok(_) => Ok(()), + Err(e) => Err(e), })); assert!(Arc::ptr_eq(&before, &h.session.active().unwrap().doc)); // A trusted session (no gate) still renders the same document. From 4354113e730dc1c2c83fd02dede69ebf222be877 Mon Sep 17 00:00:00 2001 From: nanopink Date: Fri, 16 Oct 2026 16:23:53 -0400 Subject: [PATCH 12/34] fix: match Photoshop Gradient Fill scale limits --- crates/engine/src/gradient_fill_cmds.rs | 9 +++--- crates/engine/src/gradient_fill_cmds/tests.rs | 28 ++++++++++--------- crates/engine/src/presets/gradients.rs | 4 +-- .../src/gradient_ui/properties_panel.rs | 3 +- 4 files changed, 24 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rs index 041d311691..356d2252db 100644 --- a/crates/engine/src/gradient_fill_cmds.rs +++ b/crates/engine/src/gradient_fill_cmds.rs @@ -28,9 +28,10 @@ pub const GET: &str = "gradient.fill.get"; /// Largest coordinate accepted for a start/end point (pixels). const MAX_COORD: f32 = 1.0e7; -/// Scale range of a gradient fill (a fraction): Photoshop allows 10–150 % (the PSD stores a -/// percentage). A handle drag past it clamps, so the far handle stops where the scale does. -const SCALE_RANGE: (f32, f32) = (0.1, 1.5); + +/// Scale range of a Gradient Fill layer (a fraction): Photoshop allows 1–1000 %. +/// Gradient Overlay effects have a separate range; the live tool creates fill layers. +pub const SCALE_RANGE: (f32, f32) = (0.01, 10.0); fn bad(cmd: &str, msg: impl Into) -> EngineError { EngineError::BadParams { cmd: cmd.into(), msg: msg.into() } @@ -149,7 +150,7 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } -fn clamp_scale(v: f32) -> f32 { +pub(crate) fn clamp_scale(v: f32) -> f32 { v.clamp(SCALE_RANGE.0, SCALE_RANGE.1) } diff --git a/crates/engine/src/gradient_fill_cmds/tests.rs b/crates/engine/src/gradient_fill_cmds/tests.rs index efcdb494d9..3c0c2f3c6a 100644 --- a/crates/engine/src/gradient_fill_cmds/tests.rs +++ b/crates/engine/src/gradient_fill_cmds/tests.rs @@ -27,7 +27,7 @@ fn create_makes_a_canvas_aligned_fill_layer_with_the_drag_as_handles() { let r = s .execute( CREATE, - json!({"from": [14, 16], "to": [34, 8], "style": "radial", "stops": [[0, "#ff0000"], [1, "#0000ff"]], "opacity": 50, "mode": "multiply"}), + json!({"from": [14, 16], "to": [200, -40], "style": "radial", "stops": [[0, "#ff0000"], [1, "#0000ff"]], "opacity": 50, "mode": "multiply"}), ) .unwrap(); assert_eq!(layer_count(&s), 2); @@ -42,7 +42,7 @@ fn create_makes_a_canvas_aligned_fill_layer_with_the_drag_as_handles() { assert!(!align && dither); let g = s.execute(GET, json!({})).unwrap(); let (from, to) = (g["from"].as_array().unwrap(), g["to"].as_array().unwrap()); - for (v, want) in from.iter().chain(to).zip([14.0, 16.0, 34.0, 8.0]) { + for (v, want) in from.iter().chain(to).zip([14.0, 16.0, 200.0, -40.0]) { assert!((v.as_f64().unwrap() - want).abs() < 1e-3, "{g}"); } // One undo step removes the layer. @@ -225,11 +225,11 @@ fn stops_add_move_recolour_delete_and_midpoints() { #[test] fn preview_equals_the_committed_edit() { let mut s = session(8, "white"); - s.execute(CREATE, json!({"from": [4, 4], "to": [40, 20], "style": "diamond"})).unwrap(); + s.execute(CREATE, json!({"from": [4, 4], "to": [40, 20], "style": "radial"})).unwrap(); let d = s.active().unwrap(); let l = d.doc.layer(d.active_layer.unwrap()).unwrap().clone(); let LayerContent::Fill(f) = &l.content else { panic!() }; - let p = json!({"from": [10, 12], "to": [30, 2]}); + let p = json!({"from": [10, 12], "to": [150, -80]}); let preview = apply_set(&l, f, d.doc.bounds(), &p, [0.0; 4], [1.0; 4]).unwrap(); s.execute(SET, p).unwrap(); assert_eq!(active_fill(&s), preview); @@ -316,12 +316,12 @@ fn commands_fail_gracefully() { s.execute(SET, json!({"scale": 1e30, "angle": 1e9, "offset": [1e4, -1e4]})).unwrap(); let g = s.execute(GET, json!({})).unwrap(); assert!(g["scale"].as_f64().unwrap().is_finite() && g["from"][0].as_f64().unwrap().is_finite()); - // Scale stays within Photoshop's 10–150 %, also for a handle dragged far away. - assert!((g["scale"].as_f64().unwrap() - 150.0).abs() < 1e-3, "{g}"); + // Fill layers use Photoshop's 1–1000 %, also for a handle dragged far away. + assert!((g["scale"].as_f64().unwrap() - 1000.0).abs() < 1e-3, "{g}"); let g = s.execute(SET, json!({"from": [0, 0], "to": [1e6, 0]})).unwrap(); - assert!((g["scale"].as_f64().unwrap() - 150.0).abs() < 1e-3, "{g}"); - let g = s.execute(SET, json!({"scale": 1})).unwrap(); - assert!((g["scale"].as_f64().unwrap() - 10.0).abs() < 1e-3, "{g}"); + assert!((g["scale"].as_f64().unwrap() - 1000.0).abs() < 1e-3, "{g}"); + let g = s.execute(SET, json!({"scale": 0.1})).unwrap(); + assert!((g["scale"].as_f64().unwrap() - 1.0).abs() < 1e-3, "{g}"); } /// Dragging one handle past the scale range stops it; the other handle stays put (#1243). @@ -332,17 +332,19 @@ fn a_clamped_handle_drag_leaves_the_other_handle_alone() { for style in STYLES { for (from, to, short, short_start) in [([14.0, 16.0], [34.0, 16.0], [15.0, 16.0], [33.0, 16.0]), ([24.0, 6.0], [24.0, 26.0], [24.0, 7.0], [24.0, 25.0])] { - let mut s = session(8, "white"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 480, "height": 320})).unwrap(); s.execute(CREATE, json!({"from": from, "to": to, "style": style})).unwrap(); - // End dragged almost onto the start: far below 10 %. + // End dragged almost onto the start: below 1 % on this larger canvas. let g = s.execute(SET, json!({"to": short})).unwrap(); - assert!((g["scale"].as_f64().unwrap() - 10.0).abs() < 1e-3, "{style}: {g}"); + assert!((g["scale"].as_f64().unwrap() - 1.0).abs() < 1e-3, "{style}: {g}"); assert!(close(pt(&g, "from"), from), "{style}: start moved to {:?}", pt(&g, "from")); // The end stops on the line towards the pointer. let e = pt(&g, "to"); assert!((e[0] - from[0]) * (short[0] - from[0]) >= 0.0 && (e[1] - from[1]) * (short[1] - from[1]) >= 0.0, "{style}: {e:?}"); // And the same for the start handle. - let mut s = session(8, "white"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 480, "height": 320})).unwrap(); s.execute(CREATE, json!({"from": from, "to": to, "style": style})).unwrap(); let g = s.execute(SET, json!({"from": short_start})).unwrap(); assert!(close(pt(&g, "to"), to), "{style}: end moved: {g}"); diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs index 7c92dfba97..2a700aad99 100644 --- a/crates/engine/src/presets/gradients.rs +++ b/crates/engine/src/presets/gradients.rs @@ -604,7 +604,7 @@ fn apply(s: &mut Session, p: &Value) -> Result { let g = preset_param(s, p, CMD)?; let stops = g.doc_stops(s.tools.foreground, s.tools.background); let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(90.0) as f32; - let scale = (p.get("scale").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0).clamp(0.1, 1.5); + let scale = crate::gradient_fill_cmds::clamp_scale(p.get("scale").and_then(Value::as_f64).unwrap_or(100.0) as f32 / 100.0); let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear")); let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false); let id = s.edit("New Gradient Fill Layer", |doc, active| { @@ -696,7 +696,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: leak(format!( - r##"{{"preset":name?=current|{stops},"angle":deg=90,"style":"linear|radial|angle|reflected|diamond"="linear","scale":10..150=100,"reverse":bool}} → {{layer}}"## + r##"{{"preset":name?=current|{stops},"angle":deg=90,"style":"linear|radial|angle|reflected|diamond"="linear","scale":1..1000=100,"reverse":bool}} → {{layer}}"## )), enabled: super::has_doc, run: apply, diff --git a/crates/ui-egui/src/gradient_ui/properties_panel.rs b/crates/ui-egui/src/gradient_ui/properties_panel.rs index 39b961ee20..d975102539 100644 --- a/crates/ui-egui/src/gradient_ui/properties_panel.rs +++ b/crates/ui-egui/src/gradient_ui/properties_panel.rs @@ -49,7 +49,8 @@ fn options(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) { if let Some(value) = numeric_row(ui, "angle", "Angle", angle, -180.0..=180.0, "°") { let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "angle": value})); } - if let Some(value) = numeric_row(ui, "scale", "Scale", scale * 100.0, 10.0..=150.0, "%") { + let (min, max) = cmds::SCALE_RANGE; + if let Some(value) = numeric_row(ui, "scale", "Scale", scale * 100.0, min * 100.0..=max * 100.0, "%") { let _ = app.run(cmds::SET, json!({"layer": layer.id.0, "scale": value})); } ui.horizontal_wrapped(|ui| { From dd57638d9ecd6c88edfcfcd8d07af7f2f21960fc Mon Sep 17 00:00:00 2001 From: Finn Newick Date: Sat, 17 Oct 2026 10:11:57 +0100 Subject: [PATCH 13/34] fix(psd): make packbits::decode_into crate-private and overflow-safe decode_into computed out.len() + expected unchecked. With a non-empty buffer and an expected length near usize::MAX it panicked in debug builds and, in release, wrapped and returned Ok having decoded nothing. Compute the target with checked_add and report LimitExceeded, and test each packet as len > target - out.len() so the bound checks cannot overflow either. The only callers are decode and decode_rle in this module, and the crate README documents packbits::{encode, decode} as the public API, so decode_into becomes pub(crate). Co-Authored-By: Claude Opus 5.5 --- crates/psd/src/compression.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/psd/src/compression.rs b/crates/psd/src/compression.rs index aab785dff4..68782464ad 100644 --- a/crates/psd/src/compression.rs +++ b/crates/psd/src/compression.rs @@ -111,9 +111,10 @@ pub mod packbits { /// /// Errors if the input is exhausted early or a packet would overflow the /// row. Trailing input after the row is complete is ignored except for - /// `-128` no-op bytes (which are always permitted). - pub fn decode_into(src: &[u8], expected: usize, out: &mut Vec) -> Result<()> { - let target = out.len() + expected; + /// `-128` no-op bytes (which are always permitted). Errors, rather than + /// overflowing, when `out.len() + expected` does not fit in `usize`. + pub(crate) fn decode_into(src: &[u8], expected: usize, out: &mut Vec) -> Result<()> { + let target = out.len().checked_add(expected).ok_or(PsdError::LimitExceeded("PackBits output length overflows usize"))?; let mut i = 0; while out.len() < target { let Some(&h) = src.get(i) else { @@ -126,7 +127,7 @@ pub mod packbits { let Some(lit) = src.get(i..i + len) else { return Err(PsdError::Decompress("PackBits literal truncated".into())); }; - if out.len() + len > target { + if len > target - out.len() { return Err(PsdError::Decompress("PackBits literal overflows row".into())); } out.extend_from_slice(lit); @@ -138,7 +139,7 @@ pub mod packbits { return Err(PsdError::Decompress("PackBits run truncated".into())); }; i += 1; - if out.len() + len > target { + if len > target - out.len() { return Err(PsdError::Decompress("PackBits run overflows row".into())); } out.extend(std::iter::repeat_n(b, len)); @@ -687,6 +688,20 @@ mod tests { assert!(packbits::decode(&[3, 1, 2, 3, 4], 3).is_err()); // literal overflows } + /// `out.len() + expected` past `usize::MAX` used to panic in debug builds and, in release, + /// wrap and return `Ok` having decoded nothing. + #[test] + fn packbits_decode_into_output_length_overflow_is_an_error() { + let mut out = vec![7u8]; + let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX, &mut out); + assert!(matches!(r, Err(PsdError::LimitExceeded(_))), "{r:?}"); + assert_eq!(out, [7]); + // The largest `expected` that fits still decodes up to the input, then reports it short. + let r = packbits::decode_into(&[0x00, 0xaa], usize::MAX - 1, &mut out); + assert!(matches!(r, Err(PsdError::Decompress(_))), "{r:?}"); + assert_eq!(out, [7, 0xaa]); + } + #[test] fn packbits_zero_expected_ignores_input() { assert_eq!(packbits::decode(&[0xff, 1], 0).unwrap(), Vec::::new()); From fcd337e1fc7bd0a154c05e859a1395c3450f99f8 Mon Sep 17 00:00:00 2001 From: ebosido444-ai <316167330+ebosido444-ai@users.noreply.github.com> Date: Sat, 17 Oct 2026 15:57:51 +0300 Subject: [PATCH 14/34] perf(text): rasterize a type layer's pixels on all cores, bit for bit the same A type render spends most of its time after the glyphs are drawn: composing each colour's coverage over the premultiplied accumulator, dividing it back to straight colour, and converting the tile bytes. All three are per pixel - no pixel reads a slot another wrote - so they ran one after another on one core for no reason. Measured on a 3.75 MP paragraph (4000 characters, 14 pt at 300 dpi, 1851 glyphs), release, Windows 11, i5-10300H: rasterize 98.3-103.9 ms before, 60.3-61.8 ms after (1.6-1.7x). Whole-render stage profile before: ink rect 4.1, draw 18.6-22.9, prefix sum 7.0-8.1, composite 22.6-33.4, unpremultiply 11.2-14.0, write_region 23.8, prune 3.1 ms. The glyph drawing, the winding prefix sum and the ink-rect pass stay on one thread: the first two carry a running accumulator across pixels, and the band split that would keep them bit-identical costs a second glyph traversal per band. Native only (rayon, as the other crates): the web build keeps the serial loops. --- Cargo.lock | 2 + crates/raster/Cargo.toml | 4 ++ crates/raster/src/lib.rs | 88 +++++++++++++++++++++------------ crates/text/Cargo.toml | 2 + crates/text/src/render.rs | 47 +++++++++++++----- crates/text/src/tests.rs | 34 ++++++++++++- docs/text-raster-performance.md | 60 ++++++++++++++++++++++ 7 files changed, 193 insertions(+), 44 deletions(-) create mode 100644 docs/text-raster-performance.md diff --git a/Cargo.lock b/Cargo.lock index 0167dea3b1..b0afa75133 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4944,6 +4944,7 @@ dependencies = [ "photocraft-color", "photocraft-geom", "proptest", + "rayon", "serde", ] @@ -4996,6 +4997,7 @@ dependencies = [ "photocraft-geom", "photocraft-psd", "photocraft-raster", + "rayon", "skrifa", ] diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index 956d1c9545..41b188a94f 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -12,5 +12,9 @@ photocraft-geom = { workspace = true } photocraft-color = { workspace = true } serde = { workspace = true } +# Native only: converting a region's tiles is independent per tile, so it runs on all cores. +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rayon = { workspace = true } + [dev-dependencies] proptest = { workspace = true } diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 20b809764a..883c244aa5 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -166,6 +166,55 @@ impl PartialEq for Surface { } } +/// Converts the `data` span covering one tile into that tile's bytes. +fn write_tile(t: &mut Tile, tc: TileCoord, r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) { + let tr = tc.rect().intersect(&r); + // Convert contiguous channel samples a row at a time. Dispatching on depth here removes the + // per-pixel channel loop and lets the compiler vectorise conversion. + let span = tr.width() as usize * n; + for y in tr.y0..tr.y1 { + let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; + let src = &data[o..o + span]; + let bytes = sample.bytes(); + let dst = &mut t.data[base * bytes..(base + span) * bytes]; + match sample { + SampleType::U8 => { + for (d, v) in dst.iter_mut().zip(src) { + *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + } + } + SampleType::U16 => { + for (d, v) in dst.as_chunks_mut::<2>().0.iter_mut().zip(src) { + let q = (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; + d.copy_from_slice(&q.to_ne_bytes()); + } + } + SampleType::F32 => { + for (d, v) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) { + d.copy_from_slice(&v.to_ne_bytes()); + } + } + } + } +} + +/// Converts the tiles of a region write. A tile holds no state another tile reads, so the tiles +/// are converted on all cores; each writes only its own bytes, in the same arithmetic. +#[cfg(not(target_arch = "wasm32"))] +fn convert_tiles(tiles: &mut [(TileCoord, Arc)], r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) { + use rayon::prelude::*; + tiles.par_iter_mut().for_each(|(tc, t)| write_tile(Arc::make_mut(t), *tc, r, data, w, n, sample)); +} + +/// Serial counterpart, for the web build (there are no threads to spread tiles over). +#[cfg(target_arch = "wasm32")] +fn convert_tiles(tiles: &mut [(TileCoord, Arc)], r: Rect, data: &[f32], w: usize, n: usize, sample: SampleType) { + for (tc, t) in tiles.iter_mut() { + write_tile(Arc::make_mut(t), *tc, r, data, w, n, sample); + } +} + impl Surface { /// Reads a region into a newly allocated buffer, returning an error instead of aborting if /// the requested pixel buffer cannot be represented or reserved. @@ -579,38 +628,13 @@ impl Surface { let w = r.width() as usize; assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); let sample = self.format.sample; - for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let t = self.tile_mut(tc); - // Convert contiguous channel samples a row at a time. Dispatching on depth here - // removes the per-pixel channel loop and lets the compiler vectorise conversion. - let span = tr.width() as usize * n; - for y in tr.y0..tr.y1 { - let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; - let src = &data[o..o + span]; - let bytes = sample.bytes(); - let dst = &mut t.data[base * bytes..(base + span) * bytes]; - match sample { - SampleType::U8 => { - for (d, v) in dst.iter_mut().zip(src) { - *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - } - } - SampleType::U16 => { - for (d, v) in dst.as_chunks_mut::<2>().0.iter_mut().zip(src) { - let q = (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16; - d.copy_from_slice(&q.to_ne_bytes()); - } - } - SampleType::F32 => { - for (d, v) in dst.as_chunks_mut::<4>().0.iter_mut().zip(src) { - d.copy_from_slice(&v.to_ne_bytes()); - } - } - } - } - } + // Each tile's own span of `data` is converted on its own: the tiles are disjoint, so + // converting them in any order (and on any thread) writes exactly the same bytes. + // `take_tiles` reserves the whole result before removing anything, and gives the missing + // tiles as one shared default-filled tile, copied per tile by `Arc::make_mut` below. + let mut tiles = self.take_tiles(r); + convert_tiles(&mut tiles, r, data, w, n, sample); + self.put_tiles(tiles); } /// Take the tiles covering `r` out of the surface (missing ones filled with the default diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index 985f627e90..0c251d1639 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -25,8 +25,10 @@ flate2 = { workspace = true } # line breaking. Native only: the CJK dictionary alone is 3.8 MB of wasm, and the web build must # stay under Cloudflare's 25 MiB per-file cap (packaging/web/package.sh). The web build falls back # to the generic Unicode rules for those scripts. +# Native only: the glyph rasteriser composites and converts its pixel buffers on all cores. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] parley = { version = "0.11", default-features = false, features = ["std", "complex-scripts"] } +rayon = { workspace = true } [build-dependencies] # Deflates the bundled fonts (build.rs); `flate2` above inflates them. diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index af29dd10d6..5cf6baea12 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -12,6 +12,9 @@ use crate::layout::{GlyphOrient, PlacedGlyph, TextLayout}; use crate::raster::{Bounds, Coverage, LineSink, Pen, Xform, rect_to}; use crate::warp::{Placement, Warp}; +#[cfg(not(target_arch = "wasm32"))] +use rayon::prelude::*; + /// Faux-italic slant in degrees (Photoshop-like). pub const FAUX_ITALIC_DEG: f32 = 12.0; /// Faux-bold ring radius as a fraction of the font size (tuned so stem weight stays close to the old summed-coverage look). @@ -276,35 +279,57 @@ pub fn rasterize_warped(layout: &TextLayout, transform: &Affine, format: PixelFo } let comps = color_in(&format, c); let a = c.alpha.clamp(0.0, 1.0); - for (i, &cv) in cov.iter().enumerate() { - let cv = if antialias == AntiAlias::None { if cv >= 0.5 { 1.0 } else { 0.0 } } else { cv }; + composite(&mut acc, &cov, w, stride, &comps, a, antialias); + } + // Unpremultiply. + unpremultiply(&mut acc, n, stride, format.sample); + surface.write_region(rect, &acc); + surface.prune(); + Rendered { surface, rect } +} + +/// Composites one colour's coverage over the premultiplied accumulator, resolving `AntiAlias::None` +/// to 0/1 first. A pixel's maths reads and writes only its own slots, so the rows are done in any +/// order — one per thread — for exactly the same bytes. +fn composite(acc: &mut [f32], cov: &[f32], width: usize, stride: usize, comps: &[f32], a: f32, antialias: AntiAlias) { + let n = comps.len(); + let row = |acc: &mut [f32], cov: &[f32]| { + for (cv, px) in cov.iter().zip(acc.chunks_exact_mut(stride)) { + let cv = if antialias == AntiAlias::None { if *cv >= 0.5 { 1.0 } else { 0.0 } } else { *cv }; let s = cv * a; if s <= 0.0 { continue; } - let px = &mut acc[i * stride..(i + 1) * stride]; let keep = 1.0 - s; for j in 0..n { px[j] = comps[j] * s + px[j] * keep; } px[n] = s + px[n] * keep; } - } - // Unpremultiply. - for px in acc.chunks_exact_mut(stride) { + }; + #[cfg(not(target_arch = "wasm32"))] + acc.par_chunks_mut(width * stride).zip(cov.par_chunks(width)).for_each(|(a, c)| row(a, c)); + #[cfg(target_arch = "wasm32")] + acc.chunks_mut(width * stride).zip(cov.chunks(width)).for_each(|(a, c)| row(a, c)); +} + +/// Divides the premultiplied accumulator back to straight colour. Each pixel stands alone. +fn unpremultiply(acc: &mut [f32], n: usize, stride: usize, sample: SampleType) { + let one = |px: &mut [f32]| { let a = px[n]; if a > 0.0 { for v in &mut px[..n] { let straight = *v / a; // Float text can carry HDR and signed colours. Keep integer output bounded // and retain the old handling of non-finite intermediate values. - *v = if format.sample == SampleType::F32 && straight.is_finite() { straight } else { straight.clamp(0.0, 1.0) }; + *v = if sample == SampleType::F32 && straight.is_finite() { straight } else { straight.clamp(0.0, 1.0) }; } } - } - surface.write_region(rect, &acc); - surface.prune(); - Rendered { surface, rect } + }; + #[cfg(not(target_arch = "wasm32"))] + acc.par_chunks_exact_mut(stride).for_each(one); + #[cfg(target_arch = "wasm32")] + acc.chunks_exact_mut(stride).for_each(one); } /// One element of a glyph outline in document space (see [`outlines`]). diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 894ecf4e4f..c055e1881d 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -1,6 +1,6 @@ use photocraft_color::{Color, PixelFormat, SampleType}; use photocraft_doc::TextLayer; -use photocraft_doc::text::{Caps, CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape}; +use photocraft_doc::text::{AntiAlias, Caps, CharStyle, FontFeature, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape}; use photocraft_geom::Affine; use crate::{TextEngine, fonts}; @@ -13,6 +13,38 @@ fn styled(text: &str, style: CharStyle) -> TextLayer { TextLayer { text: text.into(), runs: vec![TextRun { len: text.len(), style }], ..Default::default() } } +/// The rasteriser's pixel stages — composing one colour's coverage, unpremultiplying it, and +/// converting the tiles — are per pixel: no pixel reads a slot another pixel wrote. Spreading them +/// over threads therefore has to leave every byte as it was, which a one-thread pool checks. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn parallel_raster_matches_a_single_thread() { + let one = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("one-thread pool"); + let mut e = TextEngine::new(); + let boxed = TextShape::Box { x: 0.0, y: 0.0, width: 220.0, height: 90.0 }; + let paragraph = TextLayer { + text: "A paragraph box that wraps over several lines and covers many tiles, so the whole raster is exercised.".into(), + font_family: "Inter".into(), + size_pt: 18.0, + shape: boxed, + ..Default::default() + }; + let no_aa = TextLayer { text: "No AA edge".into(), font_family: "Inter".into(), size_pt: 30.0, antialias: AntiAlias::None, ..Default::default() }; + let cases: Vec<(TextLayer, f32, PixelFormat)> = vec![ + (point("Parallel", 48.0), 72.0, PixelFormat::RGBA8), + (styled("Bold italic", CharStyle { size_pt: 40.0, faux_bold: true, faux_italic: true, ..Default::default() }), 300.0, PixelFormat::RGBA8), + (no_aa, 150.0, PixelFormat::RGBA16), + (styled("Wide gamut", CharStyle { size_pt: 36.0, color: Color::rgba(2.5, -0.25, 0.5, 0.4), ..Default::default() }), 96.0, PixelFormat::RGBA32F), + (with_para(paragraph, ParagraphStyle::default()), 144.0, PixelFormat::RGBA8), + ]; + for (layer, dpi, format) in cases { + let (_, spread) = e.render(&layer, dpi, format); + let (_, single) = one.install(|| e.render(&layer, dpi, format)); + assert_eq!(spread.rect, single.rect, "{}", layer.text); + assert_eq!(spread.surface, single.surface, "{}", layer.text); + } +} + #[test] fn raster_preserves_hdr_and_signed_float_text_colors() { let mut e = TextEngine::new(); diff --git a/docs/text-raster-performance.md b/docs/text-raster-performance.md new file mode 100644 index 0000000000..87ccdf849f --- /dev/null +++ b/docs/text-raster-performance.md @@ -0,0 +1,60 @@ +# Text rasterization: what a type render costs + +Measured 2026-10-17 on Windows 11, `i5-10300H` (4 cores / 8 threads, 16 GB), release build, +`rustc 1.98.1`, with a probe that renders one paragraph layer through +`photocraft_text::render::rasterize_warped` and times each stage of it. + +Document: 300 dpi, a 2400 × 1600 px paragraph box holding 4000 characters at 14 pt — the worst +case a type edit has (a whole page of text at print resolution; 1851 laid-out glyphs, 2329 × 1610 px +of ink = 3.75 MP). + +| Stage | ms | What it does | +|---|---:|---| +| ink rectangle (`ink_rect_warped`) | 4.1 | its own pass over every glyph, to size the surface | +| draw (`draw_pass` into `Coverage`) | 18.6–22.9 | glyph outlines, curve flattening (0.03 px tolerance), winding scanlines | +| prefix sum (`Coverage::finish`) | 7.0–8.1 | resolves the winding accumulator to coverage 0…1, one running sum over 3.75 M pixels | +| composite | 22.6–33.4 | each colour's coverage over the premultiplied accumulator | +| unpremultiply | 11.2–14.0 | divides the accumulator back to straight colour | +| `Surface::write_region` | 23.8 | converts to the document format and fills the tiles | +| `Surface::prune` | 3.1 | drops tiles that came back the layer's default | +| **total** | **86–104** | | + +So the glyph geometry — what one would expect to dominate — is under a quarter of it. The rest is +scalar work over the pixel buffers, and every one of those passes is per pixel: a pixel's maths +reads and writes only its own slots. + +## What runs in parallel now + +`composite`, `unpremultiply` and the tile conversion of `write_region` run on all cores (rayon, +native only; the web build keeps the serial loops, since wasm has no threads). Nothing about them +is order-dependent, so each pixel still sees the same operations on the same inputs — the pixels +are identical, not merely close. + +| | before | after | +|---|---:|---:| +| the 3.75 MP case above | 98.3–103.9 ms | 60.3–61.8 ms | + +`crates/text/src/tests.rs::parallel_raster_matches_a_single_thread` renders the shapes the pipeline +can take (plain, faux bold italic, no antialias, wide gamut, a wrapping paragraph box; 8/16/32-bit) +on a one-thread pool and on the default pool and compares the surfaces; `crates/raster`'s existing +region proptests compare `write_region` against its serial reference implementation, tile for tile. + +## What stays on one thread, and why + +- **draw** (19–23 ms): the winding accumulator carries across scanlines and rows — a pixel's value + depends on the rows above it, and one scanline can spill into the next row's first pixel. A band + split can be exact (bands keep absolute coordinates, carry the spill in band order, and are + assembled before the prefix sum), but each band re-traverses every glyph — the traversal is not + free, so the win is bounded by the band count. Worth doing when the draw matters more than it does + now. +- **prefix sum** (7–8 ms): a running f32 sum over the whole image. Splitting it per row needs the + row's starting sum, which is that same sequential chain — the only exactly-known starting sums are + the ones the chain computes. +- **ink rectangle** (4.1 ms): a second full traversal into a bounds sink. Per-glyph bounds reduce by + min/max, which is associative and exact, so this is a candidate for the same treatment as the + stages above (a glyph-range split, not a band split). + +## Related + +Byte-identical output matters here beyond taste: text pixels reach a PSD's saved cache and the +round-trip corpora. `cargo xtask test-corpus` and the Photoshop oracle tests are the gate. From 18f8d33577f5648e03934c1c9ce421ea3d7c872f Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 18 Oct 2026 11:00:42 -0400 Subject: [PATCH 15/34] docs: add SonarCloud and CodeRabbit badges to README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 12e2ef4b12..1e85aca5b0 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,8 @@ macOS · Windows · Linux · FreeBSD · Web License: MIT OR Apache-2.0 Status: early alpha + Scanned by SonarCloud + Reviewed by CodeRabbit

From 050c8ebed8530010fd475bdf9a8f99eb47b32c73 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 18 Oct 2026 14:47:45 -0400 Subject: [PATCH 16/34] docs: put SonarCloud and CodeRabbit badges on their own line --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1e85aca5b0..7554fcd8f2 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ macOS · Windows · Linux · FreeBSD · Web License: MIT OR Apache-2.0 Status: early alpha +
Scanned by SonarCloud Reviewed by CodeRabbit

From 49d48fc43c4fa0ab20544c52b7dc665f414b6529 Mon Sep 17 00:00:00 2001 From: jonathnwxh <258340642+jonathanwxh-cell@users.noreply.github.com> Date: Mon, 19 Oct 2026 16:11:51 +0800 Subject: [PATCH 17/34] Fix blend preview coverage for periodic tiles and multiple views --- crates/ui-egui/src/blend_preview.rs | 27 +++++++----- crates/ui-egui/src/blend_preview/tests.rs | 34 ++++++++++++++ crates/ui-egui/src/canvas.rs | 7 ++- .../src/canvas/blend_viewport_tests.rs | 44 +++++++++++++++++++ 4 files changed, 99 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/blend_preview.rs b/crates/ui-egui/src/blend_preview.rs index fb8b6f3177..06e7a208e1 100644 --- a/crates/ui-egui/src/blend_preview.rs +++ b/crates/ui-egui/src/blend_preview.rs @@ -29,8 +29,8 @@ pub(crate) struct BlendPreview { area: Option, /// The document shown for `mode`, with its key. shown: Option<(u64, Arc)>, - /// GPU preview key, affected region (including effects), and the area last refreshed. - covered: Option<(u64, Rect, Rect)>, + /// GPU preview key, affected region (including effects), and rectangles already refreshed. + covered: Option<(u64, Rect, Vec)>, } /// The Layers panel, each frame it draws `layer`'s blend-mode dropdown: the mode under the @@ -106,26 +106,31 @@ pub(crate) fn clip_damage(app: &mut PhotocraftApp, doc: DocId, revision: u64, ke return region; } let shown = region.intersect(&visible); - // `covered` records only this refresh, including an empty intersection; it is not cumulative. - // Keep `region` so `uncovered` can recompute the next visible area. Forgetting older coverage - // can cause a redundant refresh, but cannot skip newly exposed pixels for this key. - p.covered = Some((key, region, shown)); + p.covered = Some((key, region, vec![shown])); shown } /// A pan or zoom can expose pixels not yet rendered for the current preview key. pub(crate) fn uncovered(app: &mut PhotocraftApp, doc: DocId, revision: u64, key: u64, visible: Rect) -> Option { let p = app.blend_preview.as_mut().filter(|p| p.doc == doc && p.revision == revision)?; - let (covered_key, region, covered) = p.covered?; - if covered_key != key { + let (covered_key, region, covered) = p.covered.as_mut()?; + if *covered_key != key { return None; } let want = region.intersect(&visible); - if want.is_empty() || covered.contains_rect(&want) { + if want.is_empty() || covered.iter().any(|r| r.contains_rect(&want)) { return None; } - p.covered = Some((key, region, want)); - Some(want) + // Keep disjoint views without marking the unrendered gaps between them as covered. + // Bound bookkeeping during long pans: after eight rectangles, render the whole affected + // region once. A different mode/revision resets coverage through `clip_damage`. + covered.retain(|r| !want.contains_rect(r)); + let refresh = if covered.len() < 8 { want } else { *region }; + if refresh == *region { + covered.clear(); + } + covered.push(refresh); + Some(refresh) } fn is_preview_key(key: u64) -> bool { diff --git a/crates/ui-egui/src/blend_preview/tests.rs b/crates/ui-egui/src/blend_preview/tests.rs index 22908ac248..72e809f786 100644 --- a/crates/ui-egui/src/blend_preview/tests.rs +++ b/crates/ui-egui/src/blend_preview/tests.rs @@ -138,3 +138,37 @@ fn a_hovered_mode_previews_on_every_selected_layer() { hover(&mut app, &[top], Some(BlendMode::Multiply)); assert_ne!(display_doc(&mut app, 0).unwrap().1, key); } + +#[test] +fn blend_hover_disjoint_coverage_retains_views_without_hiding_gaps() { + let (s, top) = session(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + hover(&mut app, &[top], Some(BlendMode::Multiply)); + let (_, key) = display_doc(&mut app, 0).unwrap(); + let st = app.session.active().unwrap(); + let (id, revision, region) = (st.doc.id, st.revision, st.doc.bounds()); + let a = photocraft_geom::Rect::new(0, 0, 2, 2); + let b = photocraft_geom::Rect::new(4, 0, 6, 2); + assert_eq!(super::clip_damage(&mut app, id, revision, key, region, a), a); + assert_eq!(super::uncovered(&mut app, id, revision, key, b), Some(b)); + assert_eq!(super::uncovered(&mut app, id, revision, key, a), None); + let gap = photocraft_geom::Rect::new(2, 0, 4, 2); + assert_eq!(super::uncovered(&mut app, id, revision, key, gap), Some(gap)); + // Repeated distinct views have bounded bookkeeping, then the whole region is current. + let mut fell_back = false; + for x in (8..40).step_by(4) { + let visible = photocraft_geom::Rect::new(x, 0, x + 2, 2); + if super::uncovered(&mut app, id, revision, key, visible) == Some(region) { + fell_back = true; + break; + } + } + assert!(fell_back); + assert_eq!(super::uncovered(&mut app, id, revision, key, region), None); + hover(&mut app, &[top], Some(BlendMode::Screen)); + let (_, next) = display_doc(&mut app, 0).unwrap(); + assert_eq!(super::clip_damage(&mut app, id, revision, next, region, a), a); + assert_eq!(super::uncovered(&mut app, id, revision, next, b), Some(b)); + hover(&mut app, &[top], None); + assert_eq!(super::clip_damage(&mut app, id, revision, 0, region, a), region); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 99aa686904..dee9e1388e 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1575,12 +1575,15 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: }; let (doc, raw_key) = display_doc(app, idx); let (display, _) = canvas_display(app, &doc, None); + // Repeated pattern tiles sample the same texture, including pixels outside the unwrapped + // viewport. Refresh the affected document region while Pattern Preview is enabled. + let blend_visible = if app.ui.view.pattern_preview { doc.bounds() } else { visible }; // The texture is shared by every display: only what it stores counts, not the monitor. let display_key = texture_key(display.as_deref()); let seen = app.canvases.get(&(id, GPU_OUTPUT)).map(|c| (c.revision, c.preview_key)); let mut damage = seen.and_then(|seen| damage_since(app, idx, seen, (revision, raw_key), display_key, last_damage)); if let Some(region) = damage { - damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, visible)); + damage = Some(crate::blend_preview::clip_damage(app, id, revision, raw_key, region, blend_visible)); } // To an adjustment dialog's preview: only what the view shows now (the rest as it moves there). if damage.is_some() @@ -1619,7 +1622,7 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: } // Blend previews keep offscreen pixels untouched until the view reaches them. // Use the normal refresh path so CPU fallback and pending redraws stay synchronized. - damage = crate::blend_preview::uncovered(app, id, revision, raw_key, visible); + damage = crate::blend_preview::uncovered(app, id, revision, raw_key, blend_visible); if damage.is_none() { return true; } diff --git a/crates/ui-egui/src/canvas/blend_viewport_tests.rs b/crates/ui-egui/src/canvas/blend_viewport_tests.rs index b1b4872aa6..ae6a01742d 100644 --- a/crates/ui-egui/src/canvas/blend_viewport_tests.rs +++ b/crates/ui-egui/src/canvas/blend_viewport_tests.rs @@ -30,6 +30,50 @@ fn blend_hover_multiple_layers_tracks_visible_canvas() { check_blend_viewport(false, true); } +#[test] +fn blend_hover_pattern_tiles_and_multiple_views_reuse_current_pixels() { + let _guard = photocraft_testkit::gpu_lock(); + let Some(rs) = render_state() else { return }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.set_wgpu(rs); + app.run("file.new", json!({"width":1024,"height":768,"background":"#336699"})).unwrap(); + let layer = app.run("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + app.run("edit.fill", json!({"color":"#cc8844"})).unwrap(); + let ctx = egui::Context::default(); + let a = DRect::new(724, 200, 1324, 500); + let b = DRect::new(0, 200, 300, 500); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + app.ui.view.pattern_preview = true; + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(BlendMode::Multiply)); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, b); + let bounds = app.session.active().unwrap().doc.bounds(); + assert_visible_pixels(&mut app, bounds); + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, bounds); + + app.ui.view.pattern_preview = false; + for mode in [BlendMode::Multiply, BlendMode::Screen] { + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], Some(mode)); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert!(ensure_gpu(&mut app, &ctx, 0, b)); + for visible in [a, b, a, b] { + app.perf.last_refresh_px = 0; + assert!(ensure_gpu(&mut app, &ctx, 0, visible)); + assert_eq!(app.perf.last_refresh_px, 0, "unchanged views must retain coverage together"); + assert_visible_pixels(&mut app, visible.intersect(&bounds)); + } + } + // Enabling periodic display during an existing hover must catch up the unseen gap too. + app.ui.view.pattern_preview = true; + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, bounds); + crate::blend_preview::hover(&mut app, &[photocraft_doc::LayerId(layer)], None); + assert!(ensure_gpu(&mut app, &ctx, 0, a)); + assert_visible_pixels(&mut app, bounds); +} + #[test] fn blend_hover_during_background_redraw_restores_committed_pixels() { let _guard = photocraft_testkit::gpu_lock(); From 850bf9fdaa7540d5c352cbddd97adfe793fc485a Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:31:59 +0200 Subject: [PATCH 18/34] perf(codecs): Avoid redundant PNG filter passes Keep the previous filter path as an exact byte oracle and measure the filter kernel independently of compression. --- crates/codecs/src/codecs/png.rs | 132 +++++++++++++++++++---- docs/png-filter-selection-performance.md | 38 +++++++ 2 files changed, 151 insertions(+), 19 deletions(-) create mode 100644 docs/png-filter-selection-performance.md diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 7c1a633d17..34ae84acc0 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -505,8 +505,15 @@ fn filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], o } }; let cost = |v: &[u8]| v.iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum::(); - let mut best = (cost(row), 0u8); + let mut best = cost(row); + let start = out.len(); + out.push(0); + out.extend_from_slice(row); for kind in 1u8..=4 { + if best == 0 { + break; + } + let mut c = 0u64; for i in 0..n { let x = row[i]; scratch[i] = match kind { @@ -515,27 +522,14 @@ fn filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], o 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), }; + c += u64::from((scratch[i] as i8).unsigned_abs()); } - let c = cost(&scratch[..n]); - if c < best.0 { - best = (c, kind); + if c < best { + best = c; + out[start] = kind; + out[start + 1..].copy_from_slice(&scratch[..n]); } } - out.push(best.1); - if best.1 == 0 { - out.extend_from_slice(row); - return; - } - for i in 0..n { - let x = row[i]; - scratch[i] = match best.1 { - 1 => x.wrapping_sub(left(i)), - 2 => x.wrapping_sub(up(i)), - 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), - _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), - }; - } - out.extend_from_slice(&scratch[..n]); } const ADLER_MOD: u32 = 65_521; @@ -659,6 +653,106 @@ mod indexed_tests { mod parallel_tests { use super::*; + #[test] + #[ignore = "manual 24 MP release benchmark"] + fn benchmark_filter_selection() { + use std::{hint::black_box, time::Instant}; + for pattern in ["zero", "identical", "varied"] { + let row: Vec = (0..6000 * 4).map(|i| if pattern == "zero" { 0 } else { (i * 17 + i / 13) as u8 }).collect(); + let prev: Vec<_> = row.iter().map(|v| if pattern == "identical" { *v } else { v.wrapping_add(3) }).collect(); + let mut scratch = vec![0; row.len()]; + let mut out = Vec::with_capacity(row.len() + 1); + for trial in 0..6 { + type Filter = fn(&[u8], Option<&[u8]>, usize, &mut [u8], &mut Vec); + let mut paths: [(&str, Filter); 2] = [("main", previous_filter_row), ("split", filter_row)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + for _ in 0..4000 { + out.clear(); + black_box(path)(black_box(&row), Some(black_box(&prev)), 4, &mut scratch, &mut out); + black_box(&out); + } + println!("filter,{pattern},{trial},{name},{:.6}", t.elapsed().as_secs_f64() * 1000.0); + } + } + } + } + + // The main-branch implementation before this refactor. + fn previous_filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], out: &mut Vec) { + let n = row.len(); + let up = |i: usize| prev.map_or(0, |p| p[i]); + let left = |i: usize| if i >= bpp { row[i - bpp] } else { 0 }; + let ul = |i: usize| if i >= bpp { prev.map_or(0, |p| p[i - bpp]) } else { 0 }; + let paeth = |a: u8, b: u8, c: u8| { + let p = i16::from(a) + i16::from(b) - i16::from(c); + let (pa, pb, pc) = ((p - i16::from(a)).abs(), (p - i16::from(b)).abs(), (p - i16::from(c)).abs()); + if pa <= pb && pa <= pc { + a + } else if pb <= pc { + b + } else { + c + } + }; + let cost = |v: &[u8]| v.iter().map(|&b| u64::from((b as i8).unsigned_abs())).sum::(); + let mut best = (cost(row), 0u8); + for kind in 1u8..=4 { + for i in 0..n { + let x = row[i]; + scratch[i] = match kind { + 1 => x.wrapping_sub(left(i)), + 2 => x.wrapping_sub(up(i)), + 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), + _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), + }; + } + let c = cost(&scratch[..n]); + if c < best.0 { + best = (c, kind); + } + } + out.push(best.1); + if best.1 == 0 { + out.extend_from_slice(row); + return; + } + for i in 0..n { + let x = row[i]; + scratch[i] = match best.1 { + 1 => x.wrapping_sub(left(i)), + 2 => x.wrapping_sub(up(i)), + 3 => x.wrapping_sub(((u16::from(left(i)) + u16::from(up(i))) / 2) as u8), + _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), + }; + } + out.extend_from_slice(&scratch[..n]); + } + + #[test] + fn adaptive_filter_preserves_minimum_cost_and_ties() { + for bpp in [1, 2, 3, 4, 6, 8] { + for seed in 0..32usize { + let row: Vec = (0..137).map(|i| (i * seed + i / 5) as u8).collect(); + let shifted: Vec<_> = row.iter().map(|v| v.wrapping_add(seed as u8)).collect(); + for prev in [None, Some(row.as_slice()), Some(shifted.as_slice())] { + let mut expected = vec![99]; + let mut actual = expected.clone(); + let mut scratch = vec![0; row.len()]; + previous_filter_row(&row, prev, bpp, &mut scratch, &mut expected); + filter_row(&row, prev, bpp, &mut scratch, &mut actual); + assert_eq!(actual, expected, "bpp={bpp}, seed={seed}"); + } + } + } + let mut out = Vec::new(); + filter_row(&[0; 16], None, 4, &mut [0; 16], &mut out); + assert_eq!(out, vec![0; 17]); + } + #[test] fn adler_combine_matches_one_pass() { let a: Vec = (0..100_000u32).map(|i| (i * 7 + i / 13) as u8).collect(); diff --git a/docs/png-filter-selection-performance.md b/docs/png-filter-selection-performance.md new file mode 100644 index 0000000000..34938b6d84 --- /dev/null +++ b/docs/png-filter-selection-performance.md @@ -0,0 +1,38 @@ +# PNG filter selection + +Only adaptive PNG filter selection changes: stop evaluating filters when their partial cost cannot win, and stop after a zero-cost winner. The kernel processes 4000 rows of 6000 RGBA8 pixels (24 MP) for zero, identical and varied rows; deflate is outside the timer. + +Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max +(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that +base; none of the other performance splits is applied. Release uses optimization +level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. +Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal +priority with no concurrent builds. Timings are medians of five samples after one +warm-up, except the compositor's ten Criterion samples. These synthetic workloads +are reproducible checks of this change, not a representative image corpus. + +| Workload | Main ms | This change ms | Time change | +|---|---:|---:|---:| +| zero | 448.138 | 5.734 | -98.7% | +| identical | 447.020 | 59.819 | -86.6% | +| varied | 450.469 | 277.254 | -38.5% | + +These are serial filter-kernel timings, not end-to-end PNG encoding timings. + +The committed oracle is the previous main-branch filter function. The unit test compares exact output bytes, including the selected filter/tie order, across six bytes-per-pixel layouts, 32 patterns and absent/identical/shifted previous rows. Existing encoder round trips and deterministic worker-count tests remain in place. + +Reproduce with the same release profile environment: + +```sh +CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-codecs --lib --no-run +# Run the printed executable at normal priority: + benchmark_filter_selection --ignored --nocapture --test-threads=1 +``` + +## Local validation + +- `cargo test -p photocraft-codecs --locked`: passed (782 passed, 4 ignored). +- `cargo clippy -p photocraft-codecs --locked --all-targets -- -D warnings`: passed. +- `cargo xtask layers`: passed. +- `cargo check -p photocraft-codecs --locked --target wasm32-unknown-unknown`: passed. +- `cargo xtask test-corpus -p codecs`: passed (796 passed, 4 ignored). From f6e7fc3c2a7e72afe23f7fce8d30871c303039f2 Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:31:59 +0200 Subject: [PATCH 19/34] perf(raster): Avoid redundant default pixel work Preserve default sample bits while skipping absent zero tiles and redundant default-pixel copies. Add the previous read path as the oracle. --- crates/raster/src/lib.rs | 118 +++++++++++++++++++++--- docs/sparse-raster-reads-performance.md | 40 ++++++++ 2 files changed, 145 insertions(+), 13 deletions(-) create mode 100644 docs/sparse-raster-reads-performance.md diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 20b809764a..1ea317d955 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -239,11 +239,19 @@ impl Surface { decode_pixel(&self.format, &self.default_pixel) } + fn default_samples(&self) -> [f32; 8] { + let mut px = [0.0; 8]; + for (i, v) in px.iter_mut().enumerate().take(self.channels()) { + *v = read_sample(&self.default_pixel, self.format.sample, i); + } + px + } + /// Mutable access to a tile, allocating it (filled with the default pixel) or un-sharing it. pub fn tile_mut(&mut self, c: TileCoord) -> &mut Tile { let fmt = self.format; - let dp = self.default_pixel.clone(); - let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, &dp))); + let dp = &self.default_pixel; + let arc = self.tiles.entry(c).or_insert_with(|| Arc::new(Tile::filled(&fmt, dp))); Arc::make_mut(arc) } @@ -319,9 +327,9 @@ impl Surface { /// Drop tiles that are entirely the default pixel. pub fn prune(&mut self) { - let dp = self.default_pixel.clone(); + let dp = self.default_pixel.as_ref(); let bpp = dp.len(); - self.tiles.retain(|_, t| t.data.chunks_exact(bpp).any(|px| px != &*dp)); + self.tiles.retain(|_, t| t.data.chunks_exact(bpp).any(|px| px != dp)); } #[inline] @@ -411,10 +419,15 @@ impl Surface { let w = r.width() as usize; out.clear(); out.resize(w * r.height() as usize * n, 0.0); - let dp = self.default_pixel(); + let dp = self.default_samples(); + let dp = &dp[..n]; + let zero = self.default_pixel.iter().all(|&b| b == 0); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let tile = self.tiles.get(&tc); + if tile.is_none() && zero { + continue; + } for y in tr.y0..tr.y1 { let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; let span = tr.width() as usize * n; @@ -426,9 +439,10 @@ impl Surface { *d = read_sample(&t.data, self.format.sample, base + i); } } + None if n == 1 => dst.fill(dp[0]), None => { for px in dst.chunks_exact_mut(n) { - px.copy_from_slice(&dp); + px.copy_from_slice(dp); } } } @@ -445,7 +459,7 @@ impl Surface { debug_assert_eq!(out.len(), w * r.height() as usize); let fmt = self.format; let n = fmt.channels(); - let dp = to_rgba(&fmt, &self.default_pixel()); + let dp = to_rgba(&fmt, &self.default_samples()); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let tile = self.tiles.get(&tc); @@ -510,7 +524,7 @@ impl Surface { let fmt = self.format; let rgba8 = matches!((fmt.mode, fmt.sample, fmt.alpha), (ColorMode::Rgb, SampleType::U8, true)); let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let dp = to_rgba(&fmt, &self.default_pixel()); + let dp = to_rgba(&fmt, &self.default_samples()); let dp8 = [q(dp[0]), q(dp[1]), q(dp[2]), q(dp[3])]; let mut row = Vec::new(); for tc in r.tiles() { @@ -551,10 +565,15 @@ impl Surface { let n = self.channels(); let w = r.width() as usize; let mut out = vec![0.0f32; w * r.height() as usize * n]; - let dp = self.default_pixel(); + let dp = self.default_samples(); + let dp = &dp[..n]; + let zero = self.default_pixel.iter().all(|&b| b == 0); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let tile = self.tiles.get(&tc); + if tile.is_none() && zero { + continue; + } for y in tr.y0..tr.y1 { for x in tr.x0..tr.x1 { let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; @@ -565,7 +584,8 @@ impl Surface { out[o + i] = read_sample(&t.data, self.format.sample, base + i); } } - None => out[o..o + n].copy_from_slice(&dp), + None if n == 1 => out[o] = dp[0], + None => out[o..o + n].copy_from_slice(dp), } } } @@ -1102,6 +1122,58 @@ pub fn is_hdr(sample: SampleType) -> bool { #[cfg(test)] mod tests { + + #[test] + #[ignore = "manual 24 MP release benchmark"] + fn benchmark_sparse_reads() { + use std::{hint::black_box, time::Instant}; + let rect = Rect::new(0, 0, 6000, 4000); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + for default in [0.0, 0.25] { + let mut s = Surface::with_default(PixelFormat::GRAY8.with_sample(depth), &[default]); + s.fill_rect(Rect::new(257, 257, 266, 266), &[0.75]); + assert_eq!(s.read_region(rect), previous_read_region(&s, rect)); + for trial in 0..6 { + let mut paths = [("main", previous_read_region as fn(&Surface, Rect) -> Vec), ("split", Surface::read_region)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + let out = black_box(path)(&s, rect); + let elapsed = t.elapsed().as_secs_f64() * 1000.0; + black_box(&out); + println!("sparse,{depth:?}-{default},{trial},{name},{elapsed:.6}"); + } + } + } + } + } + fn previous_read_region(surface: &Surface, r: Rect) -> Vec { + let n = surface.channels(); + let w = r.width() as usize; + let mut out = vec![0.0f32; w * r.height() as usize * n]; + let dp = surface.default_pixel(); + for tc in r.tiles() { + let tr = tc.rect().intersect(&r); + let tile = surface.tiles.get(&tc); + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; + match tile { + Some(t) => { + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; + for i in 0..n { + out[o + i] = read_sample(&t.data, surface.format.sample, base + i); + } + } + None => out[o..o + n].copy_from_slice(&dp), + } + } + } + } + out + } /// Distinct tile allocations in `s`. fn distinct_tiles(s: &Surface) -> usize { let mut seen: Vec<*const Tile> = s.tiles().map(|(_, t)| Arc::as_ptr(t)).collect(); @@ -1237,27 +1309,47 @@ mod tests { #[test] fn zero_alloc_accessors_match_read_region() { - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::GRAY8] { - let mut s = Surface::with_default(fmt, &vec![0.25; fmt.channels()]); + for (fmt, default) in [ + PixelFormat::RGBA8, + PixelFormat::RGBA16, + PixelFormat::RGBA32F, + PixelFormat::GRAYA8, + PixelFormat::CMYKA8, + PixelFormat::GRAY8, + PixelFormat::GRAY8.with_sample(SampleType::F32), + PixelFormat::new(ColorMode::Lab, SampleType::U16, true), + ] + .into_iter() + .flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default))) + { + let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); let r = Rect::new(-300, -20, 300, 40); for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() { let px: Vec = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect(); s.write_pixel(x, y, &px); } let region = s.read_region(r); + assert!(region.iter().map(|v| v.to_bits()).eq(previous_read_region(&s, r).into_iter().map(f32::to_bits))); let mut into = vec![9.0; 3]; s.read_region_into(r, &mut into); assert_eq!(region, into); let mut rgba = vec![[0.0; 4]; (r.width() * r.height()) as usize]; s.read_rgba_into(r, &mut rgba); + let mut rgba8 = vec![[0; 4]; rgba.len()]; + s.read_rgba8_into(r, &mut rgba8); let n = fmt.channels(); for (i, p) in region.chunks_exact(n).enumerate() { let want = to_rgba(&fmt, p); + assert_eq!(rgba8[i], want.map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); for c in 0..4 { assert!((rgba[i][c] - want[c]).abs() < 1e-6, "{fmt:?} px {i}"); } let (x, y) = (r.x0 + (i % r.width() as usize) as i32, r.y0 + (i / r.width() as usize) as i32); - assert_eq!(s.sample_channel(x, y, 0), p[0]); + for c in 0..n { + let bits = s.sample_channel(x, y, c).to_bits(); + assert_eq!(bits, p[c].to_bits()); + assert_eq!(bits, into[i * n + c].to_bits()); + } } assert!(s.has_tiles_in(Rect::new(0, 0, 1, 1))); assert!(!s.has_tiles_in(Rect::new(1000, 1000, 1001, 1001))); diff --git a/docs/sparse-raster-reads-performance.md b/docs/sparse-raster-reads-performance.md new file mode 100644 index 0000000000..6a76244a99 --- /dev/null +++ b/docs/sparse-raster-reads-performance.md @@ -0,0 +1,40 @@ +# Sparse raster reads + +Only default-pixel work changes: skip absent zero-default tiles and avoid temporary default-pixel allocations/copies. Read 6000×4000 single-channel pixels (24 MP) with one 9×9 painted patch, at three depths and two defaults. + +Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max +(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that +base; none of the other performance splits is applied. Release uses optimization +level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. +Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal +priority with no concurrent builds. Timings are medians of five samples after one +warm-up, except the compositor's ten Criterion samples. These synthetic workloads +are reproducible checks of this change, not a representative image corpus. + +| Workload | Main ms | This change ms | Time change | +|---|---:|---:|---:| +| U8-0 | 48.484 | 0.430 | -99.1% | +| U8-0.25 | 48.934 | 4.466 | -90.9% | +| U16-0 | 48.517 | 0.441 | -99.1% | +| U16-0.25 | 48.475 | 4.461 | -90.8% | +| F32-0 | 49.066 | 0.479 | -99.0% | +| F32-0.25 | 48.511 | 4.503 | -90.7% | + +These are read_region timings including output allocation. ZIP CRC-32 acceleration is already on main and is not duplicated here. + +The committed oracle is the previous read_region implementation. Unit coverage compares exact float bits and checks read_region_into, RGBA/RGBA8 reads and individual samples across sparse tile boundaries, negative coordinates, signed zero, nonzero defaults and eight pixel formats. + +Reproduce with the same release profile environment: + +```sh +CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-raster --lib --no-run +# Run the printed executable at normal priority: + benchmark_sparse_reads --ignored --nocapture --test-threads=1 +``` + +## Local validation + +- `cargo test -p photocraft-raster --locked`: passed (27 passed, 1 ignored). +- `cargo clippy -p photocraft-raster --locked --all-targets -- -D warnings`: passed. +- `cargo xtask layers`: passed. +- `cargo check -p photocraft-raster --locked --target wasm32-unknown-unknown`: passed. From 76a6405f9b25491cc1016ed2861e0976f6455b7a Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:31:59 +0200 Subject: [PATCH 20/34] perf(io): Interleave PSD pixels in the final buffer Remove intermediate band buffers while retaining byte-for-byte equivalence with the previous path at every sample depth. --- crates/io/src/pixels.rs | 142 ++++++++++++++++++++--------- docs/psd-interleave-performance.md | 38 ++++++++ 2 files changed, 139 insertions(+), 41 deletions(-) create mode 100644 docs/psd-interleave-performance.md diff --git a/crates/io/src/pixels.rs b/crates/io/src/pixels.rs index 0167eb3b3f..cca2a8dfd4 100644 --- a/crates/io/src/pixels.rs +++ b/crates/io/src/pixels.rs @@ -43,40 +43,43 @@ pub fn interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: Sampl let ch = planes.len(); let row = ch * bps; let mut out = vec![0u8; n * row]; - // One band of rows per core, written straight into its slice of the shared output: the - // per-pixel channel loop stays, but a band holds ~1/cores of a 20 MP image's iterations - // instead of all of them. + if out.is_empty() { + return out; + } let bs = bands(n); - let parts: Vec> = par_map(bs.clone(), |band| { - let mut part = vec![0u8; band.len() * row]; - for (i, p) in band.clone().enumerate() { - for (c, plane) in planes.iter().enumerate() { - let dst = &mut part[(i * ch + c) * bps..(i * ch + c + 1) * bps]; - match plane { - Some(pl) if pl.len() >= (p + 1) * bps => { - let src = &pl[p * bps..(p + 1) * bps]; - for k in 0..bps { - dst[k] = src[bps - 1 - k]; - } - if cfg!(target_endian = "big") { - dst.copy_from_slice(src); - } - if invert[c] { - invert_sample(dst, s); - } - } - _ => dst.copy_from_slice(&fill[c]), - } + let step = bs.first().map_or(n, |b| b.len()) * row; + par_map(bs.into_iter().zip(out.chunks_mut(step)).collect(), |(band, part)| { + for (c, plane) in planes.iter().enumerate() { + let src = plane.and_then(|p| p.get(band.start * bps..)).unwrap_or_default(); + let inv = src.len() >= bps && invert[c]; + let fill = fill.get(c).map(Vec::as_slice).unwrap_or_default(); + match s { + SampleType::U8 => write_channel(part, ch, c, src, fill, |[v]| [if inv { 255 - v } else { v }]), + SampleType::U16 => write_channel(part, ch, c, src, fill, |v| { + let v = u16::from_be_bytes(v); + (if inv { 65535 - v } else { v }).to_ne_bytes() + }), + SampleType::F32 => write_channel(part, ch, c, src, fill, |v| { + // Preserve float bits when no inversion is requested. + if inv { (1.0 - f32::from_be_bytes(v)).to_ne_bytes() } else { u32::from_be_bytes(v).to_ne_bytes() } + }), } } - part }); - for (band, part) in bs.into_iter().zip(parts) { - out[band.start * row..band.end * row].copy_from_slice(&part); - } out } +fn write_channel(out: &mut [u8], ch: usize, c: usize, src: &[u8], fill: &[u8], decode: impl Fn([u8; N]) -> [u8; N]) { + let mut samples = src.as_chunks::().0.iter(); + for pixel in out.chunks_exact_mut(ch * N) { + let dst = &mut pixel[c * N..(c + 1) * N]; + match samples.next() { + Some(sample) => dst.copy_from_slice(&decode(*sample)), + None => dst.copy_from_slice(fill), + } + } +} + /// Splits interleaved native-endian bytes into big-endian planes. pub fn deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) -> Vec> { let bps = s.bytes(); @@ -155,6 +158,7 @@ pub fn zero_sample(s: SampleType) -> Vec { } /// Quantizes a normalized value to big-endian bytes. +#[inline] pub fn encode_be(v: f32, s: SampleType, out: &mut Vec) { match s { SampleType::U8 => out.push((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8), @@ -217,21 +221,29 @@ pub fn bands(n: usize) -> Vec> { mod tests { use super::*; - #[test] - fn banded_shuffles_match_a_sequential_reference() { - fn seq_interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: SampleType, invert: &[bool]) -> Vec { - let bps = s.bytes(); - let ch = planes.len(); - let mut out = vec![0u8; n * ch * bps]; - for (c, plane) in planes.iter().enumerate() { - for i in 0..n { - let dst = &mut out[(i * ch + c) * bps..(i * ch + c + 1) * bps]; + pub(super) fn previous_interleave(planes: &[Option<&[u8]>], fill: &[Vec], n: usize, s: SampleType, invert: &[bool]) -> Vec { + let bps = s.bytes(); + let ch = planes.len(); + let row = ch * bps; + let mut out = vec![0u8; n * row]; + // One band of rows per core, written straight into its slice of the shared output: the + // per-pixel channel loop stays, but a band holds ~1/cores of a 20 MP image's iterations + // instead of all of them. + let bs = bands(n); + let parts: Vec> = par_map(bs.clone(), |band| { + let mut part = vec![0u8; band.len() * row]; + for (i, p) in band.clone().enumerate() { + for (c, plane) in planes.iter().enumerate() { + let dst = &mut part[(i * ch + c) * bps..(i * ch + c + 1) * bps]; match plane { - Some(p) if p.len() >= (i + 1) * bps => { - let src = &p[i * bps..(i + 1) * bps]; + Some(pl) if pl.len() >= (p + 1) * bps => { + let src = &pl[p * bps..(p + 1) * bps]; for k in 0..bps { dst[k] = src[bps - 1 - k]; } + if cfg!(target_endian = "big") { + dst.copy_from_slice(src); + } if invert[c] { invert_sample(dst, s); } @@ -240,8 +252,16 @@ mod tests { } } } - out + part + }); + for (band, part) in bs.into_iter().zip(parts) { + out[band.start * row..band.end * row].copy_from_slice(&part); } + out + } + + #[test] + fn banded_shuffles_match_a_sequential_reference() { fn seq_deinterleave(bytes: &[u8], ch: usize, s: SampleType, invert: &[bool]) -> Vec> { let bps = s.bytes(); let n = bytes.len() / (ch * bps).max(1); @@ -260,16 +280,17 @@ mod tests { planes } // Odd pixel counts cross band boundaries; a missing plane exercises the fill path. - for n in [1usize, 7, 64, 1000] { + for n in [0usize, 1, 7, 64, 1000] { for s in [SampleType::U8, SampleType::U16, SampleType::F32] { let bps = s.bytes(); let planes: Vec> = (0..4).map(|c| (0..n * bps).map(|i| (i * 13 + c * 5) as u8).collect()).collect(); let mut refs: Vec> = planes.iter().map(|p| Some(&p[..])).collect(); refs[2] = None; + refs[3] = Some(&planes[3][..(n * bps).saturating_sub(1)]); let fill: Vec> = (0..4).map(|c| vec![c as u8 * 40; bps]).collect(); let invert = [false, true, false, true]; let got = interleave(&refs, &fill, n, s, &invert); - let want = seq_interleave(&refs, &fill, n, s, &invert); + let want = previous_interleave(&refs, &fill, n, s, &invert); assert_eq!(got, want, "interleave n={n}"); let planes_back = deinterleave(&got, 4, s, &invert); let want_back = seq_deinterleave(&got, 4, s, &invert); @@ -287,6 +308,7 @@ mod tests { let fill = vec![zero_sample(s); 3]; let inv = [false, true, false]; let il = interleave(&refs, &fill, 4, s, &inv); + assert_eq!(interleave(&refs, &[], 4, s, &inv), il); let back = deinterleave(&il, 3, s, &inv); if s == SampleType::F32 { // 1 - (1 - v) may not be exact for floats; only check non-inverted planes. @@ -302,6 +324,12 @@ mod tests { fn missing_planes_use_fill() { let il = interleave(&[None, Some(&[5, 6])], &[vec![9], vec![0]], 2, SampleType::U8, &[false, false]); assert_eq!(il, vec![9, 5, 9, 6]); + for s in [SampleType::U8, SampleType::U16, SampleType::F32] { + for n in [1, 1000] { + let fill = vec![vec![9; s.bytes()]; 2]; + assert_eq!(interleave(&[None, Some(&[1, 2, 3][..s.bytes() - 1])], &fill, n, s, &[]), vec![9; n * 2 * s.bytes()]); + } + } } #[test] @@ -343,3 +371,35 @@ mod tests { assert_eq!(decode_be(&f, 0, SampleType::F32), 2.5); } } + +#[cfg(test)] +mod measurement { + use super::*; + #[test] + #[ignore = "manual 24 MP release benchmark"] + fn benchmark_interleave() { + use std::{hint::black_box, time::Instant}; + const N: usize = 24_000_000; + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let bps = sample.bytes(); + let planes: Vec> = (0..4).map(|c| (0..N * bps).map(|i| (i * 13 + c * 5) as u8).collect()).collect(); + let refs: Vec<_> = planes.iter().map(|p| Some(p.as_slice())).collect(); + let fill = vec![vec![0; bps]; 4]; + let invert = [false, true, false, true]; + assert_eq!(tests::previous_interleave(&refs, &fill, N, sample, &invert), interleave(&refs, &fill, N, sample, &invert)); + for trial in 0..6 { + let mut paths = [("main", tests::previous_interleave as fn(_, _, _, _, _) -> _), ("split", interleave)]; + if trial % 2 == 1 { + paths.reverse(); + } + for (name, path) in paths { + let t = Instant::now(); + let out = black_box(path)(&refs, &fill, N, sample, &invert); + let elapsed = t.elapsed().as_secs_f64() * 1000.0; + black_box(&out); + println!("interleave,{sample:?},{trial},{name},{elapsed:.6}"); + } + } + } + } +} diff --git a/docs/psd-interleave-performance.md b/docs/psd-interleave-performance.md new file mode 100644 index 0000000000..99ae70824f --- /dev/null +++ b/docs/psd-interleave-performance.md @@ -0,0 +1,38 @@ +# PSD pixel buffer allocation + +Only PSD pixel shuffling and sample-codec inlining change. Interleave writes into the final buffer rather than allocating an intermediate buffer per band. The kernel processes 24 million pixels with four full planes at 8-bit, 16-bit and float depth. + +Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max +(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that +base; none of the other performance splits is applied. Release uses optimization +level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. +Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal +priority with no concurrent builds. Timings are medians of five samples after one +warm-up, except the compositor's ten Criterion samples. These synthetic workloads +are reproducible checks of this change, not a representative image corpus. + +| Workload | Main ms | This change ms | Time change | +|---|---:|---:|---:| +| U8 | 20.493 | 5.097 | -75.1% | +| U16 | 31.827 | 6.312 | -80.2% | +| F32 | 41.915 | 11.305 | -73.0% | + +These are interleave-kernel timings, not whole PSD import/export timings. Direct RLE output is already on main and is not part of this PR. + +The committed equivalence test uses the literal previous main-branch interleave implementation. It compares raw bytes across U8/U16/F32, empty and partial bands, missing/truncated planes, fill pixels and inversion. Existing deinterleave reference and big-endian sample-codec round trips cover the companion paths. + +Reproduce with the same release profile environment: + +```sh +CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-io --lib --no-run +# Run the printed executable at normal priority: + benchmark_interleave --ignored --nocapture --test-threads=1 +``` + +## Local validation + +- `cargo test -p photocraft-io --locked`: passed (617 passed, 6 ignored). +- `cargo clippy -p photocraft-io --locked --all-targets -- -D warnings`: passed. +- `cargo xtask layers`: passed. +- `cargo check -p photocraft-io --locked --target wasm32-unknown-unknown`: passed. +- `cargo xtask test-corpus -p io`: passed (646 passed, 6 ignored). From 6b1aa81561d6cc8487a95da27b95ef6d2d4199af Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:15:05 +0200 Subject: [PATCH 21/34] docs(perf): measure PNG filtering on real images --- docs/png-filter-selection-performance.md | 42 +++++++++++------------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/docs/png-filter-selection-performance.md b/docs/png-filter-selection-performance.md index 34938b6d84..1f7ffeab29 100644 --- a/docs/png-filter-selection-performance.md +++ b/docs/png-filter-selection-performance.md @@ -1,35 +1,31 @@ # PNG filter selection -Only adaptive PNG filter selection changes: stop evaluating filters when their partial cost cannot win, and stop after a zero-cost winner. The kernel processes 4000 rows of 6000 RGBA8 pixels (24 MP) for zero, identical and varied rows; deflate is outside the timer. +Stop evaluating PNG filters when their partial cost cannot win. Filter choice and encoded bytes must remain identical. -Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max -(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that -base; none of the other performance splits is applied. Release uses optimization -level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. -Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal -priority with no concurrent builds. Timings are medians of five samples after one -warm-up, except the compositor's ten Criterion samples. These synthetic workloads -are reproducible checks of this change, not a representative image corpus. +Photo PNG encoding improves, with identical streams. The small designs show little change because they use the existing serial PNG encoder. The previous filter-kernel percentages are not end-to-end results. -| Workload | Main ms | This change ms | Time change | -|---|---:|---:|---:| -| zero | 448.138 | 5.734 | -98.7% | -| identical | 447.020 | 59.819 | -86.6% | -| varied | 450.469 | 277.254 | -38.5% | +Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. -These are serial filter-kernel timings, not end-to-end PNG encoding timings. +The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. -The committed oracle is the previous main-branch filter function. The unit test compares exact output bytes, including the selected filter/tie order, across six bytes-per-pixel layouts, 32 patterns and absent/identical/shifted previous rows. Existing encoder round trips and deterministic worker-count tests remain in place. +The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. -Reproduce with the same release profile environment: +| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | +|---|---|---:|---:|---:|---:|---:| +| panasonic-8 | png-encode | 358.725 | 346.020 | -3.5% | -7.0..-0.9% | 24,569,965 / 24,569,965 | +| panasonic-16 | png-encode | 338.106 | 296.860 | -12.2% | -12.3..-9.7% | 111,583,441 / 111,583,441 | +| canon-8 | png-encode | 178.675 | 169.289 | -5.3% | -35.0..-2.7% | 13,720,268 / 13,720,268 | +| canon-16 | png-encode | 162.107 | 145.356 | -10.3% | -12.2..+4.6% | 58,279,529 / 58,279,529 | +| layout-masks | png-encode | 4.037 | 3.986 | -1.3% | -3.3..+1.9% | 42,842 / 42,842 | +| layout-mask-index | png-encode | 11.343 | 11.404 | +0.5% | -0.0..+2.2% | 115,229 / 115,229 | -```sh -CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-codecs --lib --no-run -# Run the printed executable at normal priority: - benchmark_filter_selection --ignored --nocapture --test-threads=1 -``` +The real-image PNG streams match main byte for byte and decode to identical pixels. The committed previous-filter oracle also covers bytes-per-pixel layouts, early exits, zero-cost rows and ties. -## Local validation +Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. + +## Earlier split validation + +These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. - `cargo test -p photocraft-codecs --locked`: passed (782 passed, 4 ignored). - `cargo clippy -p photocraft-codecs --locked --all-targets -- -D warnings`: passed. From 78a9982eec3508dbd7654b262aea6b9f28386b09 Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:15:06 +0200 Subject: [PATCH 22/34] perf(raster): share contiguous region reads --- crates/raster/src/lib.rs | 34 ++++----------- docs/sparse-raster-reads-performance.md | 57 ++++++++++++++----------- 2 files changed, 39 insertions(+), 52 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 1ea317d955..2ebfde9c59 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -419,6 +419,12 @@ impl Surface { let w = r.width() as usize; out.clear(); out.resize(w * r.height() as usize * n, 0.0); + self.read_samples_into(r, out); + } + + fn read_samples_into(&self, r: Rect, out: &mut [f32]) { + let n = self.channels(); + let w = r.width() as usize; let dp = self.default_samples(); let dp = &dp[..n]; let zero = self.default_pixel.iter().all(|&b| b == 0); @@ -431,7 +437,7 @@ impl Surface { for y in tr.y0..tr.y1 { let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; let span = tr.width() as usize * n; - let dst = &mut out[o..o + span]; + let Some(dst) = out.get_mut(o..o + span) else { continue }; match tile { Some(t) => { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; @@ -565,31 +571,7 @@ impl Surface { let n = self.channels(); let w = r.width() as usize; let mut out = vec![0.0f32; w * r.height() as usize * n]; - let dp = self.default_samples(); - let dp = &dp[..n]; - let zero = self.default_pixel.iter().all(|&b| b == 0); - for tc in r.tiles() { - let tr = tc.rect().intersect(&r); - let tile = self.tiles.get(&tc); - if tile.is_none() && zero { - continue; - } - for y in tr.y0..tr.y1 { - for x in tr.x0..tr.x1 { - let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; - match tile { - Some(t) => { - let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; - for i in 0..n { - out[o + i] = read_sample(&t.data, self.format.sample, base + i); - } - } - None if n == 1 => out[o] = dp[0], - None => out[o..o + n].copy_from_slice(dp), - } - } - } - } + self.read_samples_into(r, &mut out); out } diff --git a/docs/sparse-raster-reads-performance.md b/docs/sparse-raster-reads-performance.md index 6a76244a99..1cc1a04502 100644 --- a/docs/sparse-raster-reads-performance.md +++ b/docs/sparse-raster-reads-performance.md @@ -1,38 +1,43 @@ # Sparse raster reads -Only default-pixel work changes: skip absent zero-default tiles and avoid temporary default-pixel allocations/copies. Read 6000×4000 single-channel pixels (24 MP) with one 9×9 painted patch, at three depths and two defaults. +Skip absent zero-default tiles and avoid temporary default-pixel allocations and copies. ZIP CRC acceleration is already on main. -Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max -(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that -base; none of the other performance splits is applied. Release uses optimization -level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. -Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal -priority with no concurrent builds. Timings are medians of five samples after one -warm-up, except the compositor's ten Criterion samples. These synthetic workloads -are reproducible checks of this change, not a representative image corpus. +A roughly 4% median dense 16-bit city-photo read slowdown repeated, with paired intervals crossing zero. The local fix shares the existing contiguous row loop between allocating and reusable-buffer reads, removes duplicated code, and preserves zero-filled allocation for allocating reads. Final measurements include all photo depths and authored designs; all outputs match bit for bit. -| Workload | Main ms | This change ms | Time change | -|---|---:|---:|---:| -| U8-0 | 48.484 | 0.430 | -99.1% | -| U8-0.25 | 48.934 | 4.466 | -90.9% | -| U16-0 | 48.517 | 0.441 | -99.1% | -| U16-0.25 | 48.475 | 4.461 | -90.8% | -| F32-0 | 49.066 | 0.479 | -99.0% | -| F32-0.25 | 48.511 | 4.503 | -90.7% | +Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. -These are read_region timings including output allocation. ZIP CRC-32 acceleration is already on main and is not duplicated here. +The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. -The committed oracle is the previous read_region implementation. Unit coverage compares exact float bits and checks read_region_into, RGBA/RGBA8 reads and individual samples across sparse tile boundaries, negative coordinates, signed zero, nonzero defaults and eight pixel formats. +The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. -Reproduce with the same release profile environment: +| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | +|---|---|---:|---:|---:|---:|---:| +| panasonic-16 | read (fixed) | 54.689 | 41.140 | -24.8% | -28.0..-23.8% | — | +| panasonic-16 | render (fixed) | 38.492 | 38.345 | -0.4% | -1.8..+2.0% | — | +| canon-16 | read (fixed) | 27.634 | 19.236 | -30.4% | -34.0..-23.3% | — | +| panasonic-8 | read (fixed) | 50.429 | 20.210 | -59.9% | -62.2..-56.7% | — | +| panasonic-8 | render (fixed) | 30.953 | 30.670 | -0.9% | -3.4..+1.5% | — | +| panasonic-32 | read (fixed) | 91.120 | 69.922 | -23.3% | -23.6..-20.7% | — | +| panasonic-32 | render (fixed) | 39.436 | 39.867 | +1.1% | -4.5..+3.7% | — | +| canon-8 | read (fixed) | 24.899 | 10.543 | -57.7% | -58.5..-54.9% | — | +| canon-8 | render (fixed) | 16.925 | 16.901 | -0.1% | -5.6..+5.5% | — | +| canon-16 | render (fixed) | 21.569 | 21.716 | +0.7% | -2.2..+2.4% | — | +| canon-32 | read (fixed) | 45.494 | 35.200 | -22.6% | -23.5..-21.5% | — | +| canon-32 | render (fixed) | 22.056 | 22.180 | +0.6% | -1.8..+6.9% | — | +| layout-masks | read (fixed) | 35.240 | 3.438 | -90.2% | -90.7..-89.9% | — | +| layout-masks | render (fixed) | 8.167 | 7.461 | -8.6% | -10.6..-8.3% | — | +| layout-mask-index | read (fixed) | 2.314 | 1.051 | -54.6% | -61.7..-50.0% | — | +| layout-mask-index | render (fixed) | 1.926 | 1.827 | -5.1% | -13.0..+0.6% | — | -```sh -CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-raster --lib --no-run -# Run the printed executable at normal priority: - benchmark_sparse_reads --ignored --nocapture --test-threads=1 -``` +All real read-region and render float bits match main. The committed previous-read-region oracle also covers sparse boundaries, negative coordinates, signed zero, defaults and eight pixel formats. -## Local validation +Current local checks: `cargo test -p photocraft-raster --locked --lib` (27 passed, one ignored manual benchmark); strict all-target Clippy; affected wasm32 check. All passed. The existing previous-read-path oracle covers the shared loop. + +Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. + +## Earlier split validation + +These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. - `cargo test -p photocraft-raster --locked`: passed (27 passed, 1 ignored). - `cargo clippy -p photocraft-raster --locked --all-targets -- -D warnings`: passed. From b5b5776a3058b8c7c4920f9728476b07122c635e Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:15:06 +0200 Subject: [PATCH 23/34] perf(io): remove the PSD export inlining hint --- crates/io/src/pixels.rs | 1 - docs/psd-interleave-performance.md | 54 +++++++++++++++++------------- 2 files changed, 31 insertions(+), 24 deletions(-) diff --git a/crates/io/src/pixels.rs b/crates/io/src/pixels.rs index cca2a8dfd4..0251f83755 100644 --- a/crates/io/src/pixels.rs +++ b/crates/io/src/pixels.rs @@ -158,7 +158,6 @@ pub fn zero_sample(s: SampleType) -> Vec { } /// Quantizes a normalized value to big-endian bytes. -#[inline] pub fn encode_be(v: f32, s: SampleType, out: &mut Vec) { match s { SampleType::U8 => out.push((v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8), diff --git a/docs/psd-interleave-performance.md b/docs/psd-interleave-performance.md index 99ae70824f..5958442881 100644 --- a/docs/psd-interleave-performance.md +++ b/docs/psd-interleave-performance.md @@ -1,35 +1,43 @@ # PSD pixel buffer allocation -Only PSD pixel shuffling and sample-codec inlining change. Interleave writes into the final buffer rather than allocating an intermediate buffer per band. The kernel processes 24 million pixels with four full planes at 8-bit, 16-bit and float depth. +Write PSD interleaved pixels directly into the final buffer. Direct RLE output is already on main. The unrelated export-side sample-encoder inlining hint is removed locally. -Measured on 2026-10-19 against `d95fdf3181c01ad41e95456091a394b105a9afb2` on an Apple M4 Max -(16 CPUs, 128 GiB), macOS arm64, rustc 1.99.1. Each branch starts directly at that -base; none of the other performance splits is applied. Release uses optimization -level 3, LTO off, 16 codegen units, debug info off and incremental compilation off. -Builds ran at nice 10 with APFS-cloned warm caches; measurements ran at normal -priority with no concurrent builds. Timings are medians of five samples after one -warm-up, except the compositor's ten Criterion samples. These synthetic workloads -are reproducible checks of this change, not a representative image corpus. +Whole-photo imports improve by about 4–7%, and the authored designs by about 20–26%. An added export-side inlining hint accompanied a separately confirmed 2.3% float PSD export slowdown (2440.168 → 2497.423 ms). Removing that one line leaves export source equal to main; follow-up float export is +0.4% and 16-bit export +0.9%, with both paired intervals crossing zero. These results supersede the much larger previous interleave-only percentages. -| Workload | Main ms | This change ms | Time change | -|---|---:|---:|---:| -| U8 | 20.493 | 5.097 | -75.1% | -| U16 | 31.827 | 6.312 | -80.2% | -| F32 | 41.915 | 11.305 | -73.0% | +Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. -These are interleave-kernel timings, not whole PSD import/export timings. Direct RLE output is already on main and is not part of this PR. +The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. -The committed equivalence test uses the literal previous main-branch interleave implementation. It compares raw bytes across U8/U16/F32, empty and partial bands, missing/truncated planes, fill pixels and inversion. Existing deinterleave reference and big-endian sample-codec round trips cover the companion paths. +The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. -Reproduce with the same release profile environment: +| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | +|---|---|---:|---:|---:|---:|---:| +| panasonic-32 | psd-export (fixed) | 2471.456 | 2481.877 | +0.4% | -0.1..+1.7% | 461,042,978 / 461,042,978 | +| panasonic-16 | psd-export (fixed) | 2649.246 | 2673.071 | +0.9% | -5.2..+1.6% | 274,409,683 / 274,409,683 | +| panasonic-8 | psd-import | 275.828 | 262.237 | -4.9% | -5.9..-4.1% | 98,823,859 / 98,823,859 | +| panasonic-8 | psd-export | 2937.854 | 2915.929 | -0.7% | -11.5..+5.6% | 98,823,859 / 98,823,859 | +| panasonic-16 | psd-import | 365.901 | 349.827 | -4.4% | -4.4..-2.6% | 274,409,683 / 274,409,683 | +| panasonic-32 | psd-import | 360.706 | 334.838 | -7.2% | -12.6..-4.4% | 461,042,978 / 461,042,978 | +| canon-8 | psd-import | 141.331 | 135.878 | -3.9% | -5.1..-3.6% | 56,209,597 / 56,209,597 | +| canon-8 | psd-export | 1052.421 | 1054.472 | +0.2% | -0.6..+1.3% | 56,209,597 / 56,209,597 | +| canon-16 | psd-import | 177.327 | 169.952 | -4.2% | -5.5..-1.7% | 140,673,004 / 140,673,004 | +| canon-16 | psd-export | 1248.449 | 1239.159 | -0.7% | -1.6..+0.6% | 140,673,004 / 140,673,004 | +| canon-32 | psd-import | 175.721 | 163.271 | -7.1% | -9.3..-4.9% | 228,234,238 / 228,234,238 | +| canon-32 | psd-export | 1008.772 | 1005.356 | -0.3% | -1.8..+0.7% | 228,234,238 / 228,234,238 | +| layout-masks | psd-import | 12.509 | 9.981 | -20.2% | -20.8..-14.5% | 493,006 / 493,006 | +| layout-masks | psd-export | 55.113 | 54.714 | -0.7% | -2.3..+1.2% | 493,006 / 493,006 | +| layout-mask-index | psd-import | 3.299 | 2.443 | -25.9% | -30.8..-23.4% | 411,435 / 411,435 | +| layout-mask-index | psd-export | 18.200 | 18.397 | +1.1% | -0.1..+1.7% | 411,435 / 411,435 | -```sh -CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_PROFILE_RELEASE_DEBUG=0 CARGO_INCREMENTAL=0 nice -n 10 cargo test --release -p photocraft-io --lib --no-run -# Run the printed executable at normal priority: - benchmark_interleave --ignored --nocapture --test-threads=1 -``` +Real PSD exports remain byte-identical and imported layer/mask float samples match main. The committed literal previous-interleave oracle covers depths, bands, fills, truncation and inversion. -## Local validation +Current local checks: affected `pixels::` unit tests (five passed, one ignored manual benchmark); strict all-target IO Clippy; affected IO wasm32 check. All passed. Follow-up exports at float and 16-bit depth remain byte-identical to main; no synthetic timing test was run. + +Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. + +## Earlier split validation + +These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. - `cargo test -p photocraft-io --locked`: passed (617 passed, 6 ignored). - `cargo clippy -p photocraft-io --locked --all-targets -- -D warnings`: passed. From dd552f76b1fbd918c2a56a80300f874d50f0594b Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:33:01 +0200 Subject: [PATCH 24/34] docs(raster): document touched read helpers --- crates/raster/src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 2ebfde9c59..694cdb5751 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -239,6 +239,7 @@ impl Surface { decode_pixel(&self.format, &self.default_pixel) } + /// Decode the default pixel into fixed storage without allocating. fn default_samples(&self) -> [f32; 8] { let mut px = [0.0; 8]; for (i, v) in px.iter_mut().enumerate().take(self.channels()) { @@ -422,6 +423,7 @@ impl Surface { self.read_samples_into(r, out); } + /// Copy samples into a zero-initialized buffer sized for `r`. fn read_samples_into(&self, r: Rect, out: &mut [f32]) { let n = self.channels(); let w = r.width() as usize; @@ -1105,6 +1107,7 @@ pub fn is_hdr(sample: SampleType) -> bool { #[cfg(test)] mod tests { + /// Manually compare allocating reads with the previous implementation. #[test] #[ignore = "manual 24 MP release benchmark"] fn benchmark_sparse_reads() { @@ -1131,6 +1134,7 @@ mod tests { } } } + /// Previous allocating read path, retained as the bitwise-equivalence oracle. fn previous_read_region(surface: &Surface, r: Rect) -> Vec { let n = surface.channels(); let w = r.width() as usize; @@ -1289,6 +1293,7 @@ mod tests { } } + /// Compare sparse reads and converted accessors with the previous allocating path. #[test] fn zero_alloc_accessors_match_read_region() { for (fmt, default) in [ From 4d50e31efd32576b3b65b0a47b84e32b1db76d37 Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 13:43:19 +0200 Subject: [PATCH 25/34] perf(codecs): stop PNG candidates at the winning cost --- crates/codecs/src/codecs/png.rs | 6 ++++ docs/png-filter-selection-performance.md | 39 +++++++++++++++--------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/crates/codecs/src/codecs/png.rs b/crates/codecs/src/codecs/png.rs index 34ae84acc0..946f8949e8 100644 --- a/crates/codecs/src/codecs/png.rs +++ b/crates/codecs/src/codecs/png.rs @@ -523,6 +523,9 @@ fn filter_row(row: &[u8], prev: Option<&[u8]>, bpp: usize, scratch: &mut [u8], o _ => x.wrapping_sub(paeth(left(i), up(i), ul(i))), }; c += u64::from((scratch[i] as i8).unsigned_abs()); + if c >= best { + break; + } } if c < best { best = c; @@ -751,6 +754,9 @@ mod parallel_tests { let mut out = Vec::new(); filter_row(&[0; 16], None, 4, &mut [0; 16], &mut out); assert_eq!(out, vec![0; 17]); + out.clear(); + filter_row(&[1; 16], Some(&[0; 16]), 1, &mut [0; 16], &mut out); + assert_eq!(out, [vec![1, 1], vec![0; 15]].concat()); } #[test] diff --git a/docs/png-filter-selection-performance.md b/docs/png-filter-selection-performance.md index 1f7ffeab29..6abbaaa846 100644 --- a/docs/png-filter-selection-performance.md +++ b/docs/png-filter-selection-performance.md @@ -1,27 +1,36 @@ # PNG filter selection -Stop evaluating PNG filters when their partial cost cannot win. Filter choice and encoded bytes must remain identical. +The final inner loop stops as soon as candidate cost reaches `best`. Costs cannot decrease, and only a strict improvement replaces the winning filter, preserving tie order. The previous-filter oracle now also checks an immediate tie against Sub. -Photo PNG encoding improves, with identical streams. The small designs show little change because they use the existing serial PNG encoder. The previous filter-kernel percentages are not end-to-end results. +Measured on 2026-10-19 against frozen main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently for each branch. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1. Release O3, LTO off, 16 codegen units, debug off; builds/tests at nice 10 with warm caches. Timed operations run at normal priority without concurrent builds or profiling. Persistent processes alternate execution order after a warmup. Time change compares the two medians; paired bootstrap intervals from these small samples describe variation, not guarantees. -Measured on 2026-10-19 against main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently of the other splits. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1; release O3, LTO off, 16 codegen units, debug off. Builds used nice 10 and warm APFS-cloned caches; measurements used default priority without concurrent builds or profiling. Five alternating paired samples follow a warmup; confirmation and fix runs use nine pairs. Time change compares the two medians; intervals resample paired ratios. Negative time change means faster. Small differences are not automatically established improvements or regressions. +CC0 Pixls P1000475.RW2 supplies a 6000 x 4000 centre crop (24 MP, no resampling); IMG_4059.CR2 supplies the native 4000 x 3000 city photograph. U8/U16/F32 documents retain ProPhoto RGB; F32 derives from 16-bit development and is not native HDR. No generated noise, repeated ramps, enlarged charts or duplicated photo layers are timed. Source pins and attribution remain in the existing corpus. -The full-resolution CC0 Pixls photographs are P1000475.RW2 (24 MP foliage centre crop, no resampling) and IMG_4059.CR2 (12 MP city), each converted to U8/U16/F32 with the ProPhoto RGB profile. F32 derives from 16-bit development, not HDR capture. MIT psd-tools masks.psd supplies a 640 x 1394 web layout with 22 imported layers and three masks; mask-index.psd supplies a 1000 x 867 illustrated card with a mask. The sources and hashes are pinned by the existing corpus. These are the available authored layered files, not a large layered-photo corpus. No generated noise, repeating ramps, enlarged charts or duplicated photo layers are used. +Nine alternating samples compare main, the previous split and the final cutoff implementation. The four photo cases use the parallel encoder; the two MIT psd-tools designs use the unchanged serial encoder. The illustrated card has a separate nine-pair confirmation, shown in the table. Input conversion, hashes and decoded-pixel checks are outside timers. Every PNG is byte-identical to main and decodes to identical pixels. -The shared harness times in-memory operations. Input loading, image conversion, thumbnail rendering, hashes and equivalence checks are outside timers. Every save uses a fresh PcraftWriter and a real rendered thumbnail. Common reads use main-encoded files; own-output reads are separate. PSD exports use ZIP merged images at U8/U16, Raw merged images at F32, and normal RLE layer channels at U8/U16 / ZIP prediction at F32. Results do not measure filesystem throughput or browser performance. +| Document | Operation | Main ms | Branch ms | Change | Paired 95% interval | +|---|---|---:|---:|---:|---:| +| panasonic-8 | png-encode | 358.588 | 337.725 | -5.8% | -6.6..-5.2% | +| panasonic-16 | png-encode | 334.253 | 301.130 | -9.9% | -10.8..-9.3% | +| canon-8 | png-encode | 179.462 | 168.651 | -6.0% | -8.4..-4.0% | +| canon-16 | png-encode | 168.310 | 150.325 | -10.7% | -17.5..-9.4% | +| layout-masks | png-encode | 4.035 | 4.020 | -0.4% | -1.4..+0.8% | +| layout-mask-index | png-encode (confirm) | 10.808 | 10.674 | -1.2% | -2.5..+0.7% | -| Document | Operation | Main ms | Branch ms | Time change | Paired 95% interval | Main / branch bytes | -|---|---|---:|---:|---:|---:|---:| -| panasonic-8 | png-encode | 358.725 | 346.020 | -3.5% | -7.0..-0.9% | 24,569,965 / 24,569,965 | -| panasonic-16 | png-encode | 338.106 | 296.860 | -12.2% | -12.3..-9.7% | 111,583,441 / 111,583,441 | -| canon-8 | png-encode | 178.675 | 169.289 | -5.3% | -35.0..-2.7% | 13,720,268 / 13,720,268 | -| canon-16 | png-encode | 162.107 | 145.356 | -10.3% | -12.2..+4.6% | 58,279,529 / 58,279,529 | -| layout-masks | png-encode | 4.037 | 3.986 | -1.3% | -3.3..+1.9% | 42,842 / 42,842 | -| layout-mask-index | png-encode | 11.343 | 11.404 | +0.5% | -0.0..+2.2% | 115,229 / 115,229 | +| Document | Previous split ms | Final ms | Cutoff-only change | +|---|---:|---:|---:| +| panasonic-8 | 339.785 | 337.725 | -0.6% | +| panasonic-16 | 300.287 | 301.130 | +0.3% | +| canon-8 | 172.739 | 168.651 | -2.4% | +| canon-16 | 150.183 | 150.325 | +0.1% | +| layout-masks | 4.019 | 4.020 | +0.0% | +| layout-mask-index | 10.674 | 10.674 | -0.0% | -The real-image PNG streams match main byte for byte and decode to identical pixels. The committed previous-filter oracle also covers bytes-per-pixel layouts, early exits, zero-cost rows and ties. +The cutoff-only photo intervals cross zero: these complete-image measurements do not establish an additional speedup over the previous split. The serial card initially measured +2.1% against the previous split; its independent confirmation is neutral (-0.0%, interval -1.1..+1.2%). The updated table reports the final implementation against main without relying on the earlier kernel-only promise. -Local raw evidence and the shared harness: `.local/perf-real-261019/` in the repository checkout (ignored). This comparison supersedes the earlier synthetic performance table. Small synthetic unit fixtures remain correctness checks; ignored synthetic timing tests were not run. +Current affected checks: seven PNG unit tests passed, one ignored manual benchmark; strict all-target codec Clippy, affected codec WASM check and formatting passed. No synthetic timing test was run. + +Harness, raw observations, exact inputs and binary hashes: `.local/perf-followup-261019/` (ignored local evidence). Previous flat-photo and authored-design results remain in `.local/perf-real-261019/`. Nothing was pushed and no PR was changed. ## Earlier split validation From 83aff80f35b06dd4a847ffcfce7d6d50bb724eef Mon Sep 17 00:00:00 2001 From: Rene Leonhardt <65483435+reneleonhardt@users.noreply.github.com> Date: Mon, 19 Oct 2026 17:19:18 +0200 Subject: [PATCH 26/34] fix(raster): support sample counts beyond stack capacity --- crates/raster/src/lib.rs | 61 ++++++++++++++++++++++++++++++++-------- 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 694cdb5751..2e3dc53811 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -117,6 +117,16 @@ pub struct Surface { tiles: BTreeMap>, } +/// Use stack storage when it fits, otherwise reuse a dynamically sized sample buffer. +fn sample_buffer<'a>(channels: usize, stack: &'a mut [f32], heap: &'a mut Vec) -> &'a mut [f32] { + if let Some(samples) = stack.get_mut(..channels) { + samples + } else { + heap.resize(channels, 0.0); + heap + } +} + /// Tiles of one pixel value met while moving a surface ([`Surface::translated`]): each scanned /// once, and one tile kept per value so the targets share it. #[derive(Default)] @@ -239,10 +249,10 @@ impl Surface { decode_pixel(&self.format, &self.default_pixel) } - /// Decode the default pixel into fixed storage without allocating. - fn default_samples(&self) -> [f32; 8] { - let mut px = [0.0; 8]; - for (i, v) in px.iter_mut().enumerate().take(self.channels()) { + /// Decode the default pixel, using dynamic storage only when the stack buffer is too small. + fn default_samples<'a>(&self, stack: &'a mut [f32], heap: &'a mut Vec) -> &'a mut [f32] { + let px = sample_buffer(self.channels(), stack, heap); + for (i, v) in px.iter_mut().enumerate() { *v = read_sample(&self.default_pixel, self.format.sample, i); } px @@ -427,8 +437,9 @@ impl Surface { fn read_samples_into(&self, r: Rect, out: &mut [f32]) { let n = self.channels(); let w = r.width() as usize; - let dp = self.default_samples(); - let dp = &dp[..n]; + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let dp = self.default_samples(&mut stack, &mut heap); let zero = self.default_pixel.iter().all(|&b| b == 0); for tc in r.tiles() { let tr = tc.rect().intersect(&r); @@ -467,7 +478,10 @@ impl Surface { debug_assert_eq!(out.len(), w * r.height() as usize); let fmt = self.format; let n = fmt.channels(); - let dp = to_rgba(&fmt, &self.default_samples()); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let px = self.default_samples(&mut stack, &mut heap); + let dp = to_rgba(&fmt, px); for tc in r.tiles() { let tr = tc.rect().intersect(&r); let tile = self.tiles.get(&tc); @@ -511,12 +525,11 @@ impl Surface { } } _ => { - let mut px = [0.0f32; 8]; for (i, d) in dst.iter_mut().enumerate() { - for (c, v) in px.iter_mut().enumerate().take(n) { + for (c, v) in px.iter_mut().enumerate() { *v = read_sample(&t.data, fmt.sample, base + i * n + c); } - *d = to_rgba(&fmt, &px[..n]); + *d = to_rgba(&fmt, px); } } } @@ -532,7 +545,9 @@ impl Surface { let fmt = self.format; let rgba8 = matches!((fmt.mode, fmt.sample, fmt.alpha), (ColorMode::Rgb, SampleType::U8, true)); let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let dp = to_rgba(&fmt, &self.default_samples()); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let dp = to_rgba(&fmt, self.default_samples(&mut stack, &mut heap)); let dp8 = [q(dp[0]), q(dp[1]), q(dp[2]), q(dp[3])]; let mut row = Vec::new(); for tc in r.tiles() { @@ -1293,6 +1308,24 @@ mod tests { } } + /// Sample counts above the stack capacity use writable storage without truncating channels. + #[test] + fn sample_buffer_keeps_stack_fast_path_and_supports_dynamic_channels() { + for channels in [1, 8, 9, 32] { + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + let samples = sample_buffer(channels, &mut stack, &mut heap); + assert_eq!(samples.len(), channels); + samples.fill(0.25); + if channels <= stack.len() { + assert!(heap.is_empty()); + assert_eq!(&stack[..channels], vec![0.25; channels]); + } else { + assert_eq!(heap, vec![0.25; channels]); + } + } + } + /// Compare sparse reads and converted accessors with the previous allocating path. #[test] fn zero_alloc_accessors_match_read_region() { @@ -1310,6 +1343,12 @@ mod tests { .flat_map(|fmt| [0.0, 0.25, -0.0].map(|default| (fmt, default))) { let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]); + let mut stack = [0.0; 8]; + let mut heap = Vec::new(); + for capacity in [0, stack.len()] { + let decoded = s.default_samples(&mut stack[..capacity], &mut heap); + assert!(decoded.iter().map(|v| v.to_bits()).eq(s.default_pixel().into_iter().map(f32::to_bits))); + } let r = Rect::new(-300, -20, 300, 40); for (i, (x, y)) in [(-299, -19), (0, 0), (255, 39), (256, 10), (299, 0)].into_iter().enumerate() { let px: Vec = (0..fmt.channels()).map(|c| ((i * 3 + c) % 5) as f32 / 4.0).collect(); From b8e856dffe835d9589b98f4c9bf27c9d0d3677f9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 17:18:46 +0000 Subject: [PATCH 27/34] Integration: #7022 write_region stays serial; the text rasterizer uses the parallel variant --- crates/raster/src/lib.rs | 61 ++++++++++++++++++++++++++++++--- crates/text/src/render.rs | 2 +- docs/text-raster-performance.md | 9 +++-- 3 files changed, 63 insertions(+), 9 deletions(-) diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 1393a8236e..958ab38b53 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -641,16 +641,34 @@ impl Surface { out } - /// Write interleaved normalised floats into a rectangle. + /// Write interleaved normalised floats into a rectangle, on the calling thread. + /// + /// This never enters Rayon, so it is safe inside a `OnceLock` initializer or any other + /// section that must not run another Rayon job on its stack. [`Surface::write_region_par`] + /// writes the same bytes on all cores. pub fn write_region(&mut self, r: Rect, data: &[f32]) { let n = self.channels(); let w = r.width() as usize; assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); let sample = self.format.sample; - // Each tile's own span of `data` is converted on its own: the tiles are disjoint, so - // converting them in any order (and on any thread) writes exactly the same bytes. - // `take_tiles` reserves the whole result before removing anything, and gives the missing - // tiles as one shared default-filled tile, copied per tile by `Arc::make_mut` below. + for tc in r.tiles() { + write_tile(self.tile_mut(tc), tc, r, data, w, n, sample); + } + } + + /// [`Surface::write_region`] with the tiles converted on all cores (serially on the web). + /// + /// This enters Rayon: while it waits for its tiles, the calling worker may run any other + /// queued Rayon job. Callers inside a `OnceLock` initializer or another section that must + /// not do that use [`Surface::write_region`]. + pub fn write_region_par(&mut self, r: Rect, data: &[f32]) { + let n = self.channels(); + let w = r.width() as usize; + assert_eq!(data.len(), w * r.height() as usize * n, "region data length mismatch"); + let sample = self.format.sample; + // The tiles are disjoint, so converting them in any order (and on any thread) writes + // exactly the same bytes. `take_tiles` gives the missing tiles as one shared + // default-filled tile, copied per tile by `Arc::make_mut` in `convert_tiles`. let mut tiles = self.take_tiles(r); convert_tiles(&mut tiles, r, data, w, n, sample); self.put_tiles(tiles); @@ -1310,19 +1328,52 @@ mod tests { .collect(); let snapshot = actual.clone(); let snapshot_bytes = snapshot.to_interleaved(rect.inflate(1)); + let mut par = actual.clone(); actual.write_region(rect, &data); + par.write_region_par(rect, &data); write_region_reference(&mut expected, rect, &data); assert_eq!(actual, expected, "{fmt:?}, {rect:?}"); + assert_eq!(par, expected, "parallel {fmt:?}, {rect:?}"); assert_eq!(snapshot.to_interleaved(rect.inflate(1)), snapshot_bytes, "COW snapshot changed"); // Repeat against already materialised, unshared tiles too. actual.write_region(rect, &data); + par.write_region_par(rect, &data); assert_eq!(actual, expected); + assert_eq!(par, expected); } } } } } + /// Mask builds call `write_region` inside a `OnceLock` initializer, where entering Rayon can + /// run another tile's job that waits on the same lock. With every global worker held, a write + /// that queued work on Rayon could not finish. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn write_region_does_not_enter_rayon() { + use std::sync::{Barrier, mpsc}; + let workers = rayon::current_num_threads(); + let held = Arc::new(Barrier::new(workers + 1)); + let release = Arc::new(Barrier::new(workers + 1)); + let (h, rel) = (held.clone(), release.clone()); + rayon::spawn_broadcast(move |_| { + h.wait(); + rel.wait(); + }); + held.wait(); + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let r = Rect::new(0, 0, 2 * TILE_SIZE, 2 * TILE_SIZE); + let mut s = Surface::new(PixelFormat::RGBA8); + s.write_region(r, &vec![0.5; (r.width() * r.height() * 4) as usize]); + tx.send(()).ok(); + }); + let done = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); + release.wait(); + assert!(done, "write_region waited on the Rayon pool"); + } + #[test] fn from_rgba_into_matches_from_rgba() { for fmt in [PixelFormat::RGBA8, PixelFormat::GRAY8, PixelFormat::GRAYA8, PixelFormat::CMYKA8, PixelFormat::new(ColorMode::Lab, SampleType::F32, true)] { diff --git a/crates/text/src/render.rs b/crates/text/src/render.rs index 5cf6baea12..39eef20757 100644 --- a/crates/text/src/render.rs +++ b/crates/text/src/render.rs @@ -283,7 +283,7 @@ pub fn rasterize_warped(layout: &TextLayout, transform: &Affine, format: PixelFo } // Unpremultiply. unpremultiply(&mut acc, n, stride, format.sample); - surface.write_region(rect, &acc); + surface.write_region_par(rect, &acc); surface.prune(); Rendered { surface, rect } } diff --git a/docs/text-raster-performance.md b/docs/text-raster-performance.md index 87ccdf849f..5bc446ead1 100644 --- a/docs/text-raster-performance.md +++ b/docs/text-raster-performance.md @@ -25,8 +25,10 @@ reads and writes only its own slots. ## What runs in parallel now -`composite`, `unpremultiply` and the tile conversion of `write_region` run on all cores (rayon, -native only; the web build keeps the serial loops, since wasm has no threads). Nothing about them +`composite`, `unpremultiply` and the tile conversion run on all cores (rayon, native only; the web +build keeps the serial loops, since wasm has no threads). The rasterizer writes its tiles with +`Surface::write_region_par`; `Surface::write_region` stays serial, because mask builds call it inside +a `OnceLock` initializer, which must not enter rayon. Nothing about them is order-dependent, so each pixel still sees the same operations on the same inputs — the pixels are identical, not merely close. @@ -37,7 +39,8 @@ are identical, not merely close. `crates/text/src/tests.rs::parallel_raster_matches_a_single_thread` renders the shapes the pipeline can take (plain, faux bold italic, no antialias, wide gamut, a wrapping paragraph box; 8/16/32-bit) on a one-thread pool and on the default pool and compares the surfaces; `crates/raster`'s existing -region proptests compare `write_region` against its serial reference implementation, tile for tile. +`region_writes_match_scalar_bytes_for_every_format` compares `write_region` and `write_region_par` +against a scalar reference implementation, tile for tile. ## What stays on one thread, and why From 3f509f06ed585815310ba18ed8dd4efb0cfd7fc7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 18:01:48 +0000 Subject: [PATCH 28/34] Integration: regenerate docs/scorecard.md --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index b320028936..c4b53a20f8 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 24 | 58 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 19 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 | | [Tools](#tools) | 33 | 11 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 168 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 169 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -179,7 +179,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 25 of 168** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 25 of 169** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. From 46f7e2422e7c8636df75c2c2cd1683b41ad1441c Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 19 Oct 2026 18:41:15 +0000 Subject: [PATCH 29/34] Integration: drop #7690's benchmark report, as #7690 did before it merged --- docs/png-filter-selection-performance.md | 43 ------------------------ 1 file changed, 43 deletions(-) delete mode 100644 docs/png-filter-selection-performance.md diff --git a/docs/png-filter-selection-performance.md b/docs/png-filter-selection-performance.md deleted file mode 100644 index 6abbaaa846..0000000000 --- a/docs/png-filter-selection-performance.md +++ /dev/null @@ -1,43 +0,0 @@ -# PNG filter selection - -The final inner loop stops as soon as candidate cost reaches `best`. Costs cannot decrease, and only a strict improvement replaces the winning filter, preserving tie order. The previous-filter oracle now also checks an immediate tie against Sub. - -Measured on 2026-10-19 against frozen main `d95fdf3181c01ad41e95456091a394b105a9afb2`, independently for each branch. Apple M4 Max, 16 CPUs, 128 GiB, macOS arm64, rustc 1.99.1. Release O3, LTO off, 16 codegen units, debug off; builds/tests at nice 10 with warm caches. Timed operations run at normal priority without concurrent builds or profiling. Persistent processes alternate execution order after a warmup. Time change compares the two medians; paired bootstrap intervals from these small samples describe variation, not guarantees. - -CC0 Pixls P1000475.RW2 supplies a 6000 x 4000 centre crop (24 MP, no resampling); IMG_4059.CR2 supplies the native 4000 x 3000 city photograph. U8/U16/F32 documents retain ProPhoto RGB; F32 derives from 16-bit development and is not native HDR. No generated noise, repeated ramps, enlarged charts or duplicated photo layers are timed. Source pins and attribution remain in the existing corpus. - -Nine alternating samples compare main, the previous split and the final cutoff implementation. The four photo cases use the parallel encoder; the two MIT psd-tools designs use the unchanged serial encoder. The illustrated card has a separate nine-pair confirmation, shown in the table. Input conversion, hashes and decoded-pixel checks are outside timers. Every PNG is byte-identical to main and decodes to identical pixels. - -| Document | Operation | Main ms | Branch ms | Change | Paired 95% interval | -|---|---|---:|---:|---:|---:| -| panasonic-8 | png-encode | 358.588 | 337.725 | -5.8% | -6.6..-5.2% | -| panasonic-16 | png-encode | 334.253 | 301.130 | -9.9% | -10.8..-9.3% | -| canon-8 | png-encode | 179.462 | 168.651 | -6.0% | -8.4..-4.0% | -| canon-16 | png-encode | 168.310 | 150.325 | -10.7% | -17.5..-9.4% | -| layout-masks | png-encode | 4.035 | 4.020 | -0.4% | -1.4..+0.8% | -| layout-mask-index | png-encode (confirm) | 10.808 | 10.674 | -1.2% | -2.5..+0.7% | - -| Document | Previous split ms | Final ms | Cutoff-only change | -|---|---:|---:|---:| -| panasonic-8 | 339.785 | 337.725 | -0.6% | -| panasonic-16 | 300.287 | 301.130 | +0.3% | -| canon-8 | 172.739 | 168.651 | -2.4% | -| canon-16 | 150.183 | 150.325 | +0.1% | -| layout-masks | 4.019 | 4.020 | +0.0% | -| layout-mask-index | 10.674 | 10.674 | -0.0% | - -The cutoff-only photo intervals cross zero: these complete-image measurements do not establish an additional speedup over the previous split. The serial card initially measured +2.1% against the previous split; its independent confirmation is neutral (-0.0%, interval -1.1..+1.2%). The updated table reports the final implementation against main without relying on the earlier kernel-only promise. - -Current affected checks: seven PNG unit tests passed, one ignored manual benchmark; strict all-target codec Clippy, affected codec WASM check and formatting passed. No synthetic timing test was run. - -Harness, raw observations, exact inputs and binary hashes: `.local/perf-followup-261019/` (ignored local evidence). Previous flat-photo and authored-design results remain in `.local/perf-real-261019/`. Nothing was pushed and no PR was changed. - -## Earlier split validation - -These checks passed when the split was prepared; they were not all rerun for this benchmark review. Current affected checks are listed above where production code changed. - -- `cargo test -p photocraft-codecs --locked`: passed (782 passed, 4 ignored). -- `cargo clippy -p photocraft-codecs --locked --all-targets -- -D warnings`: passed. -- `cargo xtask layers`: passed. -- `cargo check -p photocraft-codecs --locked --target wasm32-unknown-unknown`: passed. -- `cargo xtask test-corpus -p codecs`: passed (796 passed, 4 ignored). From cd79a5a9e892ab21c302fcbffcbcdd260c592703 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Mon, 19 Oct 2026 22:19:11 -0400 Subject: [PATCH 30/34] Release 0.11.0 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 62 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b5c6a4571e..03b1431ea1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4630,7 +4630,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.10.0" +version = "0.11.0" dependencies = [ "arboard", "async-io", @@ -4675,7 +4675,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.10.0" +version = "0.11.0" dependencies = [ "crc32fast", "flate2", @@ -4685,7 +4685,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4698,7 +4698,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.10.0" +version = "0.11.0" dependencies = [ "base64 0.22.1", "cap-std", @@ -4721,7 +4721,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-automation", "photocraft-codecs", @@ -4735,7 +4735,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.10.0" +version = "0.11.0" dependencies = [ "moxcms", "rayon", @@ -4743,7 +4743,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.10.0" +version = "0.11.0" dependencies = [ "exr", "flate2", @@ -4764,7 +4764,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-cms", "serde", @@ -4772,7 +4772,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.10.0" +version = "0.11.0" dependencies = [ "criterion", "photocraft-color", @@ -4787,7 +4787,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4798,7 +4798,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.10.0" +version = "0.11.0" dependencies = [ "blake3", "craft-print", @@ -4835,7 +4835,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.10.0" +version = "0.11.0" dependencies = [ "blake3", "crc32fast", @@ -4858,14 +4858,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.10.0" +version = "0.11.0" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.10.0" +version = "0.11.0" dependencies = [ "half", "log", @@ -4882,14 +4882,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.10.0" +version = "0.11.0" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.10.0" +version = "0.11.0" dependencies = [ "blake3", "craft-docpath", @@ -4919,18 +4919,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.10.0" +version = "0.11.0" [[package]] name = "photocraft-ops" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4941,7 +4941,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4956,7 +4956,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.10.0" +version = "0.11.0" dependencies = [ "flate2", "photocraft-psd", @@ -4967,7 +4967,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4978,7 +4978,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.10.0" +version = "0.11.0" dependencies = [ "flate2", "image", @@ -4993,7 +4993,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.10.0" +version = "0.11.0" dependencies = [ "block2 0.6.2", "objc2 0.6.4", @@ -5005,7 +5005,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.10.0" +version = "0.11.0" dependencies = [ "memory-stats", "photocraft-color", @@ -5016,7 +5016,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.10.0" +version = "0.11.0" dependencies = [ "flate2", "parley", @@ -5031,7 +5031,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.10.0" +version = "0.11.0" dependencies = [ "base64 0.22.1", "craft-print", @@ -5073,7 +5073,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.10.0" +version = "0.11.0" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5084,7 +5084,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.10.0" +version = "0.11.0" dependencies = [ "eframe", "egui", @@ -5106,7 +5106,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.10.0" +version = "0.11.0" dependencies = [ "flate2", "js-sys", @@ -8693,7 +8693,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.10.0" +version = "0.11.0" dependencies = [ "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 3f8dbb0a72..718c87f037 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.10.0" +version = "0.11.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 8ede07b096af6d3afbfcb80659338fbfbd0c7fba Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Tue, 20 Oct 2026 08:47:42 -0400 Subject: [PATCH 31/34] Format: build on FreeBSD (rustix has no xattr calls there) The 0.11.0 release's FreeBSD job failed: copy_xattrs used rustix's fsetxattr/flistxattr/fgetxattr, which rustix offers only on Linux, Android and Apple systems. The real copy is now gated to those, and other Unix systems get a no-op copy_xattrs, as Windows has. The xattr tests are gated the same way; the Unix mode test now also checks that no temporary file is left behind. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/workspace.rs | 2 +- crates/format/src/atomic/meta.rs | 21 ++++++++++++++------- crates/format/src/atomic/meta/tests.rs | 3 ++- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 77f728ce04..99dedac77d 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -591,7 +591,7 @@ mod tests { /// #7095: replacing a file through the automation path keeps the old file's extended /// attributes, the same as a save through `atomic_write` does. - #[cfg(unix)] + #[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] #[test] fn write_keeps_the_replaced_files_extended_attributes() { #[cfg(target_os = "macos")] diff --git a/crates/format/src/atomic/meta.rs b/crates/format/src/atomic/meta.rs index 6c7cfbc21e..10008faa9f 100644 --- a/crates/format/src/atomic/meta.rs +++ b/crates/format/src/atomic/meta.rs @@ -32,17 +32,17 @@ use std::os::fd::BorrowedFd; /// Largest attribute-name list [`copy_xattrs`] will read. Names are short; a file with a /// megabyte of them is not something a save should spend memory on. -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] const MAX_XATTR_NAMES: usize = 1 << 20; /// Largest single attribute value [`copy_xattrs`] will carry over. Finder tags and `user.*` /// attributes are tens of bytes; a resource fork can be large, and past this it is not worth /// holding a copy of it in memory during a save. -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] const MAX_XATTR_VALUE: usize = 16 << 20; /// First read size for an attribute list or value; grown on `ERANGE`. -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] const XATTR_CHUNK: usize = 4 << 10; /// Copy, best effort, everything [`crate::atomic::atomic_write`] should carry from the file it @@ -92,7 +92,7 @@ fn copy_xattrs_at(from: &Path, to: &Path) -> io::Result<()> { /// `com.apple.rootless` on macOS and `security.*` on Linux belong to the system and refuse to /// be written by an ordinary process, and failing a document save over one would be absurd. /// `Err` means the attribute *list* could not be read, so nothing was copied. -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] pub fn copy_xattrs(from: BorrowedFd<'_>, to: BorrowedFd<'_>) -> io::Result<()> { use rustix::fs::{XattrFlags, fsetxattr}; @@ -106,9 +106,16 @@ pub fn copy_xattrs(from: BorrowedFd<'_>, to: BorrowedFd<'_>) -> io::Result<()> { Ok(()) } +/// [`copy_xattrs`] where rustix offers no extended-attribute calls (FreeBSD and the other BSDs): +/// nothing is copied, as on Windows. +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))))] +pub fn copy_xattrs(_from: BorrowedFd<'_>, _to: BorrowedFd<'_>) -> io::Result<()> { + Ok(()) +} + /// Attributes that describe how the *old* file's bytes are stored rather than anything about /// the document, and so must never be pinned onto a file holding different bytes. -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] fn skip_xattr(name: &[u8]) -> bool { // `com.apple.decmpfs` marks a file whose data lives compressed inside the attribute itself. // The kernel hides it from a plain `listxattr` and refuses to set it, but a file claiming @@ -117,7 +124,7 @@ fn skip_xattr(name: &[u8]) -> bool { } /// The NUL-separated attribute names of `fd`. -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] fn list_xattrs(fd: BorrowedFd<'_>) -> io::Result> { let mut buf = vec![0u8; XATTR_CHUNK]; loop { @@ -137,7 +144,7 @@ fn list_xattrs(fd: BorrowedFd<'_>) -> io::Result> { /// The value of one attribute, or `None` if it cannot be read or is larger than /// [`MAX_XATTR_VALUE`]. A missing value is normal: another process may remove an attribute /// between the listing and the read. -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] fn read_xattr(fd: BorrowedFd<'_>, name: &[u8]) -> Option> { let mut buf = vec![0u8; XATTR_CHUNK]; loop { diff --git a/crates/format/src/atomic/meta/tests.rs b/crates/format/src/atomic/meta/tests.rs index 5c8f08c6ba..834e87e66e 100644 --- a/crates/format/src/atomic/meta/tests.rs +++ b/crates/format/src/atomic/meta/tests.rs @@ -36,7 +36,7 @@ fn assert_no_temp(dir: &Path) { // ---------------------------------------------------------------- extended attributes (Unix) -#[cfg(unix)] +#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] mod xattrs { use super::*; @@ -164,6 +164,7 @@ fn replacing_a_file_keeps_its_mode() { atomic_write(&p, b"second").unwrap(); assert_eq!(std::fs::metadata(&p).unwrap().permissions().mode() & 0o777, 0o600); + assert_no_temp(&d.0); } // ----------------------------------------------------------------------------- ACL (macOS) From 46e538b3a2bacb533e89c7a30a99bbf2d91c3381 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Tue, 20 Oct 2026 08:47:46 -0400 Subject: [PATCH 32/34] Release 0.11.1 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 62 +++++++++++++++++++++++++++--------------------------- Cargo.toml | 2 +- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 03b1431ea1..6b5a7bbf9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4630,7 +4630,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.11.0" +version = "0.11.1" dependencies = [ "arboard", "async-io", @@ -4675,7 +4675,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.11.0" +version = "0.11.1" dependencies = [ "crc32fast", "flate2", @@ -4685,7 +4685,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4698,7 +4698,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.11.0" +version = "0.11.1" dependencies = [ "base64 0.22.1", "cap-std", @@ -4721,7 +4721,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-automation", "photocraft-codecs", @@ -4735,7 +4735,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.11.0" +version = "0.11.1" dependencies = [ "moxcms", "rayon", @@ -4743,7 +4743,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.11.0" +version = "0.11.1" dependencies = [ "exr", "flate2", @@ -4764,7 +4764,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-cms", "serde", @@ -4772,7 +4772,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.11.0" +version = "0.11.1" dependencies = [ "criterion", "photocraft-color", @@ -4787,7 +4787,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4798,7 +4798,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.11.0" +version = "0.11.1" dependencies = [ "blake3", "craft-print", @@ -4835,7 +4835,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.11.0" +version = "0.11.1" dependencies = [ "blake3", "crc32fast", @@ -4858,14 +4858,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.11.0" +version = "0.11.1" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.11.0" +version = "0.11.1" dependencies = [ "half", "log", @@ -4882,14 +4882,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.11.0" +version = "0.11.1" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.11.0" +version = "0.11.1" dependencies = [ "blake3", "craft-docpath", @@ -4919,18 +4919,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.11.0" +version = "0.11.1" [[package]] name = "photocraft-ops" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4941,7 +4941,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4956,7 +4956,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.11.0" +version = "0.11.1" dependencies = [ "flate2", "photocraft-psd", @@ -4967,7 +4967,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4978,7 +4978,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.11.0" +version = "0.11.1" dependencies = [ "flate2", "image", @@ -4993,7 +4993,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.11.0" +version = "0.11.1" dependencies = [ "block2 0.6.2", "objc2 0.6.4", @@ -5005,7 +5005,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.11.0" +version = "0.11.1" dependencies = [ "memory-stats", "photocraft-color", @@ -5016,7 +5016,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.11.0" +version = "0.11.1" dependencies = [ "flate2", "parley", @@ -5031,7 +5031,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.11.0" +version = "0.11.1" dependencies = [ "base64 0.22.1", "craft-print", @@ -5073,7 +5073,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.11.0" +version = "0.11.1" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5084,7 +5084,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.11.0" +version = "0.11.1" dependencies = [ "eframe", "egui", @@ -5106,7 +5106,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.11.0" +version = "0.11.1" dependencies = [ "flate2", "js-sys", @@ -8693,7 +8693,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.11.0" +version = "0.11.1" dependencies = [ "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 718c87f037..b3f49802e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/photocraft", "apps/photocraft-cli", "xtask"] [workspace.package] -version = "0.11.0" +version = "0.11.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 9b9643764f3fb77d9f0e48d7510983ae50621e11 Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Tue, 20 Oct 2026 11:38:22 -0400 Subject: [PATCH 33/34] Skip CodeRabbit reviews on Dependabot PRs (#7991) Adds .coderabbit.yaml so CodeRabbit no longer reviews or comments on PRs opened by dependabot[bot]. Co-authored-by: Claude Opus 5.5 --- .coderabbit.yaml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .coderabbit.yaml diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000..2408084cf9 --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,6 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +reviews: + auto_review: + # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. + ignore_usernames: + - "dependabot[bot]" From 872748fb5b2a53e09dd4e385e31968d985c0515b Mon Sep 17 00:00:00 2001 From: Guillem Hermida <66697068+guillehr2@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:02:39 +0200 Subject: [PATCH 34/34] =?UTF-8?q?Codecs:=20save=20DDS=20textures,=20uncomp?= =?UTF-8?q?ressed=20or=20BC1=E2=80=93BC3,=20with=20optional=20mipmaps=20(#?= =?UTF-8?q?1327)=20(#5993)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DDS textures can now be saved, not just opened: uncompressed (BGRA, BGRX, L8, A8L8; lossless) or BC1/BC2/BC3 (DXT1/3/5) from a clean-room block encoder, with an optional box-filtered mip chain, in the legacy header. Save As and Save a Copy ask with DDS Options; scripts pass `ddsCompression`/`ddsMipmaps` (file commands, control `app.save`, RPC `doc.save`, MCP `doc_save`/`doc_export`), and the CLI takes `--dds-compression`/`--dds-mipmaps`. Targa and DDS answers travel together as `FormatChoices` through the Save As flow. Review follow-ups: - File › Save behind DDS or Targa Options records a plain Save with its answer, and replaying `file.save` applies it (#3531). - The block encoder finds the principal axis from every channel, so a channel that varies on its own can't hide the others' variation. - DDS joins the shared round-trip suite; the header is built before the output buffer is allocated. - Enter on a focused Cancel in DDS, Targa or TIFF Options cancels instead of saving. --- apps/photocraft-cli/src/lib.rs | 28 +- apps/photocraft-cli/tests/cli.rs | 33 ++ apps/photocraft/src/services.rs | 4 +- book/src/formats/raster-formats.md | 1 + contributors/people.toml | 4 + crates/automation/src/rpc.rs | 1 + crates/automation/src/server.rs | 21 +- crates/automation/tests/mcp.rs | 39 ++ crates/codecs/README.md | 12 +- crates/codecs/src/codecs/dds.rs | 311 +++++++++++++-- crates/codecs/src/codecs/dds_bc.rs | 368 +++++++++++++++++ crates/codecs/src/codecs/mod.rs | 1 + crates/codecs/src/fidelity.rs | 9 +- crates/codecs/src/format.rs | 10 +- crates/codecs/src/lib.rs | 6 +- crates/codecs/src/options.rs | 58 +++ crates/codecs/tests/dds.rs | 9 +- crates/codecs/tests/dds_write.rs | 372 ++++++++++++++++++ crates/codecs/tests/roundtrip.rs | 3 + crates/engine/src/file_cmds.rs | 51 ++- crates/engine/src/file_cmds/tests.rs | 47 +++ crates/io/src/lib.rs | 2 +- crates/ui-egui/examples/snapshot.rs | 1 + crates/ui-egui/src/control.rs | 37 +- crates/ui-egui/src/dds_options_ui.rs | 148 +++++++ crates/ui-egui/src/discard_ui.rs | 3 + .../ui-egui/src/discard_ui/tests/dds_tests.rs | 217 ++++++++++ .../src/discard_ui/tests/targa_tests.rs | 43 ++ .../src/discard_ui/tests/tiff_tests.rs | 7 +- crates/ui-egui/src/disk_change_prompt.rs | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 5 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 5 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 5 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 5 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 5 + crates/ui-egui/src/i18n/sr.tsv | 4 + crates/ui-egui/src/i18n/tr.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 5 + crates/ui-egui/src/i18n/vi.tsv | 5 + crates/ui-egui/src/i18n/zh-hans.tsv | 5 + crates/ui-egui/src/i18n/zh-hant.tsv | 5 + crates/ui-egui/src/lib.rs | 160 +++++--- crates/ui-egui/src/menus.rs | 15 +- crates/ui-egui/src/targa_options_ui.rs | 13 +- crates/ui-egui/src/tiff_options_ui.rs | 3 +- crates/ui-egui/src/view_cmds.rs | 26 +- docs/control-protocol.md | 6 +- docs/file-format-parity.md | 5 +- 57 files changed, 2013 insertions(+), 156 deletions(-) create mode 100644 crates/codecs/src/codecs/dds_bc.rs create mode 100644 crates/codecs/tests/dds_write.rs create mode 100644 crates/ui-egui/src/dds_options_ui.rs create mode 100644 crates/ui-egui/src/discard_ui/tests/dds_tests.rs diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs index 03001ab02d..0e3429d074 100644 --- a/apps/photocraft-cli/src/lib.rs +++ b/apps/photocraft-cli/src/lib.rs @@ -15,19 +15,21 @@ pub const USAGE: &str = "\ photocraft-cli: headless PhotoCraft USAGE: - photocraft-cli convert [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] + photocraft-cli convert [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] Convert between formats (.pcraft, .psd, .png, .jpg, .tif, .webp, .exr, …). TIFF output is flat unless --tiff-layers keeps the layers (Photoshop layer data). --quality sets the JPEG or WebP quality; a WebP written with a quality is lossy, without one lossless. --tga-bits sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none. Without it: 32 with an alpha channel or transparency, else 24. --dpx-bits sets a DPX's bits per sample. Without it: 8 for an 8-bit document, else 16. + --dds-compression sets a DDS texture's compression: none (uncompressed, the default), bc1 + (DXT1: alpha on or off), bc2 (DXT3) or bc3 (DXT5). --dds-mipmaps also writes the full mip chain. photocraft-cli info [--compact] Print the document as JSON (size, mode, depth, layer tree). - photocraft-cli run ( | --new ) --cmd [--params ] [--cmd …] [--out ] [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] + photocraft-cli run ( | --new ) --cmd [--params ] [--cmd …] [--out ] [--format ] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] Open a file, run engine commands in order, save the result. Each --params applies to the preceding --cmd. Prints each command's JSON result. - photocraft-cli batch --actions [--action ] --in --out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] + photocraft-cli batch --actions [--action ] --in --out [--format ] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>] [--dds-compression ] [--dds-mipmaps] Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is a set: its action --action names plays, as below. JSON steps are [id, params] pairs, {\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them @@ -69,18 +71,23 @@ struct Subcommand { } const SUBCOMMANDS: &[Subcommand] = &[ - Subcommand { name: "convert", values: &["--format", "--quality", "--tga-bits", "--dpx-bits"], bare: &["--tiff-layers"], run: convert }, + Subcommand { + name: "convert", + values: &["--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"], + bare: &["--tiff-layers", "--dds-mipmaps"], + run: convert, + }, Subcommand { name: "info", values: &[], bare: &["--compact"], run: |a, out, _| info(a, out) }, Subcommand { name: "run", - values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"], - bare: &["--tiff-layers"], + values: &["--new", "--cmd", "--params", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"], + bare: &["--tiff-layers", "--dds-mipmaps"], run: run_cmds, }, Subcommand { name: "batch", - values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"], - bare: &["--in-place", "--tiff-layers"], + values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits", "--dds-compression"], + bare: &["--in-place", "--tiff-layers", "--dds-mipmaps"], run: batch, }, Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet }, @@ -219,6 +226,11 @@ fn export_opts(a: &Args) -> Result { o.encode.dpx_bits = Some(b.parse().ok().and_then(photocraft_io::DpxBits::from_bits).ok_or_else(|| format!("bad --dpx-bits `{b}`: expected 8, 10, 12 or 16"))?); } + if let Some(c) = a.get("--dds-compression") { + o.encode.dds.compression = + photocraft_io::DdsCompression::from_name(c).ok_or_else(|| format!("bad --dds-compression `{c}`: expected none, bc1, bc2 or bc3"))?; + } + o.encode.dds.mipmaps = a.has("--dds-mipmaps"); Ok(o) } diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rs index 3c28a8196e..6c62e40804 100644 --- a/apps/photocraft-cli/tests/cli.rs +++ b/apps/photocraft-cli/tests/cli.rs @@ -494,6 +494,39 @@ fn dpx_converts_both_ways_with_the_bits_asked_for() { } } +/// DDS converts both ways; `--dds-compression` picks the FourCC (bytes 84–87; none writes +/// uncompressed pixels) and `--dds-mipmaps` the mip count (bytes 28–31). A compression that +/// isn't none, bc1, bc2 or bc3 is refused and nothing is written (#1327). +#[test] +fn dds_converts_both_ways_with_the_compression_asked_for() { + let d = tmp("dds"); + let a = d.join("a.png"); + write_png(&a, 8, 4, 3); + for (args, fourcc, mips) in [ + (&[][..], [0; 4], 1), + (&["--dds-compression", "bc1"][..], *b"DXT1", 1), + (&["--dds-compression", "DXT3", "--dds-mipmaps"][..], *b"DXT3", 4), + (&["--dds-compression", "bc3"][..], *b"DXT5", 1), + (&["--dds-mipmaps"][..], [0; 4], 4), + ] { + let out = d.join("a.dds"); + ok(bin().arg("convert").arg(&a).arg(&out).args(args)); + let bytes = std::fs::read(&out).unwrap(); + let mip_count = u32::from_le_bytes(bytes[28..32].try_into().unwrap()); + assert_eq!((&bytes[..4], &bytes[84..88], mip_count), (&b"DDS "[..], &fourcc[..], mips), "{args:?}"); + let back = d.join("back.png"); + ok(bin().arg("convert").arg(&out).arg(&back)); + assert!(back.exists(), "{args:?}"); + } + for bad in ["bc7", "dxt2", ""] { + let out = d.join("bad.dds"); + let o = bin().arg("convert").arg(&a).arg(&out).args(["--dds-compression", bad]).output().unwrap(); + assert_eq!(o.status.code(), Some(1), "--dds-compression {bad}"); + assert!(String::from_utf8_lossy(&o.stderr).contains(&format!("bad --dds-compression `{bad}`")), "--dds-compression {bad}"); + assert!(!out.exists(), "--dds-compression {bad} wrote a file"); + } +} + /// `--tga-bits` picks a TGA's bits per pixel (byte 16 of its header); anything but 24 or 32 is /// refused and nothing is written. #[test] diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index fcacf81b26..437f5cee12 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -99,6 +99,8 @@ const SAVE_FILTERS: &[(&str, &[&str])] = &[ ("OpenEXR", &["exr"]), ("FITS", &["fits", "fit"]), ("DPX", &["dpx"]), + // Game and 3D textures; DDS Options asks for the compression and mipmaps (#1327). + ("DDS", &["dds"]), ]; /// Non-document files the shell saves (Swatches panel exports): offered alone, so the dialog @@ -903,7 +905,7 @@ mod tests { assert!(format.caps().write, "{name}: .{ext} can't be written"); } } - for ext in ["ico", "gif", "bmp"] { + for ext in ["ico", "gif", "bmp", "dds"] { assert!(save_filters("Untitled-1.psd").iter().any(|(_, exts)| exts.iter().any(|e| e == ext)), ".{ext} is offered"); } assert_eq!(save_filters("icon.ico")[0].0, "ICO", "an .ico name leads with its own type"); diff --git a/book/src/formats/raster-formats.md b/book/src/formats/raster-formats.md index 2e65d51550..c333cbc737 100644 --- a/book/src/formats/raster-formats.md +++ b/book/src/formats/raster-formats.md @@ -19,6 +19,7 @@ Every route that writes a document to a flat format (Save As, the CLI, MCP `doc_ - Formats without transparency (JPEG, Radiance HDR) get the image composited over white, as Export As and Quick Export do; in CMYK, white is no ink. - Formats that can't embed an ICC profile (GIF, BMP, TGA, QOI, ICO, Netpbm/PFM) get RGB documents in another profile (linear light, Display P3, …) converted to sRGB through the colour engine (perceptual intent), since an untagged file is read as sRGB. OpenEXR and Radiance HDR get linear sRGB instead (linear gray for a grayscale OpenEXR), which is how they are tagged when opened. - TGA, as Photoshop's Targa: an RGB Targa is 24 or 32 bits per pixel. Save As and Save a Copy ask (Targa Options, starting at 32 with an alpha channel, else 24); Export As has a Resolution choice (Auto, 24 or 32 bits/pixel); scripts pass `tgaBits` (`--tga-bits` on the CLI). At 32 bits the document's alpha channel is the file's alpha when it has exactly one (spot channels don't count; with several, none is used), and the colours are written exactly, never premultiplied or cleared where the alpha is 0, so a game texture's mask and its colours both survive. Without a usable alpha channel the layers' transparency is the alpha (opaque without any). 24 bits write no alpha, compositing transparency over white. Without a choice: 32 with an alpha channel or transparency, else 24. A 32-bit Targa opens as an opaque Background with its alpha as "Alpha 1", so it round-trips. Grayscale Targas are 8-bit. +- DDS, for game and 3D textures: Save As and Save a Copy ask (DDS Options) for the compression (None, uncompressed and lossless; BC1/DXT1, whose alpha is on or off; BC2/DXT3; BC3/DXT5) and whether to generate mipmaps (the full chain down to 1×1, each level a box filter of the one above). Scripts pass `ddsCompression` (`none`, `bc1`, `bc2`, `bc3`) and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Opening one reads its top mip level. Flat TIFF and JPEG exports of composited CMYK documents convert the RGB composite back through the document's CMYK ICC profile (relative colorimetric with black point compensation) and embed diff --git a/contributors/people.toml b/contributors/people.toml index bc3533777b..99d81059e9 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -181,3 +181,7 @@ sync_github_name = true [people.00xJS] sync_github_name = true + +[people.guillehr2] +real_name = "Guillem Hermida" +sync_github_name = true diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 15a0e24e30..3db25c4fdd 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -114,6 +114,7 @@ impl Headless { let mut opts = photocraft_io::ExportOptions { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits, ..Default::default() }; opts.encode.dpx_bits = photocraft_engine::file_cmds::dpx_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?; + opts.encode.dds = photocraft_engine::file_cmds::dds_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?.unwrap_or_default(); if let Some(q) = p.get("quality").and_then(Value::as_u64) { opts.encode.jpeg_quality = q.clamp(1, 100) as u8; opts.encode.webp_quality = q.clamp(1, 100) as u8; diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index f52376a9c5..567d0b4837 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -170,6 +170,13 @@ pub struct SaveParams { /// DPX: 8, 10, 12 or 16 bits per sample. Unset: 8 for an 8-bit document, else 16. #[serde(default, rename = "dpxBits")] pub dpx_bits: Option, + /// DDS: "none" (uncompressed, the default), "bc1" (DXT1: alpha on or off), "bc2" (DXT3) or + /// "bc3" (DXT5). + #[serde(default, rename = "ddsCompression")] + pub dds_compression: Option, + /// DDS: also write the full mip chain, each level a box filter of the one above. + #[serde(default, rename = "ddsMipmaps")] + pub dds_mipmaps: bool, #[serde(default)] pub index: Option, } @@ -1001,10 +1008,15 @@ impl PhotocraftMcp { Some((_, Some(bits))) => Some(bits), Some((b, None)) => return Ok(fail(format!("`dpxBits` must be 8, 10, 12 or 16, got {b}"))), }; + let dds_compression = match p.dds_compression.as_deref().map(|c| (c, photocraft_io::DdsCompression::from_name(c))) { + None => None, + Some((_, Some(c))) => Some(c), + Some((c, None)) => return Ok(fail(format!("`ddsCompression` must be none, bc1, bc2 or bc3, got {c:?}"))), + }; if let Some(b) = self.bridge_client() { // The bridge forwards to the running app's `app.save`, which takes only an optional // path (without one it writes back to the document's own layered file, as headless - // does) and the Targa bits, so the other options are headless-only. Saying so beats + // does), the Targa bits and the DDS options, so the other options are headless-only. Saying so beats // saving with defaults while the caller believes their quality or format was applied. let unsupported: Vec<&str> = [ p.format.is_some().then_some("format"), @@ -1026,12 +1038,19 @@ impl PhotocraftMcp { if let Some(bits) = tga_bits { params["tgaBits"] = json!(bits.bits()); } + if let Some(c) = dds_compression { + params["ddsCompression"] = json!(c.name()); + } + if p.dds_mipmaps { + params["ddsMipmaps"] = json!(true); + } return to_result(b.call("app.save", params).await); } let Some(r) = self .headless_op(move |h| { let mut opts = photocraft_io::ExportOptions { tiff_layers: p.tiff_layers, tga_bits, ..Default::default() }; opts.encode.dpx_bits = dpx_bits; + opts.encode.dds = photocraft_io::DdsOptions { compression: dds_compression.unwrap_or_default(), mipmaps: p.dds_mipmaps }; if let Some(q) = p.quality { opts.encode.jpeg_quality = q.clamp(1, 100); opts.encode.webp_quality = q.clamp(1, 100); diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs index 7386f3d58c..5a9fa7c56e 100644 --- a/crates/automation/tests/mcp.rs +++ b/crates/automation/tests/mcp.rs @@ -415,6 +415,45 @@ async fn headless_doc_save_writes_targa_bits() { cleanup(&dir); } +/// `ddsCompression` and `ddsMipmaps` reach the app's `app.save` through the bridge; an unknown +/// compression is refused before anything is sent. +#[tokio::test(flavor = "multi_thread")] +async fn bridge_doc_save_forwards_dds_options() { + let (addr, app) = fake_app().await; + let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await; + let saved = json_of(&call(&client, "doc_save", json!({"path": "out.dds", "ddsCompression": "DXT5", "ddsMipmaps": true})).await); + assert_eq!(saved, json!({"saved": {"path": "out.dds", "ddsCompression": "bc3", "ddsMipmaps": true}})); + let r = call(&client, "doc_save", json!({"path": "out.dds", "ddsCompression": "bc7"})).await; + assert_eq!(r.is_error, Some(true), "{}", text(&r)); + assert!(text(&r).contains("ddsCompression"), "{}", text(&r)); + client.cancel().await.unwrap(); + app.abort(); +} + +/// Headless `doc_save`/`doc_export` write the DDS compression (the FourCC, bytes 84–87) and mip +/// count (bytes 28–31) asked for; unset, an uncompressed texture without mipmaps. +#[tokio::test(flavor = "multi_thread")] +async fn headless_doc_save_writes_dds_options() { + let dir = tmp("dds-options"); + let client = connect(headless_in(&dir)).await; + call(&client, "doc_new", json!({"width": 16, "height": 8, "background": "white"})).await; + for (tool, params, fourcc, mips) in [ + ("doc_export", json!({"path": "plain.dds"}), [0; 4], 1), + ("doc_export", json!({"path": "bc1.dds", "ddsCompression": "bc1"}), *b"DXT1", 1), + ("doc_save", json!({"path": "bc3.dds", "ddsCompression": "bc3", "ddsMipmaps": true}), *b"DXT5", 5), + ] { + let r = call(&client, tool, params.clone()).await; + assert_ne!(r.is_error, Some(true), "{params}: {}", text(&r)); + let bytes = std::fs::read(dir.join(params["path"].as_str().unwrap())).unwrap(); + assert_eq!((&bytes[84..88], u32::from_le_bytes(bytes[28..32].try_into().unwrap())), (&fourcc[..], mips), "{params}"); + } + let r = call(&client, "doc_export", json!({"path": "bad.dds", "ddsCompression": "bc7"})).await; + assert_eq!(r.is_error, Some(true), "{}", text(&r)); + assert!(!dir.join("bad.dds").exists()); + client.cancel().await.unwrap(); + cleanup(&dir); +} + #[tokio::test(flavor = "multi_thread")] async fn bridge_response_budget_drops_connection_without_retrying_the_operation() { use photocraft_automation::{BridgeClient, budgets::MAX_RESPONSE_BYTES}; diff --git a/crates/codecs/README.md b/crates/codecs/README.md index 46baf50f82..539365c95b 100644 --- a/crates/codecs/README.md +++ b/crates/codecs/README.md @@ -40,7 +40,7 @@ let out = encode(&img, Format::Tiff, &EncodeOptions::default())?; | BMP | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` | | TGA | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | no | `image` (read) / built in (RLE write, one scanline per packet) | | ICO | yes | yes | U8 | RGBA (at most 256×256) | yes | no | no | no | no | no | no | `image` | -| DDS | yes | **no** | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | n/a | built in | +| DDS | yes | yes | U8 | Gray, GrayA, RGB, RGBA | yes | no | no | no | no | no | yes (BC1–BC3, when `EncodeOptions::dds` asks for one) | built in | | Netpbm (PBM/PGM/PPM/PAM/PFM) | yes | yes | U8, U16, F32 (float: PFM gray/RGB only) | all six (PAM `CMYK`/`CMYK_ALPHA`) | yes (PAM) | no | no | no | no | no | no | built in | | QOI | yes | yes | U8 | RGB, RGBA | yes | no | no | no | no | no | no | `image` | | OpenEXR | yes | yes | F16, F32 | Y, YA, RGB, RGBA | yes | no | no | no | no | no | no | `exr` | @@ -73,7 +73,15 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them (8, 16, 24 or 32 bits, RGB or luminance, with or without alpha) or BC1/BC2/BC3 (DXT1/DXT3/DXT5), with the legacy header or the DX10 one. Everything opens as U8; the other mip levels are ignored. Cubemaps, texture arrays, volume textures, premultiplied DXT2/DXT4 and other formats - (BC4–BC7, float) are refused with `CodecError::Unsupported`. Writing is not provided. + (BC4–BC7, float) are refused with `CodecError::Unsupported`. Writing (`EncodeOptions::dds`) makes + a 2D texture with the legacy header: uncompressed by default (BGRA, BGRX, or luminance with or + without alpha, so it reads back exactly), or BC1/BC2/BC3. The block encoder is our own, from + Microsoft's public block-compression documentation: RGB565 endpoints fitted along each block's + principal axis and refined by least squares, indices picked against the palette the reader + decodes; BC1 turns texels under half opacity into its transparent black, and BC3 picks + whichever alpha mode fits. `mipmaps` adds the full chain down to 1×1, each level a box filter + of the one above (the last column and row of an odd-sized level average three pixels, so none + is dropped). Cubemaps, arrays, BC4–BC7 and sRGB (DX10-only) formats aren't written. * **FITS.** The image in the primary HDU, or the first `IMAGE` extension, is read; `NAXIS3 = 3` opens as RGB and any other plane count opens the first plane with `DecodeWarning::MorePages`. diff --git a/crates/codecs/src/codecs/dds.rs b/crates/codecs/src/codecs/dds.rs index efe93c7f2e..d35c7d1092 100644 --- a/crates/codecs/src/codecs/dds.rs +++ b/crates/codecs/src/codecs/dds.rs @@ -1,13 +1,24 @@ -//! DirectDraw Surface (DDS) reader: the top mip level of a 2D texture, either uncompressed -//! (8 to 32 bits per pixel described by channel masks, RGB or luminance) or block-compressed -//! BC1/BC2/BC3 (DXT1/DXT3/DXT5), with or without the DX10 header. Read-only. Cubemaps, -//! texture arrays and volume textures are refused rather than flattened to one face or slice. +//! DirectDraw Surface (DDS) textures, after Microsoft's public DDS documentation ("DDS", +//! "DDS_HEADER", "DDS_PIXELFORMAT", "DDS_HEADER_DXT10"). +//! +//! Reading: the top mip level of a 2D texture, either uncompressed (8 to 32 bits per pixel +//! described by channel masks, RGB or luminance) or block-compressed BC1/BC2/BC3 +//! (DXT1/DXT3/DXT5), with or without the DX10 header. Cubemaps, texture arrays and volume +//! textures are refused rather than flattened to one face or slice. +//! +//! Writing: a 2D texture, uncompressed (BGRA or BGRX, luminance with or without alpha) or +//! BC1/BC2/BC3, optionally with its full mip chain. The legacy header describes all of these, +//! so no DX10 header is written; formats only DXGI can name (BC4–BC7, sRGB) aren't written. +use std::borrow::Cow; + +use super::dds_bc::{self, Block, Mask}; use crate::SampleType; use crate::error::CodecError; +use crate::fidelity::Plan; use crate::format::Format; use crate::image::{ChannelLayout, Image}; -use crate::options::Limits; +use crate::options::{DdsCompression, EncodeOptions, Limits}; /// `DDS ` plus the 124-byte DDS_HEADER. const HEADER: usize = 128; @@ -224,27 +235,12 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { Image::from_u8(width, height, layout, pixels) } -fn rgb565(c: u16) -> [u8; 3] { - let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8; - [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)] -} - /// A BC1 colour block. BC2 and BC3 colour blocks always have four colours; only BC1's /// `c0 <= c1` order selects three colours and transparent black. fn bc1(block: &[u8], one_bit_alpha: bool) -> [[u8; 4]; 16] { let byte = |i: usize| block.get(i).copied().unwrap_or(0); let (c0, c1) = (u16::from_le_bytes([byte(0), byte(1)]), u16::from_le_bytes([byte(2), byte(3)])); - let (a, b) = (rgb565(c0), rgb565(c1)); - let mix = |wa: u32, wb: u32| { - let d = wa + wb; - let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8; - [at(0), at(1), at(2), 255] - }; - let palette = if c0 > c1 || !one_bit_alpha { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)] - } else { - [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]] - }; + let palette = dds_bc::colour_palette(c0, c1, c0 > c1 || !one_bit_alpha); let indices = u32::from_le_bytes([byte(4), byte(5), byte(6), byte(7)]); std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) } @@ -259,21 +255,9 @@ fn bc2_alpha(block: &[u8]) -> [u8; 16] { /// 0 and 255 when `a0 <= a1`. fn bc3_alpha(block: &[u8]) -> [u8; 16] { let byte = |i: usize| block.get(i).copied().unwrap_or(0); - let (a0, a1) = (u32::from(byte(0)), u32::from(byte(1))); - let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255]; - if a0 > a1 { - for (k, v) in palette.iter_mut().enumerate().skip(2) { - let k = k as u32; - *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; - } - } else { - for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { - let k = k as u32; - *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; - } - } + let palette = dds_bc::alpha_palette(byte(0), byte(1)); let bits = u64::from_le_bytes([byte(2), byte(3), byte(4), byte(5), byte(6), byte(7), 0, 0]); - std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize] as u8) + std::array::from_fn(|t| palette[((bits >> (3 * t)) & 7) as usize]) } fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { @@ -282,3 +266,260 @@ fn with_alpha(mut texels: [[u8; 4]; 16], alpha: [u8; 16]) -> [[u8; 4]; 16] { } texels } + +const DDSD_CAPS: u32 = 0x1; +const DDSD_HEIGHT: u32 = 0x2; +const DDSD_WIDTH: u32 = 0x4; +const DDSD_PITCH: u32 = 0x8; +const DDSD_PIXELFORMAT: u32 = 0x1000; +const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; +const DDSD_LINEARSIZE: u32 = 0x8_0000; +const DDSCAPS_COMPLEX: u32 = 0x8; +const DDSCAPS_TEXTURE: u32 = 0x1000; +const DDSCAPS_MIPMAP: u32 = 0x40_0000; + +fn encode_err(reason: impl std::fmt::Display) -> CodecError { + CodecError::encode(Format::Dds, reason) +} + +/// How a written texture stores its pixels. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Store { + /// 8-bit luminance. + Luminance, + /// 8-bit luminance, then 8-bit alpha. + LuminanceAlpha, + /// Blue, green, red and an unused byte (written as 255, so a reader that takes it for + /// alpha still sees an opaque texture). + Bgrx, + Bgra, + Bc1, + Bc2, + Bc3, +} + +impl Store { + /// The storage for an image of `layout`, as [`crate::fidelity::plan`] chose it. + fn new(compression: DdsCompression, layout: ChannelLayout) -> Result { + Ok(match (compression, layout) { + (DdsCompression::None, ChannelLayout::Gray) => Store::Luminance, + (DdsCompression::None, ChannelLayout::GrayA) => Store::LuminanceAlpha, + (DdsCompression::None, ChannelLayout::Rgb) => Store::Bgrx, + (DdsCompression::None, ChannelLayout::Rgba) => Store::Bgra, + (DdsCompression::Bc1, ChannelLayout::Rgba) => Store::Bc1, + (DdsCompression::Bc2, ChannelLayout::Rgba) => Store::Bc2, + (DdsCompression::Bc3, ChannelLayout::Rgba) => Store::Bc3, + (_, layout) => return Err(encode_err(format!("{layout:?} pixels can't be written as `{}`", compression.name()))), + }) + } + + /// Bytes per pixel, or per 4×4 block for a block compression. + fn unit(self) -> usize { + match self { + Store::Luminance => 1, + Store::LuminanceAlpha => 2, + Store::Bgrx | Store::Bgra => 4, + Store::Bc1 => 8, + Store::Bc2 | Store::Bc3 => 16, + } + } + + fn is_block(self) -> bool { + matches!(self, Store::Bc1 | Store::Bc2 | Store::Bc3) + } + + /// Bytes of one row of pixels (or of 4×4 blocks) of a level `width` wide. + fn row_bytes(self, width: usize) -> Option { + if self.is_block() { width.div_ceil(4).checked_mul(self.unit()) } else { width.checked_mul(self.unit()) } + } + + fn level_bytes(self, width: usize, height: usize) -> Option { + let rows = if self.is_block() { height.div_ceil(4) } else { height }; + self.row_bytes(width)?.checked_mul(rows) + } + + /// DDS_PIXELFORMAT: flags, FourCC, bits per pixel and the red, green, blue and alpha masks. + fn pixel_format(self) -> (u32, [u8; 4], u32, [u32; 4]) { + match self { + Store::Luminance => (DDPF_LUMINANCE, [0; 4], 8, [0xff, 0, 0, 0]), + Store::LuminanceAlpha => (DDPF_LUMINANCE | DDPF_ALPHAPIXELS, [0; 4], 16, [0xff, 0, 0, 0xff00]), + Store::Bgrx => (DDPF_RGB, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0]), + Store::Bgra => (DDPF_RGB | DDPF_ALPHAPIXELS, [0; 4], 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), + Store::Bc1 => (DDPF_FOURCC, *b"DXT1", 0, [0; 4]), + Store::Bc2 => (DDPF_FOURCC, *b"DXT3", 0, [0; 4]), + Store::Bc3 => (DDPF_FOURCC, *b"DXT5", 0, [0; 4]), + } + } +} + +/// Levels in a full mip chain: the larger side halves down to 1. +fn mip_levels(width: u32, height: u32) -> u32 { + 32 - width.max(height).max(1).leading_zeros() +} + +fn half((w, h): (usize, usize)) -> (usize, usize) { + ((w / 2).max(1), (h / 2).max(1)) +} + +pub(crate) fn encode(image: &Image, plan: Plan, opts: &EncodeOptions) -> Result, CodecError> { + let img = image.converted(plan.layout, SampleType::U8); + let pixels = img.as_u8().ok_or_else(|| encode_err("the image was not converted to 8 bits per channel"))?; + let store = Store::new(opts.dds.compression, img.layout())?; + let (width, height) = img.dimensions(); + let levels = if opts.dds.mipmaps { mip_levels(width, height) } else { 1 }; + let top = (width as usize, height as usize); + // Every level's size, checked before anything is allocated. + let mut sizes = Vec::new(); + let mut size = top; + for _ in 0..levels { + sizes.push(store.level_bytes(size.0, size.1).ok_or_else(|| encode_err("texture size overflow"))?); + size = half(size); + } + let total = sizes.iter().try_fold(HEADER, |total, &s| total.checked_add(s)).ok_or_else(|| encode_err("texture size overflow"))?; + let header = header(width, height, store, levels, sizes.first().copied().unwrap_or(0))?; + let mut out = crate::options::alloc_zeroed::(total)?; + out.get_mut(..HEADER).ok_or_else(|| encode_err("output buffer too small"))?.copy_from_slice(&header); + + let channels = img.layout().channels(); + let mut level = Cow::Borrowed(pixels); + let (mut size, mut at) = (top, HEADER); + for (i, &bytes) in sizes.iter().enumerate() { + let dst = out.get_mut(at..at + bytes).ok_or_else(|| encode_err("output buffer too small"))?; + write_level(store, &level, size, dst)?; + at += bytes; + if i + 1 < sizes.len() { + let next = half(size); + level = Cow::Owned(downsample(&level, size, next, channels)?); + size = next; + } + } + Ok(out) +} + +/// The `DDS ` signature and DDS_HEADER. `top` is the top level's size in bytes. +fn header(width: u32, height: u32, store: Store, levels: u32, top: usize) -> Result<[u8; HEADER], CodecError> { + let mut b = [0u8; HEADER]; + let mut put = |at: usize, v: u32| { + if let Some(d) = b.get_mut(at..at + 4) { + d.copy_from_slice(&v.to_le_bytes()); + } + }; + // Uncompressed: the pitch of one row. Compressed: the whole top level (its "linear size"). + let (size_flag, pitch_or_size) = if store.is_block() { (DDSD_LINEARSIZE, Some(top)) } else { (DDSD_PITCH, store.row_bytes(width as usize)) }; + let pitch_or_size = + pitch_or_size.and_then(|v| u32::try_from(v).ok()).ok_or_else(|| encode_err(format!("a {width}x{height} level is too large for a DDS header")))?; + let mipmapped = levels > 1; + put(4, 124); + put(8, DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH | DDSD_PIXELFORMAT | size_flag | if mipmapped { DDSD_MIPMAPCOUNT } else { 0 }); + put(12, height); + put(16, width); + put(20, pitch_or_size); + put(28, levels); + let (flags, fourcc, bits, masks) = store.pixel_format(); + put(76, 32); + put(80, flags); + put(84, u32::from_le_bytes(fourcc)); + put(88, bits); + for (i, mask) in masks.into_iter().enumerate() { + put(92 + 4 * i, mask); + } + put(108, DDSCAPS_TEXTURE | if mipmapped { DDSCAPS_COMPLEX | DDSCAPS_MIPMAP } else { 0 }); + b[..4].copy_from_slice(b"DDS "); + Ok(b) +} + +/// Runs `f` on each `len`-byte row of `out` with its index, in parallel on native targets. +fn rows(out: &mut [u8], len: usize, f: impl Fn(usize, &mut [u8]) + Send + Sync) { + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + out.par_chunks_mut(len.max(1)).enumerate().for_each(|(i, row)| f(i, row)); + } + #[cfg(target_arch = "wasm32")] + for (i, row) in out.chunks_mut(len.max(1)).enumerate() { + f(i, row); + } +} + +/// Writes one level of `width` × `height` pixels (in the image's layout) into `dst`. +fn write_level(store: Store, pixels: &[u8], (width, height): (usize, usize), dst: &mut [u8]) -> Result<(), CodecError> { + let row_bytes = store.row_bytes(width).ok_or_else(|| encode_err("texture size overflow"))?; + match store { + Store::Luminance | Store::LuminanceAlpha => { + // The image's gray (and alpha) samples, in the same order. + let src = pixels.get(..dst.len()).ok_or_else(|| encode_err("the level is smaller than its size"))?; + dst.copy_from_slice(src); + } + Store::Bgrx | Store::Bgra => { + let channels = if store == Store::Bgra { 4 } else { 3 }; + rows(dst, row_bytes, |y, row| { + let src = pixels.get(y * width * channels..).unwrap_or_default(); + for (d, s) in row.as_chunks_mut::<4>().0.iter_mut().zip(src.chunks_exact(channels)) { + let byte = |i: usize| s.get(i).copied().unwrap_or(255); + *d = [byte(2), byte(1), byte(0), byte(3)]; + } + }); + } + Store::Bc1 | Store::Bc2 | Store::Bc3 => { + let (texels, _) = pixels.as_chunks::<4>(); + rows(dst, row_bytes, |by, row| { + for (bx, d) in row.chunks_exact_mut(store.unit()).enumerate() { + let (block, inside) = gather(texels, (width, height), bx, by); + let encoded: &[u8] = match store { + Store::Bc1 => &dds_bc::encode_bc1(&block, inside), + Store::Bc2 => &dds_bc::encode_bc2(&block, inside), + _ => &dds_bc::encode_bc3(&block, inside), + }; + for (d, s) in d.iter_mut().zip(encoded) { + *d = *s; + } + } + }); + } + } + Ok(()) +} + +/// Block (`bx`, `by`)'s texels, and which of them lie inside the image. +fn gather(texels: &[[u8; 4]], (width, height): (usize, usize), bx: usize, by: usize) -> (Block, Mask) { + let mut block = [[0u8; 4]; 16]; + let mut inside: Mask = 0; + for (t, texel) in block.iter_mut().enumerate() { + let (x, y) = (bx * 4 + t % 4, by * 4 + t / 4); + if x < width + && y < height + && let Some(p) = texels.get(y * width + x) + { + *texel = *p; + inside |= 1 << t; + } + } + (block, inside) +} + +/// The next mip level: each pixel the average of the 2×2 pixels it covers, or of 2×3, 3×2 or +/// 3×3 along the last column and row of an odd-sized level, so no pixel is dropped. +fn downsample(src: &[u8], (w, h): (usize, usize), (nw, nh): (usize, usize), channels: usize) -> Result, CodecError> { + let len = nw.checked_mul(nh).and_then(|n| n.checked_mul(channels)).ok_or_else(|| encode_err("mip level size overflow"))?; + let mut dst = crate::options::alloc_zeroed::(len)?; + let span = |i: usize, n: usize, size: usize| 2 * i..=if i + 1 == n { size.saturating_sub(1) } else { 2 * i + 1 }; + rows(&mut dst, nw * channels, |y, row| { + let ys = span(y, nh, h); + for (x, px) in row.chunks_exact_mut(channels.max(1)).enumerate() { + let xs = span(x, nw, w); + for (c, v) in px.iter_mut().enumerate() { + let (mut sum, mut n) = (0u32, 0u32); + for sy in ys.clone() { + for sx in xs.clone() { + if let Some(&s) = src.get((sy * w + sx) * channels + c) { + sum += u32::from(s); + n += 1; + } + } + } + *v = ((sum + n / 2) / n.max(1)) as u8; + } + } + }); + Ok(dst) +} diff --git a/crates/codecs/src/codecs/dds_bc.rs b/crates/codecs/src/codecs/dds_bc.rs new file mode 100644 index 0000000000..bbd55b4bf3 --- /dev/null +++ b/crates/codecs/src/codecs/dds_bc.rs @@ -0,0 +1,368 @@ +//! BC1, BC2 and BC3 (DXT1, DXT3, DXT5) blocks, after Microsoft's public block compression +//! documentation ("Block Compression (Direct3D 10)" and "Texture Block Compression in Direct3D +//! 11"): the palettes the DDS reader decodes with, and the block encoder the DDS writer uses. +//! +//! The encoder fits a block's colours with two RGB565 endpoints along their principal axis, +//! refines them by least squares, and scores every candidate against the exact palette the +//! reader rebuilds, so the indices it picks are the best ones for what a decoder shows. + +/// The 16 texels of a 4×4 block, row by row, as RGBA. +pub(crate) type Block = [[u8; 4]; 16]; + +/// Bit `t` set for each texel `t` of a block that counts: edge blocks of a texture whose size is +/// not a multiple of four have texels outside the image. +pub(crate) type Mask = u16; + +pub(crate) fn rgb565(c: u16) -> [u8; 3] { + let scale = |v: u16, max: u16| ((u32::from(v) * 255 + u32::from(max) / 2) / u32::from(max)) as u8; + [scale(c >> 11, 31), scale((c >> 5) & 63, 63), scale(c & 31, 31)] +} + +/// The colours a colour block's indices select. Four-colour mode (BC1 with `c0 > c1`, and every +/// BC2 and BC3 block) adds two colours at thirds; three-colour mode adds the midpoint and +/// transparent black. +pub(crate) fn colour_palette(c0: u16, c1: u16, four: bool) -> [[u8; 4]; 4] { + let (a, b) = (rgb565(c0), rgb565(c1)); + let mix = |wa: u32, wb: u32| { + let d = wa + wb; + let at = |i: usize| ((wa * u32::from(a[i]) + wb * u32::from(b[i]) + d / 2) / d) as u8; + [at(0), at(1), at(2), 255] + }; + if four { + [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(2, 1), mix(1, 2)] + } else { + [[a[0], a[1], a[2], 255], [b[0], b[1], b[2], 255], mix(1, 1), [0; 4]] + } +} + +/// A BC3 alpha block's eight values: six interpolated at sevenths when `a0 > a1`, else four +/// interpolated at fifths followed by 0 and 255. +pub(crate) fn alpha_palette(a0: u8, a1: u8) -> [u8; 8] { + let (a0, a1) = (u32::from(a0), u32::from(a1)); + let mut palette = [a0, a1, 0, 0, 0, 0, 0, 255]; + if a0 > a1 { + for (k, v) in palette.iter_mut().enumerate().skip(2) { + let k = k as u32; + *v = ((8 - k) * a0 + (k - 1) * a1 + 3) / 7; + } + } else { + for (k, v) in palette.iter_mut().enumerate().take(6).skip(2) { + let k = k as u32; + *v = ((6 - k) * a0 + (k - 1) * a1 + 2) / 5; + } + } + palette.map(|v| v as u8) +} + +/// A BC1 block. Texels under half opacity become BC1's transparent black, which needs the +/// three-colour mode; an opaque block takes whichever mode fits its colours better. +pub(crate) fn encode_bc1(block: &Block, inside: Mask) -> [u8; 8] { + let transparent = select(block, inside, |t| t[3] < 128); + colour_block(block, inside & !transparent, transparent, true) +} + +/// A BC2 block: four bits of alpha per texel, then a four-colour block. +pub(crate) fn encode_bc2(block: &Block, inside: Mask) -> [u8; 16] { + let bits = block.iter().enumerate().fold(0u64, |bits, (t, texel)| bits | ((u64::from(texel[3]) * 15 + 127) / 255) << (4 * t)); + join(bits.to_le_bytes(), colour_block(block, inside, 0, false)) +} + +/// A BC3 block: an interpolated alpha block, then a four-colour block. +pub(crate) fn encode_bc3(block: &Block, inside: Mask) -> [u8; 16] { + join(alpha_block(block, inside), colour_block(block, inside, 0, false)) +} + +fn join(a: [u8; 8], b: [u8; 8]) -> [u8; 16] { + std::array::from_fn(|i| if i < 8 { a.get(i) } else { b.get(i - 8) }.copied().unwrap_or(0)) +} + +/// The texels of `inside` for which `f` holds. +fn select(block: &Block, inside: Mask, f: impl Fn(&[u8; 4]) -> bool) -> Mask { + block.iter().enumerate().filter(|(t, texel)| inside >> t & 1 != 0 && f(texel)).fold(0, |m, (t, _)| m | 1 << t) +} + +fn rgb_of(texel: &[u8; 4]) -> [f32; 3] { + [f32::from(texel[0]), f32::from(texel[1]), f32::from(texel[2])] +} + +/// RGB565 of a colour, rounding each channel to the nearest level. +fn to565(c: [f32; 3]) -> u16 { + let q = |v: f32, max: f32| (v.clamp(0.0, 255.0) * max / 255.0).round() as u16; + q(c[0], 31.0) << 11 | q(c[1], 63.0) << 5 | q(c[2], 31.0) +} + +fn distance(a: &[u8; 4], b: &[u8; 4]) -> u32 { + (0..3).map(|i| u32::from(a[i].abs_diff(b[i])).pow(2)).sum() +} + +/// A colour block (endpoints, then 2-bit indices) for the `opaque` texels' colours, with the +/// `transparent` ones on BC1's transparent index. `bc1` allows the three-colour mode; BC2 and +/// BC3 always decode four colours. +fn colour_block(block: &Block, opaque: Mask, transparent: Mask, bc1: bool) -> [u8; 8] { + let colours: Vec<[f32; 3]> = block.iter().enumerate().filter(|(t, _)| opaque >> t & 1 != 0).map(|(_, texel)| rgb_of(texel)).collect(); + if colours.is_empty() { + // Nothing visible: every texel on the transparent index (or index 0 of black). + let indices = if transparent != 0 { u32::MAX } else { 0 }; + return pack(0, 0, indices); + } + let (lo, hi) = principal_endpoints(&colours); + let mut candidates = vec![(to565(lo), to565(hi))]; + let modes: &[bool] = if transparent != 0 { + &[false] + } else if bc1 { + &[true, false] + } else { + &[true] + }; + let mut best: Option<(u32, [u8; 8])> = None; + // Each refinement starts from the best block so far: its indices give the least-squares + // endpoints, which become one more candidate. + for round in 0..3 { + for &(e0, e1) in &candidates { + for &four in modes { + let (bytes, error) = fit(block, opaque, transparent, e0, e1, four); + if best.is_none_or(|(e, _)| error < e) { + best = Some((error, bytes)); + } + } + } + let Some((error, bytes)) = best else { break }; + if error == 0 || round == 2 { + break; + } + candidates = least_squares(block, opaque, &bytes).into_iter().collect(); + if candidates.is_empty() { + break; + } + } + best.map_or([0; 8], |(_, bytes)| bytes) +} + +/// Orders endpoints `e0`, `e1` for the mode (`c0 > c1` for four colours, `c0 <= c1` for three) +/// and picks each texel's nearest palette colour. Returns the block and its squared error. +fn fit(block: &Block, opaque: Mask, transparent: Mask, e0: u16, e1: u16, four: bool) -> ([u8; 8], u32) { + let (c0, c1) = if four == (e0 >= e1) { (e0, e1) } else { (e1, e0) }; + // Equal endpoints can't be in four-colour order; the palette is then one colour either way. + let palette = colour_palette(c0, c1, four && c0 > c1); + let choices = if four && c0 > c1 { 4 } else { 3 }; + let mut indices = 0u32; + let mut error = 0u32; + for (t, texel) in block.iter().enumerate() { + let index = if transparent >> t & 1 != 0 { + 3 + } else if opaque >> t & 1 != 0 { + let (i, d) = palette.iter().take(choices).enumerate().map(|(i, p)| (i, distance(texel, p))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); + error += d; + i as u32 + } else { + 0 + }; + indices |= index << (2 * t); + } + (pack(c0, c1, indices), error) +} + +fn pack(c0: u16, c1: u16, indices: u32) -> [u8; 8] { + let (c0, c1, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes()); + [c0[0], c0[1], c1[0], c1[1], i[0], i[1], i[2], i[3]] +} + +/// The ends of the colours' spread along their principal axis (the covariance's dominant +/// eigenvector, by power iteration), clamped to the RGB cube. +fn principal_endpoints(colours: &[[f32; 3]]) -> ([f32; 3], [f32; 3]) { + let n = colours.len().max(1) as f32; + let mean = [0, 1, 2].map(|i| colours.iter().map(|c| c[i]).sum::() / n); + let mut cov = [[0f32; 3]; 3]; + for c in colours { + let d = [c[0] - mean[0], c[1] - mean[1], c[2] - mean[2]]; + for (i, row) in cov.iter_mut().enumerate() { + for (j, v) in row.iter_mut().enumerate() { + *v += d[i] * d[j]; + } + } + } + let times = |a: [f32; 3]| [0, 1, 2].map(|i| cov[i][0] * a[0] + cov[i][1] * a[1] + cov[i][2] * a[2]); + let iterate = |start: usize| { + let mut axis = [0f32; 3]; + axis[start] = 1.0; + for _ in 0..8 { + let next = times(axis); + let len = next.iter().map(|v| v * v).sum::().sqrt(); + if !len.is_normal() { + break; + } + axis = next.map(|v| v / len); + } + axis + }; + // From each channel's axis, keeping the one the colours spread along most: a channel that + // varies on its own is already an eigenvector, so a single start there would never leave it + // even when the others vary more together. + let spread = |a: [f32; 3]| times(a).iter().zip(a).map(|(x, y)| x * y).sum::(); + let axis = [0, 1, 2].map(iterate).into_iter().max_by(|&a, &b| spread(a).total_cmp(&spread(b))).unwrap_or([1.0, 0.0, 0.0]); + let along = |c: &[f32; 3]| (c[0] - mean[0]) * axis[0] + (c[1] - mean[1]) * axis[1] + (c[2] - mean[2]) * axis[2]; + let (lo, hi) = colours.iter().map(along).fold((f32::MAX, f32::MIN), |(lo, hi), t| (lo.min(t), hi.max(t))); + let at = |t: f32| [0, 1, 2].map(|i| (mean[i] + t * axis[i]).clamp(0.0, 255.0)); + if lo > hi { (mean, mean) } else { (at(lo), at(hi)) } +} + +/// The endpoints that minimise the squared error for the indices `bytes` already chose: each +/// texel's index fixes its weights between the endpoints, giving 2×2 normal equations per +/// channel. `None` when the indices don't constrain both endpoints. +fn least_squares(block: &Block, opaque: Mask, bytes: &[u8; 8]) -> Option<(u16, u16)> { + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + let four = c0 > c1; + // How much of c0 each index holds. + let weight = |i: u32| match (four, i) { + (_, 0) => Some(1.0f32), + (_, 1) => Some(0.0), + (true, 2) => Some(2.0 / 3.0), + (true, _) => Some(1.0 / 3.0), + (false, 2) => Some(0.5), + (false, _) => None, + }; + let (mut aa, mut ab, mut bb) = (0f32, 0f32, 0f32); + let (mut ax, mut bx) = ([0f32; 3], [0f32; 3]); + for (t, texel) in block.iter().enumerate() { + if opaque >> t & 1 == 0 { + continue; + } + let Some(a) = weight(indices >> (2 * t) & 3) else { continue }; + let b = 1.0 - a; + let c = rgb_of(texel); + aa += a * a; + ab += a * b; + bb += b * b; + for ((x0, x1), v) in ax.iter_mut().zip(bx.iter_mut()).zip(c) { + *x0 += a * v; + *x1 += b * v; + } + } + let det = aa * bb - ab * ab; + if det.abs() < 1e-3 { + return None; + } + let e0 = [0, 1, 2].map(|i| (ax[i] * bb - bx[i] * ab) / det); + let e1 = [0, 1, 2].map(|i| (bx[i] * aa - ax[i] * ab) / det); + Some((to565(e0), to565(e1))) +} + +/// A BC3 alpha block: whichever of the two modes (eight values between the extremes, or six +/// between the extremes other than 0 and 255, plus exact 0 and 255) fits better. +fn alpha_block(block: &Block, inside: Mask) -> [u8; 8] { + let alphas = || block.iter().enumerate().filter(move |(t, _)| inside >> t & 1 != 0).map(|(_, texel)| texel[3]); + let range = |values: &mut dyn Iterator| values.fold(None, |r: Option<(u8, u8)>, a| Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a))))); + let (lo, hi) = range(&mut alphas()).unwrap_or((0, 0)); + // Eight values need a0 > a1; equal ends fall to the six-value mode, which starts with a0 too. + let eight = alpha_fit(block, inside, hi, lo); + let (mid_lo, mid_hi) = range(&mut alphas().filter(|a| !matches!(a, 0 | 255))).unwrap_or((0, 0)); + let six = alpha_fit(block, inside, mid_lo, mid_hi); + if six.1 < eight.1 { six.0 } else { eight.0 } +} + +fn alpha_fit(block: &Block, inside: Mask, a0: u8, a1: u8) -> ([u8; 8], u32) { + let palette = alpha_palette(a0, a1); + let mut bits = 0u64; + let mut error = 0u32; + for (t, texel) in block.iter().enumerate() { + if inside >> t & 1 == 0 { + continue; + } + let (i, d) = palette.iter().enumerate().map(|(i, &p)| (i, u32::from(p.abs_diff(texel[3])).pow(2))).min_by_key(|&(_, d)| d).unwrap_or((0, 0)); + error += d; + bits |= (i as u64) << (3 * t); + } + let b = bits.to_le_bytes(); + ([a0, a1, b[0], b[1], b[2], b[3], b[4], b[5]], error) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn decode_colour(bytes: &[u8; 8], bc1: bool) -> Block { + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + let palette = colour_palette(c0, c1, c0 > c1 || !bc1); + let indices = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]); + std::array::from_fn(|t| palette[(indices >> (2 * t)) as usize & 3]) + } + + #[test] + fn solid_blocks_land_on_the_nearest_565_colour() { + for colour in [[0, 0, 0, 255], [255, 255, 255, 255], [12, 200, 77, 255]] { + let block = [colour; 16]; + let out = decode_colour(&encode_bc1(&block, u16::MAX), true); + for texel in out { + assert!(texel.iter().zip(colour).all(|(a, b)| a.abs_diff(b) <= 4), "{texel:?} for {colour:?}"); + } + } + } + + #[test] + fn two_colour_blocks_are_exact_when_the_colours_are_565() { + let (a, b) = ([255, 0, 0, 255], [0, 0, 255, 255]); + let block: Block = std::array::from_fn(|t| if t % 3 == 0 { a } else { b }); + for bc1 in [true, false] { + let bytes = if bc1 { encode_bc1(&block, u16::MAX) } else { colour_block(&block, u16::MAX, 0, false) }; + assert_eq!(decode_colour(&bytes, bc1), block); + } + } + + #[test] + fn bc1_punches_through_texels_under_half_alpha() { + let block: Block = std::array::from_fn(|t| if t < 8 { [200, 100, 50, 255] } else { [9, 9, 9, 127] }); + let bytes = encode_bc1(&block, u16::MAX); + let (c0, c1) = (u16::from_le_bytes([bytes[0], bytes[1]]), u16::from_le_bytes([bytes[2], bytes[3]])); + assert!(c0 <= c1, "three-colour mode"); + let out = decode_colour(&bytes, true); + assert!(out[..8].iter().all(|t| t[3] == 255) && out[8..].iter().all(|t| *t == [0; 4]), "{out:?}"); + } + + #[test] + fn four_colour_blocks_keep_c0_above_c1() { + // A ramp needs all four colours; BC2 and BC3 blocks must not rely on the order, but + // older decoders read c0 <= c1 as three colours, so the encoder never writes that. + let block: Block = std::array::from_fn(|t| [(t * 16) as u8, 0, 0, 255]); + let bytes = colour_block(&block, u16::MAX, 0, false); + assert!(u16::from_le_bytes([bytes[0], bytes[1]]) > u16::from_le_bytes([bytes[2], bytes[3]])); + } + + #[test] + fn alpha_blocks_pick_the_mode_that_keeps_0_and_255() { + // 0, 255 and a cluster in between: the six-value mode stores 0 and 255 exactly. + let block: Block = std::array::from_fn(|t| [0, 0, 0, [0, 255, 100, 110][t % 4]]); + let bytes = alpha_block(&block, u16::MAX); + assert!(bytes[0] <= bytes[1], "six-value mode"); + let palette = alpha_palette(bytes[0], bytes[1]); + let bits = u64::from_le_bytes([bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], 0, 0]); + for (t, texel) in block.iter().enumerate() { + let got = palette[(bits >> (3 * t)) as usize & 7]; + assert!(got.abs_diff(texel[3]) <= 2, "texel {t}: {got} for {}", texel[3]); + } + } + + #[test] + fn the_principal_axis_is_found_when_one_channel_varies_on_its_own() { + // Red alternates on its own (variance 64); green and blue alternate together (variance 49 + // each, 98 along their shared axis), uncorrelated with red. Starting on red alone would + // keep red's axis and flatten green and blue; the block must do better than its bounding box. + let block: Block = std::array::from_fn(|t| { + let gb = if (t / 2) % 2 == 0 { 121 } else { 135 }; + [if t % 2 == 0 { 120 } else { 136 }, gb, gb, 255] + }); + let error = |bytes: &[u8; 8]| decode_colour(bytes, false).iter().zip(&block).map(|(a, b)| distance(a, b)).sum::(); + let (_, bounding_box) = fit(&block, u16::MAX, 0, to565([120.0, 121.0, 121.0]), to565([136.0, 135.0, 135.0]), true); + let ours = error(&colour_block(&block, u16::MAX, 0, false)); + assert!(ours < bounding_box, "{ours} vs the bounding box's {bounding_box}"); + } + + #[test] + fn texels_outside_the_image_are_ignored() { + // Only the top-left texel is inside: its colour alone decides the endpoints. + let mut block: Block = [[0, 255, 0, 255]; 16]; + block[0] = [255, 0, 255, 255]; + let out = decode_colour(&encode_bc1(&block, 1), true); + assert_eq!(out[0], [255, 0, 255, 255]); + } +} diff --git a/crates/codecs/src/codecs/mod.rs b/crates/codecs/src/codecs/mod.rs index 32e68b336a..d9905ab978 100644 --- a/crates/codecs/src/codecs/mod.rs +++ b/crates/codecs/src/codecs/mod.rs @@ -1,4 +1,5 @@ pub(crate) mod dds; +pub(crate) mod dds_bc; pub(crate) mod deep_exr; pub(crate) mod dpx; pub(crate) mod exr; diff --git a/crates/codecs/src/fidelity.rs b/crates/codecs/src/fidelity.rs index 594735edb4..a6937b571c 100644 --- a/crates/codecs/src/fidelity.rs +++ b/crates/codecs/src/fidelity.rs @@ -6,7 +6,7 @@ use std::fmt; use crate::format::{Format, caps}; use crate::image::{ChannelLayout, Image, SampleType}; -use crate::options::EncodeOptions; +use crate::options::{DdsCompression, EncodeOptions}; /// Something that will be lost or altered when writing an image to a format. #[derive(Debug, Clone, PartialEq)] @@ -165,6 +165,8 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan }, // CIELab has no float form: float Lab is written with 16 bits. Format::Tiff if layout.is_lab() && sample.is_float() => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: SampleType::U16 }, + // A block-compressed DDS stores RGBA whatever the source; uncompressed keeps gray and RGB. + Format::Dds if opts.dds.compression.is_block() => Plan { layout: ChannelLayout::Rgba, sample: SampleType::U8 }, _ => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: pick_sample(sample, c.depths) }, } } @@ -211,7 +213,8 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption if sl.has_alpha() && !p.layout.has_alpha() && image.has_translucency() { w.push(W::AlphaDiscarded); } - if format == Format::Gif && p.layout.has_alpha() && image.has_translucency() { + let binary_alpha = format == Format::Gif || (format == Format::Dds && opts.dds.compression == DdsCompression::Bc1); + if binary_alpha && p.layout.has_alpha() && image.has_translucency() { w.push(W::AlphaBinarized); } if sl.is_cmyk() && !p.layout.is_cmyk() { @@ -227,7 +230,7 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption // Compression if format == Format::Gif { w.push(W::PaletteQuantized); - } else if c.lossy || (format == Format::WebP && !opts.webp_lossless) { + } else if c.lossy || (format == Format::WebP && !opts.webp_lossless) || (format == Format::Dds && opts.dds.compression.is_block()) { w.push(W::LossyCompression); } diff --git a/crates/codecs/src/format.rs b/crates/codecs/src/format.rs index fa2e1e6cb3..24611bd90d 100644 --- a/crates/codecs/src/format.rs +++ b/crates/codecs/src/format.rs @@ -19,7 +19,8 @@ pub enum Format { Pcx, /// X PixMap icons (XPM2 plain text and XPM3 C-string arrays). Xpm, - /// DirectDraw Surface: the top mip level of a 2D texture, uncompressed or BC1–BC3. + /// DirectDraw Surface: a 2D texture, uncompressed or BC1–BC3. Reading takes the top mip + /// level; writing can add the full mip chain ([`crate::DdsOptions`]). Dds, Qoi, OpenExr, @@ -71,10 +72,6 @@ pub const ASYMMETRIC_EXCEPTIONS: &[(Format, &str)] = &[ Format::Pcx, "PCX is supported for opening legacy paint and clipart assets. New files should use PNG; writing obsolete indexed and planar variants is intentionally not provided.", ), - ( - Format::Dds, - "DDS is supported for opening game and 3D textures. Writing one well means choosing a block compression and generating mip levels, which belongs in a texture export, not Save As.", - ), ( Format::Avif, "AVIF encode uses ravif (pure Rust) but decoding requires dav1d (C); read stays unsupported \ @@ -255,7 +252,8 @@ pub fn caps(format: Format) -> FormatCaps { Format::Pnm => FormatCaps { depths: &[S::U8, S::U16, S::F32], layouts: ALL_LAYOUTS, ..base }, Format::Pcx => FormatCaps { read: true, write: false, layouts: &[L::Rgb], alpha: false, ..base }, Format::Xpm => FormatCaps { read: true, write: false, layouts: &[L::Rgba], ..base }, - Format::Dds => FormatCaps { read: true, write: false, layouts: RGB_GRAY, ..base }, + // Uncompressed by default; a block compression is lossy (see `fidelity_warnings_with`). + Format::Dds => FormatCaps { layouts: RGB_GRAY, ..base }, Format::Qoi => base, Format::OpenExr => FormatCaps { depths: &[S::F16, S::F32], layouts: RGB_GRAY, ..base }, Format::Hdr => FormatCaps { depths: &[S::F32], layouts: &[L::Rgb], alpha: false, lossy: true, ..base }, diff --git a/crates/codecs/src/lib.rs b/crates/codecs/src/lib.rs index 67369d0266..a5675c9823 100644 --- a/crates/codecs/src/lib.rs +++ b/crates/codecs/src/lib.rs @@ -38,7 +38,9 @@ pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, pub use crate::image::{ ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, Image, Metadata, SampleType, }; -pub use crate::options::{DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression}; +pub use crate::options::{ + DdsCompression, DdsOptions, DecodeOptions, DpxBits, EncodeOptions, ExrCompression, Limits, PngCompression, PngStereo, TiffCompression, +}; pub use crate::orientation::{exif_orientation, upright_exif, upright_xmp}; pub use crate::resolution::{exif_resolution, export_exif, export_xmp, photoshop_resolution, xmp_resolution}; pub use crate::source_settings::{WebpEncoding, jpeg_quality, webp_encoding}; @@ -252,7 +254,7 @@ pub fn encode(image: &Image, format: Format, opts: &EncodeOptions) -> Result pnm::encode(image, plan, opts), Format::Pcx => Err(CodecError::unsupported(format, "PCX is import-only; save as PNG instead")), Format::Xpm => Err(CodecError::unsupported(format, "XPM is import-only; save as PNG instead")), - Format::Dds => Err(CodecError::unsupported(format, "DDS is import-only; save as PNG instead")), + Format::Dds => dds::encode(image, plan, opts), Format::Fits => fits::encode(image, plan, opts), Format::Dpx => dpx::encode(image, plan, opts), Format::Cineon => Err(CodecError::unsupported(format, "Cineon is import-only; save as DPX, TIFF or EXR instead")), diff --git a/crates/codecs/src/options.rs b/crates/codecs/src/options.rs index e6ca3cb94f..08de328574 100644 --- a/crates/codecs/src/options.rs +++ b/crates/codecs/src/options.rs @@ -182,6 +182,61 @@ impl DpxBits { } } +/// How a DDS texture stores its pixels. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum DdsCompression { + /// Uncompressed, 8 bits per channel: BGRA (BGRX without alpha), or luminance with or + /// without alpha for grayscale. Lossless. + #[default] + None, + /// BC1 (DXT1): 4 bits per pixel. Alpha is on or off: texels under half opacity become + /// transparent black. + Bc1, + /// BC2 (DXT3): 8 bits per pixel, with 4 bits of explicit alpha per texel. + Bc2, + /// BC3 (DXT5): 8 bits per pixel, with smooth interpolated alpha. + Bc3, +} + +impl DdsCompression { + pub const ALL: [DdsCompression; 4] = [DdsCompression::None, DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; + + /// The name scripts and the CLI use: `none`, `bc1`, `bc2` or `bc3`. + pub fn name(self) -> &'static str { + match self { + DdsCompression::None => "none", + DdsCompression::Bc1 => "bc1", + DdsCompression::Bc2 => "bc2", + DdsCompression::Bc3 => "bc3", + } + } + + /// [`Self::name`] back to a compression, also taking the DXT names (`dxt1`, `dxt3`, + /// `dxt5`), in any case. Anything else is `None`. + pub fn from_name(name: &str) -> Option { + match name.to_ascii_lowercase().as_str() { + "none" => Some(DdsCompression::None), + "bc1" | "dxt1" => Some(DdsCompression::Bc1), + "bc2" | "dxt3" => Some(DdsCompression::Bc2), + "bc3" | "dxt5" => Some(DdsCompression::Bc3), + _ => None, + } + } + + /// A block compression (lossy), not uncompressed pixels. + pub fn is_block(self) -> bool { + self != DdsCompression::None + } +} + +/// What a DDS file is written with. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DdsOptions { + pub compression: DdsCompression, + /// Write the full mip chain down to 1×1, each level a box filter of the one above. + pub mipmaps: bool, +} + /// Options for [`crate::encode`]. #[derive(Debug, Clone)] pub struct EncodeOptions { @@ -207,6 +262,8 @@ pub struct EncodeOptions { pub exr_compression: ExrCompression, /// DPX bits per sample. `None` follows the image: 8 for 8-bit, 16 otherwise. pub dpx_bits: Option, + /// DDS compression and mip chain. + pub dds: DdsOptions, /// Embed the ICC profile when the format supports it. pub embed_icc: bool, /// Embed EXIF/XMP/DPI/text when the format supports it. @@ -227,6 +284,7 @@ impl Default for EncodeOptions { tiff_bigtiff: false, exr_compression: ExrCompression::Zip16, dpx_bits: None, + dds: DdsOptions::default(), embed_icc: true, embed_metadata: true, } diff --git a/crates/codecs/tests/dds.rs b/crates/codecs/tests/dds.rs index 766555f6e5..ebf4042f48 100644 --- a/crates/codecs/tests/dds.rs +++ b/crates/codecs/tests/dds.rs @@ -59,11 +59,12 @@ const WHITE: u16 = 0xffff; const INDICES_0123: [u8; 4] = [0x04, 0x0e, 0, 0]; #[test] -fn dds_is_readable_but_not_writable() { +fn dds_is_readable_and_writable() { assert_eq!(from_extension("texture.DDS"), Some(Format::Dds)); - assert!(caps(Format::Dds).read && !caps(Format::Dds).write); - let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgba, vec![0, 0, 0, 0]).unwrap(); - assert!(matches!(encode(&img, Format::Dds, &Default::default()), Err(CodecError::Unsupported { .. }))); + assert!(caps(Format::Dds).read && caps(Format::Dds).write); + let img = photocraft_codecs::Image::from_u8(1, 1, ChannelLayout::Rgba, vec![1, 2, 3, 0]).unwrap(); + let b = encode(&img, Format::Dds, &Default::default()).unwrap(); + assert_eq!(decode(&b).unwrap().data(), &[1, 2, 3, 0]); } #[test] diff --git a/crates/codecs/tests/dds_write.rs b/crates/codecs/tests/dds_write.rs new file mode 100644 index 0000000000..3225dd14d6 --- /dev/null +++ b/crates/codecs/tests/dds_write.rs @@ -0,0 +1,372 @@ +//! Writing DDS textures: every storage read back through the reader, the header fields, sizes +//! that aren't a multiple of four, the mip chain, and the block-compression error on ramps. + +use photocraft_codecs::{ChannelLayout, DdsCompression, DdsOptions, EncodeOptions, FidelityWarning, Format, Image, decode, encode, fidelity_warnings_with}; + +const DDSD_PITCH: u32 = 0x8; +const DDSD_MIPMAPCOUNT: u32 = 0x2_0000; +const DDSD_LINEARSIZE: u32 = 0x8_0000; +const REQUIRED: u32 = 0x1007; // CAPS | HEIGHT | WIDTH | PIXELFORMAT +const DDSCAPS_COMPLEX: u32 = 0x8; +const DDSCAPS_TEXTURE: u32 = 0x1000; +const DDSCAPS_MIPMAP: u32 = 0x40_0000; +const DDPF_ALPHAPIXELS: u32 = 0x1; +const DDPF_FOURCC: u32 = 0x4; +const DDPF_RGB: u32 = 0x40; +const DDPF_LUMINANCE: u32 = 0x2_0000; + +const BLOCKS: [DdsCompression; 3] = [DdsCompression::Bc1, DdsCompression::Bc2, DdsCompression::Bc3]; + +fn opts(compression: DdsCompression, mipmaps: bool) -> EncodeOptions { + EncodeOptions { dds: DdsOptions { compression, mipmaps }, ..Default::default() } +} + +fn le32(b: &[u8], at: usize) -> u32 { + u32::from_le_bytes(b[at..at + 4].try_into().unwrap()) +} + +/// A ramp along one line through RGB (red up, green up half as fast, blue down) across the +/// texture, and alpha falling from opaque down it: every block's colours lie on a line, which +/// is what a colour block stores. +fn ramp(w: u32, h: u32, layout: ChannelLayout) -> Image { + let ch = layout.channels(); + let at = |v: u32, n: u32| (v * 255 / (n - 1).max(1)) as u8; + let mut data = Vec::new(); + for y in 0..h { + for x in 0..w { + let r = at(x, w); + let rgba = [r, 64 + r / 2, 255 - r, 255 - at(y, h)]; + match ch { + 1 => data.push(rgba[0]), + 2 => data.extend([rgba[0], rgba[3]]), + _ => data.extend(&rgba[..ch]), + } + } + } + Image::from_u8(w, h, layout, data).unwrap() +} + +/// The same RGBA image, fully opaque. +fn opaque(img: &Image) -> Image { + let data = img.data().chunks(4).flat_map(|p| [p[0], p[1], p[2], 255]).collect(); + Image::from_u8(img.width(), img.height(), ChannelLayout::Rgba, data).unwrap() +} + +/// Largest difference in channel `c` (of four) between RGBA images. +fn max_diff_channel(a: &Image, b: &Image, c: usize) -> u8 { + a.data().chunks(4).zip(b.data().chunks(4)).map(|(x, y)| x[c].abs_diff(y[c])).max().unwrap_or(0) +} + +/// Largest colour difference between RGBA images where `b` is visible (BC1 turns texels under +/// half opacity into transparent black). +fn max_colour_diff(a: &Image, b: &Image) -> u8 { + a.data().chunks(4).zip(b.data().chunks(4)).filter(|(_, y)| y[3] != 0).flat_map(|(x, y)| (0..3).map(|c| x[c].abs_diff(y[c]))).max().unwrap_or(0) +} + +/// A 2D gradient: red across, green down and blue along the diagonal, opaque. +fn gradient(w: u32, h: u32) -> Image { + let data = (0..h).flat_map(|y| (0..w).flat_map(move |x| [(x * 4).min(255) as u8, (y * 4).min(255) as u8, ((x + y) * 2).min(255) as u8, 255])).collect(); + Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap() +} + +/// PSNR of the colour (not the alpha) of two RGBA images. +fn psnr(a: &Image, b: &Image) -> f64 { + let rgb = |i: &Image| i.data().chunks(4).flat_map(|p| [p[0], p[1], p[2]]).map(f64::from).collect::>(); + let (a, b) = (rgb(a), rgb(b)); + let mse = a.iter().zip(&b).map(|(x, y)| (x - y).powi(2)).sum::() / a.len() as f64; + if mse == 0.0 { f64::INFINITY } else { 10.0 * (255.0f64.powi(2) / mse).log10() } +} + +/// Bytes of one level as a reader computes them from the header's pixel format. +fn level_bytes(file: &[u8], w: usize, h: usize) -> usize { + if le32(file, 80) & DDPF_FOURCC != 0 { + let block = if &file[84..88] == b"DXT1" { 8 } else { 16 }; + w.div_ceil(4) * h.div_ceil(4) * block + } else { + w * h * le32(file, 88) as usize / 8 + } +} + +/// Mip level `i` of a written texture, cut out as a single-level texture and decoded. +fn level(file: &[u8], i: u32) -> Image { + let (w, h) = (le32(file, 16) as usize, le32(file, 12) as usize); + let size = |i: u32| ((w >> i).max(1), (h >> i).max(1)); + let start = 128 + (0..i).map(|j| level_bytes(file, size(j).0, size(j).1)).sum::(); + let (lw, lh) = size(i); + let mut b = file[..128].to_vec(); + b[12..16].copy_from_slice(&(lh as u32).to_le_bytes()); + b[16..20].copy_from_slice(&(lw as u32).to_le_bytes()); + b[28..32].copy_from_slice(&1u32.to_le_bytes()); + b.extend(&file[start..start + level_bytes(file, lw, lh)]); + decode(&b).unwrap() +} + +#[test] +fn uncompressed_textures_round_trip_every_layout_exactly() { + for (layout, pf_flags, bits, masks) in [ + (ChannelLayout::Gray, DDPF_LUMINANCE, 8, [0xff, 0, 0, 0]), + (ChannelLayout::GrayA, DDPF_LUMINANCE | DDPF_ALPHAPIXELS, 16, [0xff, 0, 0, 0xff00]), + (ChannelLayout::Rgb, DDPF_RGB, 32, [0xff_0000, 0xff00, 0xff, 0]), + (ChannelLayout::Rgba, DDPF_RGB | DDPF_ALPHAPIXELS, 32, [0xff_0000, 0xff00, 0xff, 0xff00_0000]), + ] { + for (w, h) in [(1, 1), (5, 3), (17, 9)] { + let img = ramp(w, h, layout); + let b = encode(&img, Format::Dds, &EncodeOptions::default()).unwrap(); + let back = decode(&b).unwrap(); + assert_eq!(back.layout(), layout, "{layout:?} {w}x{h}"); + assert_eq!(back.data(), img.data(), "{layout:?} {w}x{h}"); + + assert_eq!((&b[..4], le32(&b, 4), le32(&b, 76)), (&b"DDS "[..], 124, 32)); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_PITCH, "pitch, not linear size, and no mip count"); + assert_eq!((le32(&b, 12), le32(&b, 16)), (h, w)); + assert_eq!(le32(&b, 20), w * bits / 8, "pitch of {layout:?} {w}x{h}"); + assert_eq!((le32(&b, 28), le32(&b, 108)), (1, DDSCAPS_TEXTURE)); + assert_eq!((le32(&b, 80), le32(&b, 88)), (pf_flags, bits)); + assert_eq!([le32(&b, 92), le32(&b, 96), le32(&b, 100), le32(&b, 104)], masks); + assert_eq!(b.len(), 128 + (w * h * bits / 8) as usize); + } + } +} + +#[test] +fn block_compressed_textures_round_trip_through_the_reader() { + for (compression, fourcc, block) in [(DdsCompression::Bc1, b"DXT1", 8), (DdsCompression::Bc2, b"DXT3", 16), (DdsCompression::Bc3, b"DXT5", 16)] { + // Not multiples of four, and the 1×1 and 2×2 textures smaller than one block. + for (w, h) in [(1, 1), (2, 2), (4, 4), (5, 3), (7, 13), (33, 17)] { + let img = ramp(w, h, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(compression, false)).unwrap(); + let linear = w.div_ceil(4) * h.div_ceil(4) * block; + assert_eq!(&b[84..88], fourcc); + assert_eq!((le32(&b, 80), le32(&b, 88)), (DDPF_FOURCC, 0)); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE, "linear size, not pitch"); + assert_eq!(le32(&b, 20), linear, "{compression:?} {w}x{h}: the top level's size"); + assert_eq!(b.len(), 128 + linear as usize); + + let back = decode(&b).unwrap(); + assert_eq!((back.dimensions(), back.layout()), ((w, h), ChannelLayout::Rgba)); + // Steep ramps across tiny textures put three colours where a block interpolates at + // thirds, so this bound is loose; it still catches swapped channels or misplaced + // blocks. `block_compression_error_on_gradients_is_bounded` is the tight one. A BC1 + // block with transparent texels has only three colours, so BC1's colours are + // checked on the opaque ramp. + let (src, back_colour) = if compression == DdsCompression::Bc1 { + let o = opaque(&img); + let back = decode(&encode(&o, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + (o, back) + } else { + (img.clone(), back.clone()) + }; + let colour = max_colour_diff(&src, &back_colour); + assert!(colour <= 24, "{compression:?} {w}x{h}: colour off by {colour}"); + let alpha = max_diff_channel(&img, &back, 3); + match compression { + DdsCompression::Bc1 => assert!(back.data().chunks(4).zip(img.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })), + _ => assert!(alpha <= 8, "{compression:?} {w}x{h}: alpha off by {alpha}"), + } + } + } +} + +#[test] +fn gray_and_rgb_sources_are_written_as_rgba_blocks() { + for layout in [ChannelLayout::Gray, ChannelLayout::GrayA, ChannelLayout::Rgb] { + for compression in BLOCKS { + let img = ramp(8, 8, layout); + let back = decode(&encode(&img, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + let want = img.convert(ChannelLayout::Rgba, img.sample_type()); + assert_eq!(back.layout(), ChannelLayout::Rgba); + let colour = max_colour_diff(&want, &back); + assert!(colour <= 8, "{layout:?} {compression:?}: colour off by {colour}"); + } + } +} + +#[test] +fn block_compression_error_on_gradients_is_bounded() { + let (line, plane) = (ramp(64, 64, ChannelLayout::Rgba), gradient(64, 64)); + for compression in BLOCKS { + let roundtrip = |img: &Image| decode(&encode(img, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + let (line_back, plane_back) = (roundtrip(&line), roundtrip(&plane)); + let (line_err, plane_err) = (max_colour_diff(&line, &line_back), max_colour_diff(&plane, &plane_back)); + let p = psnr(&plane, &plane_back); + let alpha = max_diff_channel(&line, &line_back, 3); + // Colours on a line only lose the RGB565 rounding of the endpoints (up to 4 levels in + // red and blue). A gradient in two directions is not on a line: the spread off a + // block's best line alone limits this one to about 40 dB, and RGB565 costs a little + // more (the encoder measures 38.6 dB and 9 levels at most). + assert!(line_err <= 5, "{compression:?}: colour ramp off by {line_err}"); + assert!(plane_err <= 10, "{compression:?}: 2D gradient off by {plane_err}"); + assert!(p >= 38.0, "{compression:?}: 2D gradient PSNR {p:.1} dB"); + match compression { + DdsCompression::Bc1 => assert!(line_back.data().chunks(4).zip(line.data().chunks(4)).all(|(b, i)| b[3] == if i[3] < 128 { 0 } else { 255 })), + // Four bits: within half a step of 17. + DdsCompression::Bc2 => assert!(alpha <= 8, "BC2 alpha off by {alpha}"), + // Eight values across a block's few levels of alpha. + _ => assert!(alpha <= 2, "BC3 alpha off by {alpha}"), + } + } +} + +#[test] +fn solid_and_cutout_textures_keep_their_values() { + // RGB565-exact colours and BC2's 4-bit alpha steps come back exactly. + let solid = Image::from_u8(6, 5, ChannelLayout::Rgba, [255, 0, 255, 170].repeat(30)).unwrap(); + for compression in BLOCKS { + let back = decode(&encode(&solid, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + let want = if compression == DdsCompression::Bc1 { [255, 0, 255, 255] } else { [255, 0, 255, 170] }; + assert!(back.data().chunks(4).all(|p| p == want), "{compression:?}: {:?}", &back.data()[..4]); + } + // A cutout: BC1's transparent texels decode as transparent black, the rest stay opaque. + let cutout: Vec = (0..36).flat_map(|i| if (i / 6 + i % 6) % 2 == 0 { [200, 40, 40, 255] } else { [10, 10, 10, 0] }).collect(); + let cutout = Image::from_u8(6, 6, ChannelLayout::Rgba, cutout).unwrap(); + for compression in BLOCKS { + let back = decode(&encode(&cutout, Format::Dds, &opts(compression, false)).unwrap()).unwrap(); + assert_eq!(max_diff_channel(&cutout, &back, 3), 0, "{compression:?}"); + if compression == DdsCompression::Bc1 { + assert!(back.data().chunks(4).filter(|p| p[3] == 0).all(|p| p == [0, 0, 0, 0])); + } + } +} + +#[test] +fn mipmaps_write_the_full_chain_box_filtered() { + // 16×8 halves to 8×4, 4×2, 2×1 and 1×1: five levels. + let img = ramp(16, 8, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(DdsCompression::None, true)).unwrap(); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_PITCH | DDSD_MIPMAPCOUNT); + assert_eq!(le32(&b, 28), 5); + assert_eq!(le32(&b, 108), DDSCAPS_TEXTURE | DDSCAPS_COMPLEX | DDSCAPS_MIPMAP); + assert_eq!(b.len(), 128 + 4 * (16 * 8 + 8 * 4 + 4 * 2 + 2 + 1)); + assert_eq!(decode(&b).unwrap().data(), img.data(), "the reader still reads the top level"); + let mut above = img.clone(); + for i in 1..5 { + let got = level(&b, i); + assert_eq!(got.dimensions(), ((16 >> i).max(1), (8 >> i).max(1))); + let want = box_filter(&above); + assert_eq!(got.data(), want.data(), "level {i}"); + above = got; + } + // 1×1 has a single level. + let one = encode(&ramp(1, 1, ChannelLayout::Rgba), Format::Dds, &opts(DdsCompression::None, true)).unwrap(); + assert_eq!((le32(&one, 28), le32(&one, 8) & DDSD_MIPMAPCOUNT), (1, 0)); +} + +/// The documented filter, written independently: each pixel averages the 2×2 pixels it covers, +/// and the last column and row of an odd-sized level take in the leftover pixel too. +fn box_filter(src: &Image) -> Image { + let (w, h) = (src.width() as usize, src.height() as usize); + let (nw, nh) = ((w / 2).max(1), (h / 2).max(1)); + let ch = src.layout().channels(); + let span = |i: usize, n: usize, size: usize| (2 * i, if i + 1 == n { size } else { 2 * i + 2 }); + let mut out = Vec::new(); + for y in 0..nh { + for x in 0..nw { + let ((x0, x1), (y0, y1)) = (span(x, nw, w), span(y, nh, h)); + for c in 0..ch { + let values: Vec = + (y0..y1).flat_map(|sy| (x0..x1).map(move |sx| (sy, sx))).map(|(sy, sx)| u32::from(src.data()[(sy * w + sx) * ch + c])).collect(); + let n = values.len() as u32; + out.push(((values.iter().sum::() + n / 2) / n) as u8); + } + } + } + Image::from_u8(nw as u32, nh as u32, src.layout(), out).unwrap() +} + +#[test] +fn odd_sized_mip_chains_keep_every_pixel() { + // 5×3 → 2×1 → 1×1. The 2×1 level's right pixel averages columns 2–4 of all three rows. + let img = ramp(5, 3, ChannelLayout::Gray); + let b = encode(&img, Format::Dds, &opts(DdsCompression::None, true)).unwrap(); + assert_eq!(le32(&b, 28), 3); + assert_eq!(b.len(), 128 + 5 * 3 + 2 + 1); + let second = level(&b, 1); + assert_eq!(second.data(), box_filter(&img).data()); + let px = |x: usize, y: usize| u32::from(img.data()[y * 5 + x]); + let right: u32 = (0..3).flat_map(|y| (2..5).map(move |x| (x, y))).map(|(x, y)| px(x, y)).sum(); + assert_eq!(u32::from(second.data()[1]), (right + 4) / 9); +} + +#[test] +fn block_compressed_mip_chains_have_a_block_per_small_level() { + for compression in BLOCKS { + let block = if compression == DdsCompression::Bc1 { 8 } else { 16 }; + let img = ramp(12, 6, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(compression, true)).unwrap(); + // 12×6, 6×3, 3×1, 1×1: 3×2, 2×1, 1 and 1 blocks. + assert_eq!(le32(&b, 28), 4); + assert_eq!(le32(&b, 8), REQUIRED | DDSD_LINEARSIZE | DDSD_MIPMAPCOUNT); + assert_eq!(le32(&b, 20), 6 * block); + assert_eq!(b.len(), 128 + (6 + 2 + 1 + 1) * block as usize); + for i in 0..4 { + let got = level(&b, i); + assert_eq!(got.dimensions(), ((12 >> i).max(1), (6 >> i).max(1)), "{compression:?} level {i}"); + } + } +} + +#[test] +fn strips_and_tiny_textures_encode_with_every_option() { + for (w, h) in [(1, 1), (1, 9), (9, 1), (2, 3), (3, 2)] { + for compression in DdsCompression::ALL { + for mipmaps in [false, true] { + let img = ramp(w, h, ChannelLayout::Rgba); + let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap_or_else(|e| panic!("{w}x{h} {compression:?} {mipmaps}: {e}")); + assert_eq!(decode(&b).unwrap().dimensions(), (w, h)); + } + } + } +} + +#[test] +fn fidelity_warnings_follow_the_compression() { + let translucent = ramp(8, 8, ChannelLayout::Rgba); + let warns = |c| fidelity_warnings_with(&translucent, Format::Dds, &opts(c, false)); + assert!(warns(DdsCompression::None).is_empty(), "uncompressed RGBA loses nothing"); + for c in BLOCKS { + assert!(warns(c).contains(&FidelityWarning::LossyCompression), "{c:?}"); + } + assert!(warns(DdsCompression::Bc1).contains(&FidelityWarning::AlphaBinarized)); + assert!(!warns(DdsCompression::Bc3).contains(&FidelityWarning::AlphaBinarized)); +} + +#[test] +fn compression_names_round_trip() { + for c in DdsCompression::ALL { + assert_eq!(DdsCompression::from_name(c.name()), Some(c)); + } + assert_eq!(DdsCompression::from_name("DXT5"), Some(DdsCompression::Bc3)); + assert_eq!(DdsCompression::from_name("dxt1"), Some(DdsCompression::Bc1)); + for bad in ["", "bc7", "dxt2", "uncompressed "] { + assert_eq!(DdsCompression::from_name(bad), None, "{bad:?}"); + } +} + +/// Encode timings on a synthetic ~30 MP texture (6336×4752). Ignored by default; run in release: +/// +/// ```sh +/// cargo test --release -p photocraft-codecs --test dds_write -- --ignored --nocapture +/// ``` +#[test] +#[ignore] +fn dds_encode_timings_on_30_mp() { + let (w, h) = (6336u32, 4752u32); + let mut s = 0x1234_5678u32; + let mut data = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..h { + for x in 0..w { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + data.extend([(x / 25 + y / 19) as u8, (x / 31) as u8 ^ (s as u8 & 3), (y / 23) as u8, (255 - x / 25) as u8]); + } + } + let img = Image::from_u8(w, h, ChannelLayout::Rgba, data).unwrap(); + for compression in DdsCompression::ALL { + for mipmaps in [false, true] { + let t = std::time::Instant::now(); + let b = encode(&img, Format::Dds, &opts(compression, mipmaps)).unwrap(); + eprintln!("{compression:?} mipmaps={mipmaps}: {:.0} ms, {} MB", t.elapsed().as_secs_f64() * 1e3, b.len() >> 20); + } + } +} diff --git a/crates/codecs/tests/roundtrip.rs b/crates/codecs/tests/roundtrip.rs index 7918d313b6..9c6cb8cb6f 100644 --- a/crates/codecs/tests/roundtrip.rs +++ b/crates/codecs/tests/roundtrip.rs @@ -137,6 +137,9 @@ mod fits { mod dpx { cases!(Format::Dpx); } +mod dds { + cases!(Format::Dds); +} mod qoi { cases!(Format::Qoi); } diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index 2299aa3e49..f9cee9e214 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -288,8 +288,8 @@ pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { Ok(r.document) } -/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits, PSD -/// previews and the PSD merged image. +/// What a headless save writes beyond the format: JPEG quality, TIFF layers, Targa bits, DPX +/// bits, DDS compression and mipmaps, PSD previews and the PSD merged image. #[derive(Debug, Clone, Copy)] pub(crate) struct SaveOpts { /// Photoshop's 0–12 JPEG scale. @@ -301,6 +301,9 @@ pub(crate) struct SaveOpts { pub tga_bits: Option, /// DPX: 8, 10, 12 or 16 bits per sample (`"dpxBits"`); unset, 8 for an 8-bit document, else 16. pub dpx_bits: Option, + /// DDS: the compression and whether to write the mip chain (`"ddsCompression"`, + /// `"ddsMipmaps"`); unset, uncompressed without mipmaps. + pub dds: photocraft_io::DdsOptions, /// PSD/PSB: embed the thumbnail resource (Preferences › File Handling › Image Previews). pub image_previews: bool, /// PSD/PSB: write the real merged image (Preferences › File Handling › Maximize PSD and PSB @@ -310,7 +313,15 @@ pub(crate) struct SaveOpts { impl Default for SaveOpts { fn default() -> Self { - SaveOpts { quality: None, tiff_layers: false, tga_bits: None, dpx_bits: None, image_previews: true, psd_maximize_compatibility: true } + SaveOpts { + quality: None, + tiff_layers: false, + tga_bits: None, + dpx_bits: None, + dds: photocraft_io::DdsOptions::default(), + image_previews: true, + psd_maximize_compatibility: true, + } } } @@ -326,6 +337,7 @@ impl SaveOpts { tiff_layers: p.get("tiffLayers").and_then(Value::as_bool).unwrap_or(false), tga_bits: tga_bits_param(p, cmd)?, dpx_bits: dpx_bits_param(p, cmd)?, + dds: dds_param(p, cmd)?.unwrap_or_default(), image_previews: file_handling.image_previews != crate::prefs::Ask::Never, psd_maximize_compatibility: file_handling.maximize_psd_compatibility != crate::prefs::Ask::Never, }) @@ -370,6 +382,30 @@ pub fn dpx_bits_param(p: &Value, cmd: &str) -> Result Result> { + let bad = |msg: String| EngineError::BadParams { cmd: cmd.into(), msg }; + let compression = match p.get("ddsCompression") { + None | Some(Value::Null) => None, + Some(v) => Some( + v.as_str() + .and_then(photocraft_io::DdsCompression::from_name) + .ok_or_else(|| bad(format!("`ddsCompression` must be \"none\", \"bc1\", \"bc2\" or \"bc3\", got {v}")))?, + ), + }; + let mipmaps = match p.get("ddsMipmaps") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_bool().ok_or_else(|| bad(format!("`ddsMipmaps` must be true or false, got {v}")))?), + }; + if compression.is_none() && mipmaps.is_none() { + return Ok(None); + } + Ok(Some(photocraft_io::DdsOptions { compression: compression.unwrap_or_default(), mipmaps: mipmaps.unwrap_or(false) })) +} + /// Encodes `doc` for `path`'s extension. pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> Result<(Vec, Vec)> { crate::allocation::checkpoint("saving document")?; @@ -387,6 +423,7 @@ pub(crate) fn encode(doc: &Document, path: &str, save: impl Into) -> R // lossy or lossless as it was), as Photoshop's Save does. photocraft_io::apply_file_encoding(doc, &mut opts.encode); opts.encode.dpx_bits = save.dpx_bits; + opts.encode.dds = save.dds; if let Some(q) = save.quality { let q = (q.clamp(0.0, 12.0) / 12.0 * 99.0 + 1.0).round() as u8; opts.encode.jpeg_quality = q; @@ -1651,7 +1688,7 @@ pub fn specs() -> Vec { "Save a Copy…", &["File"], Some("Cmd+Alt+S"), - r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)}"##, + r##"{"path":str (format from the extension),"quality":0..12? (JPEG),"layers":bool=true,"overwrite":bool=false (replace the document's own file),"tiffLayers":bool=false (TIFF: keep the layers; flat by default),"tgaBits":24|32? (TGA: 32 writes the alpha channel, or else the transparency, as the alpha; unset, 32 with an alpha channel or transparency, else 24),"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)}"##, native_doc, save_a_copy ), @@ -1714,7 +1751,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, batch ), @@ -1723,7 +1760,7 @@ pub fn specs() -> Vec { "Image Processor…", &["File", "Scripts"], None, - r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, image_processor ), @@ -1751,7 +1788,7 @@ pub fn specs() -> Vec { "Layers to Files…", &["File", "Export"], None, - r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16)} → {files}"##, + r##"{"dir":folder,"format":"png|jpg|psd|tiff|…"="png","prefix":str=document name,"visibleOnly":bool=true,"quality":0..12?,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain)} → {files}"##, native_doc, layers_to_files ), diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs index b07c649850..167ddfb898 100644 --- a/crates/engine/src/file_cmds/tests.rs +++ b/crates/engine/src/file_cmds/tests.rs @@ -219,6 +219,53 @@ fn save_a_copy_writes_the_dpx_bits_asked_for() { } } +/// `ddsCompression` picks the DDS FourCC (or none, uncompressed) and `ddsMipmaps` the mip count +/// in the header; unset, an uncompressed texture without mipmaps. Bad values are refused before +/// anything is written. +#[test] +fn save_a_copy_writes_the_dds_options_asked_for() { + let dir = tmp("dds-options"); + let le32 = |b: &[u8], at: usize| u32::from_le_bytes(b[at..at + 4].try_into().unwrap()); + for (params, fourcc, mips) in [ + (json!({}), [0; 4], 1), + (json!({"ddsCompression": "none", "ddsMipmaps": true}), [0; 4], 5), + (json!({"ddsCompression": "bc1"}), *b"DXT1", 1), + (json!({"ddsCompression": "DXT3", "ddsMipmaps": false}), *b"DXT3", 1), + (json!({"ddsCompression": "bc3", "ddsMipmaps": true}), *b"DXT5", 5), + (json!({"ddsCompression": null, "ddsMipmaps": null}), [0; 4], 1), + ] { + let mut s = session(16, 12, 8); + let out = join(&dir, "a.dds"); + let mut p = params.clone(); + p["path"] = json!(out); + s.execute("file.saveACopy", p).unwrap(); + let bytes = std::fs::read(&out).unwrap(); + assert_eq!((&bytes[..4], &bytes[84..88], le32(&bytes, 28)), (&b"DDS "[..], &fourcc[..], mips), "{params}"); + assert_eq!(photocraft_io::import("a.dds", &bytes).unwrap().document.size, photocraft_geom::Size::new(16, 12), "{params}"); + } + let mut s = session(8, 8, 8); + let state = |s: &Session| s.active().map(|st| (st.revision, st.path.clone(), st.is_dirty())); + let before = state(&s); + for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsCompression": 1}), json!({"ddsMipmaps": "yes"}), json!({"ddsMipmaps": 1})] { + let out = join(&dir, "bad.dds"); + let mut p = bad.clone(); + p["path"] = json!(out); + let r = s.execute("file.saveACopy", p); + assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}"); + assert!(!std::path::Path::new(&out).exists(), "{bad}: nothing written"); + assert_eq!(state(&s), before, "{bad}: the document is untouched"); + } +} + +#[test] +fn dds_params_are_none_until_one_is_given() { + use photocraft_io::{DdsCompression, DdsOptions}; + assert_eq!(dds_param(&json!({}), "file.saveAs").unwrap(), None); + assert_eq!(dds_param(&json!({"ddsCompression": null}), "file.saveAs").unwrap(), None); + assert_eq!(dds_param(&json!({"ddsMipmaps": true}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::None, mipmaps: true })); + assert_eq!(dds_param(&json!({"ddsCompression": "bc2"}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::Bc2, mipmaps: false })); +} + /// A `tgaBits` other than 24 or 32 is a bad parameter, reported before anything is written. #[test] fn bad_targa_bits_are_refused_before_writing() { diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 00163e93c0..f604b8c174 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -68,8 +68,8 @@ pub mod text_styles_map; pub mod tiff_layers; pub mod vector_map; -pub use photocraft_codecs::DpxBits; use photocraft_codecs::{CodecError, EncodeOptions}; +pub use photocraft_codecs::{DdsCompression, DdsOptions, DpxBits}; use photocraft_doc::{Adjustment, Document, Layer, LayerContent}; use photocraft_psd::{PsdError, PsdFile}; diff --git a/crates/ui-egui/examples/snapshot.rs b/crates/ui-egui/examples/snapshot.rs index 0d227255db..c6ca4cd605 100644 --- a/crates/ui-egui/examples/snapshot.rs +++ b/crates/ui-egui/examples/snapshot.rs @@ -54,6 +54,7 @@ fn main() { opts.encode.webp_quality = q; } opts.tga_bits = settings.tga_bits; + opts.encode.dds = settings.dds; photocraft_io::export(doc, path, &opts).map(|r| (r.bytes, r.warnings)).map_err(|e| e.to_string()) })), write: Some(Box::new(|path: &str, bytes: &[u8]| photocraft_format::atomic_write(std::path::Path::new(path), bytes).map_err(|e| e.to_string()))), diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 581925f83c..321c73ec60 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1280,10 +1280,10 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest) } None => err("missing `path`"), }, - "app.save" => match crate::targa_options_ui::bits_param(p, "app.save") { - Ok(tga_bits) => { + "app.save" => match crate::FormatChoices::from_params(p, "app.save") { + Ok(choices) => { let path = s("path").map(str::to_string); - run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, tga_bits)) + run_waiting(app, p.get("wait").and_then(Value::as_bool).unwrap_or(true), move |app| app.save_automation_with(path, choices)) } Err(e) => err(e), }, @@ -2441,6 +2441,37 @@ mod tests { assert_eq!(written.borrow().len(), 3, "a bad tgaBits writes nothing"); } + /// `app.save` takes the DDS options (`ddsCompression`, `ddsMipmaps`) and never stops at DDS + /// Options. + #[test] + fn automation_save_passes_dds_options_without_asking() { + use photocraft_io::{DdsCompression, DdsOptions}; + use std::cell::RefCell; + use std::rc::Rc; + let asked: Rc>> = Rc::default(); + let a = asked.clone(); + let services = crate::Services { + export: Some(Box::new(move |_d: &photocraft_doc::Document, _p: &str, s: &crate::ExportSettings| { + a.borrow_mut().push(s.dds); + Ok((b"out".to_vec(), Vec::new())) + })), + automation_write: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 8, "height": 8})).unwrap(); + for params in [json!({"path": "a.dds"}), json!({"path": "b.dds", "ddsCompression": "bc1", "ddsMipmaps": true})] { + let r = call(&mut app, &ctx, "app.save", params.clone()); + assert_eq!(r["result"]["path"], params["path"], "{r}"); + assert!(app.dds_options.is_none(), "automation saves never prompt"); + } + assert_eq!(*asked.borrow(), [DdsOptions::default(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }]); + let r = call(&mut app, &ctx, "app.save", json!({"path": "c.dds", "ddsCompression": "bc9"})); + assert!(r["error"].as_str().unwrap().contains("ddsCompression"), "{r}"); + assert_eq!(asked.borrow().len(), 2, "a bad ddsCompression writes nothing"); + } + #[test] fn automation_open_and_save_use_the_roots_and_reply_with_warnings() { use photocraft_color::{ColorMode, SampleType}; diff --git a/crates/ui-egui/src/dds_options_ui.rs b/crates/ui-egui/src/dds_options_ui.rs new file mode 100644 index 0000000000..c795643a7d --- /dev/null +++ b/crates/ui-egui/src/dds_options_ui.rs @@ -0,0 +1,148 @@ +//! DDS Options: the compression and mip chain File › Save As and Save a Copy ask for before +//! writing a DirectDraw Surface texture (#1327). Photoshop has no DDS writer of its own (a plug-in +//! adds one), so this follows the texture tools' usual choices: uncompressed, or BC1/BC2/BC3 +//! (DXT1/DXT3/DXT5), and whether to generate mipmaps (see `photocraft_io::DdsOptions`). +//! +//! The save is parked in [`Prompt`] while the modal is up (egui is immediate-mode) and written +//! once answered. Cancel drops the save. Scripts skip the prompt by passing `ddsCompression` or +//! `ddsMipmaps`. + +use photocraft_io::{DdsCompression, DdsOptions}; + +use crate::{ExportSettings, PhotocraftApp}; + +/// A save waiting on the DDS Options answer. +pub struct Prompt { + /// The document that requested the save, even if tabs change while this is open. + doc: photocraft_doc::DocId, + /// Where the texture goes. + pub path: String, + /// The options chosen, starting uncompressed without mipmaps. + pub options: DdsOptions, + /// Save a Copy: the document keeps its path and unsaved changes. + pub copy: bool, + /// The step the answered save is recorded as (`file.saveAs` or `file.saveACopy`), so an + /// action being recorded keeps it; `file.save` when File › Save confirmed the document's own + /// texture (#3531), which plays back on the file the action is played on. + pub record: &'static str, +} + +/// `true` when `path` names a DDS texture. +pub fn wants_prompt(path: &str) -> bool { + photocraft_engine::file_cmds::extension(path).and_then(|e| photocraft_codecs::from_extension(&e)) == Some(photocraft_codecs::Format::Dds) +} + +/// The DDS options a command or control call asks for (`"ddsCompression"`, `"ddsMipmaps"`), +/// which skip the prompt. +pub fn options_param(params: &serde_json::Value, cmd: &str) -> Result, String> { + photocraft_engine::file_cmds::dds_param(params, cmd).map_err(|e| e.to_string()) +} + +/// The params a save with `options` is recorded with. +pub fn record(options: DdsOptions, step: &mut serde_json::Value) { + step["ddsCompression"] = options.compression.name().into(); + step["ddsMipmaps"] = options.mipmaps.into(); +} + +/// Parks the save behind the prompt. A prompt already waiting is never replaced. +pub fn park(app: &mut PhotocraftApp, path: String, copy: bool, record: &'static str) -> Result<(), String> { + if app.save_options_open() { + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); + } + let doc = app.active_doc_id()?; + app.dds_options = Some(Prompt { doc, path, options: DdsOptions::default(), copy, record }); + Ok(()) +} + +/// The block compressions go by their format names, which stay untranslated like other +/// technology names. +fn label(c: DdsCompression) -> &'static str { + match c { + DdsCompression::None => tl!("None"), + DdsCompression::Bc1 => "BC1 / DXT1", + DdsCompression::Bc2 => "BC2 / DXT3", + DdsCompression::Bc3 => "BC3 / DXT5", + } +} + +pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { + let Some(p) = &mut app.dds_options else { return }; + let (mut ok, mut cancel) = (false, false); + let mut options = p.options; + let modal = egui::Modal::new(egui::Id::new("dds-options")).show(ctx, |ui| { + ui.set_max_width(340.0); + ui.label(egui::RichText::new(tl!("DDS Options")).font(crate::theme::semibold(15.0))); + ui.add_space(4.0); + crate::widgets::hairline(ui); + ui.add_space(8.0); + crate::widgets::section_label(ui, tl!("Compression")); + for c in DdsCompression::ALL { + ui.radio_value(&mut options.compression, c, label(c)); + } + ui.add_space(8.0); + crate::widgets::checkbox(ui, &mut options.mipmaps, tl!("Generate Mipmaps")); + ui.add_space(12.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.spacing_mut().item_spacing.x = 10.0; + ok = crate::widgets::primary_button(ui, tl!("OK"), 84.0).clicked(); + cancel = crate::widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked(); + }); + }); + cancel |= modal.should_close(); + p.options = options; + // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels. + if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) { + let Some(p) = app.dds_options.take() else { return }; + let settings = ExportSettings { dds: p.options, ..app.save_settings() }; + let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) }; + record(p.options, &mut step); + let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy)); + if written.is_ok() { + // An action being recorded keeps the Save As or Save a Copy with this answer. + app.session.journal.push((p.record.into(), step)); + } + match written { + Err(e) => { + app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]); + app.ui.status_error = true; + } + Ok(Some(_)) if !p.copy => crate::discard_ui::saved_document(app, ctx, p.doc), + // A background save releases the close prompt when it finishes (`jobs_ui`). + Ok(_) => {} + } + } else if cancel { + app.dds_options = None; + app.ui.status = tl!("Save cancelled").into(); + app.ui.status_error = false; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dds_names() { + assert!(wants_prompt("a.dds")); + assert!(wants_prompt("dir/sub/a.DDS")); + assert!(wants_prompt("C:\\x\\y.dds")); + assert!(!wants_prompt("a.dds.psd")); + assert!(!wants_prompt(".dds")); + assert!(!wants_prompt("a.png")); + } + + #[test] + fn options_params() { + use serde_json::json; + assert_eq!(options_param(&json!({}), "file.saveAs"), Ok(None)); + assert_eq!(options_param(&json!({"ddsCompression": "bc3"}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc3, mipmaps: false }))); + assert_eq!(options_param(&json!({"ddsMipmaps": true}), "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::None, mipmaps: true }))); + for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsCompression": 3}), json!({"ddsMipmaps": "yes"})] { + assert!(options_param(&bad, "file.saveAs").is_err(), "{bad}"); + } + let mut step = json!({"path": "a.dds"}); + record(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }, &mut step); + assert_eq!(step, json!({"path": "a.dds", "ddsCompression": "bc1", "ddsMipmaps": true})); + assert_eq!(options_param(&step, "file.saveAs"), Ok(Some(DdsOptions { compression: DdsCompression::Bc1, mipmaps: true }))); + } +} diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rs index 82e4497d92..e9b5504bea 100644 --- a/crates/ui-egui/src/discard_ui.rs +++ b/crates/ui-egui/src/discard_ui.rs @@ -959,6 +959,9 @@ mod tests { #[path = "targa_tests.rs"] mod targa_tests; + #[path = "dds_tests.rs"] + mod dds_tests; + /// One frame with the window's close button pressed; the commands the guard sent. fn window_close_commands(app: &mut PhotocraftApp) -> Vec { let mut info = egui::ViewportInfo::default(); diff --git a/crates/ui-egui/src/discard_ui/tests/dds_tests.rs b/crates/ui-egui/src/discard_ui/tests/dds_tests.rs new file mode 100644 index 0000000000..f1c88dec81 --- /dev/null +++ b/crates/ui-egui/src/discard_ui/tests/dds_tests.rs @@ -0,0 +1,217 @@ +//! DDS Options on Save As and Save a Copy: the compression and mipmaps it asks for, the scripted +//! `ddsCompression` and `ddsMipmaps` that skip it, and action recording and playback (#1327). +use super::*; +use crate::{FileDialogAnswer, dds_options_ui}; +use egui_kittest::kittest::Queryable; +use photocraft_io::{DdsCompression, DdsOptions}; +use std::{cell::RefCell, rc::Rc}; + +/// Each write: the path, and the DDS options the export was asked for. +type Writes = Rc>>; + +const PLAIN: DdsOptions = DdsOptions { compression: DdsCompression::None, mipmaps: false }; + +/// One 8×8 RGB document whose exports record their DDS options, in a harness showing DDS Options +/// and answering a save dialog with `to`. +fn dds_app(to: &str) -> (Prompted, Writes) { + let mut app = app_with_docs(1); + let writes: Writes = Rc::default(); + let (asked, written) = (Rc::new(RefCell::new(PLAIN)), writes.clone()); + let seen = asked.clone(); + app.services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo(to.into()))]).0); + app.services.export = Some(Box::new(move |_, _, settings| { + *seen.borrow_mut() = settings.dds; + Ok((Vec::new(), Vec::new())) + })); + app.services.write = Some(Box::new(move |path, _| { + written.borrow_mut().push((path.to_string(), *asked.borrow())); + Ok(()) + })); + let h = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0)).build_ui_state( + |ui, app| { + show(app, ui.ctx()); + dds_options_ui::show(app, ui.ctx()); + app.poll_file_dialog(ui.ctx(), None); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.ctx.set_os(egui::os::OperatingSystem::Windows); + (h, writes) +} + +/// Save As to a DDS texture asks first, starting uncompressed without mipmaps, and writes only +/// what is chosen once answered. +#[test] +fn save_as_to_a_dds_texture_asks_for_its_compression() { + let (mut h, writes) = dds_app("unused.dds"); + h.state_mut().save_as(Some("t.dds".into())).unwrap(); + h.run_steps(2); + assert_eq!(h.state().dds_options.as_ref().map(|p| (p.options, p.copy)), Some((PLAIN, false))); + assert!(writes.borrow().is_empty(), "nothing is written before the answer"); + assert!(h.state_mut().save_as(Some("other.dds".into())).is_err(), "one save at a time"); + h.get_by_label("BC3 / DXT5").click(); + h.run_steps(2); + h.get_by_label("Generate Mipmaps").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + let chosen = DdsOptions { compression: DdsCompression::Bc3, mipmaps: true }; + assert_eq!(writes.borrow().as_slice(), &[("t.dds".to_string(), chosen)]); + assert!(h.state().dds_options.is_none()); + assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("t.dds")); + + // Cancel writes nothing. + h.state_mut().save_as(Some("c.dds".into())).unwrap(); + h.run_steps(2); + h.key_press(Key::Escape); + h.run_steps(3); + assert!(h.state().dds_options.is_none()); + assert_eq!(writes.borrow().len(), 1, "cancelled: nothing more written"); + assert_eq!(h.state().ui.status, "Save cancelled"); +} + +/// Scripts choose with `ddsCompression` or `ddsMipmaps` and are never asked; bad values write +/// nothing, and other formats aren't asked. +#[test] +fn scripted_dds_options_and_other_formats_skip_the_prompt() { + let (mut h, writes) = dds_app("unused.dds"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "s.dds", "ddsCompression": "bc1"})).unwrap(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "m.dds", "ddsMipmaps": true})).unwrap(); + assert!(h.state().dds_options.is_none()); + for bad in [json!({"ddsCompression": "bc7"}), json!({"ddsMipmaps": 1})] { + let mut p = bad.clone(); + p["path"] = json!("bad.dds"); + assert!(crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", p).is_err(), "{bad}"); + } + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "p.png"})).unwrap(); + assert!(h.state().dds_options.is_none()); + assert_eq!( + writes.borrow().as_slice(), + &[ + ("s.dds".to_string(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }), + ("m.dds".to_string(), DdsOptions { compression: DdsCompression::None, mipmaps: true }), + ("p.png".to_string(), PLAIN), + ] + ); +} + +/// Save a Copy to a DDS texture asks too, and the copy leaves the document's path and unsaved +/// state. +#[test] +fn save_a_copy_to_a_dds_texture_asks_and_keeps_the_document_unsaved() { + let (mut h, writes) = dds_app("copy.dds"); + make_dirty(h.state_mut(), 0); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().dds_options.as_ref().map(|p| (p.options, p.copy)), Some((PLAIN, true))); + assert!(dds_options_ui::park(h.state_mut(), "other.dds".into(), false, "file.saveAs").is_err(), "the waiting prompt is kept"); + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(writes.borrow().as_slice(), &[("copy.dds".to_string(), PLAIN)]); + let st = h.state().session.active().unwrap(); + assert!(st.is_dirty()); + assert_eq!(st.path, None); +} + +/// An action being recorded keeps a DDS Save As or Save a Copy with its options, answered in DDS +/// Options or scripted, and plays them back without asking. +#[test] +fn recorded_dds_saves_keep_their_options_and_replay_without_asking() { + let (mut h, writes) = dds_app("copy.dds"); + let ctx = h.ctx.clone(); + h.state_mut().run("actions.record", json!({})).unwrap(); + h.state_mut().save_as(Some("t.dds".into())).unwrap(); + h.run_steps(2); + h.get_by_label("BC1 / DXT1").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveACopy", json!({})).unwrap(); + h.run_steps(3); + h.get_by_label("Generate Mipmaps").click(); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "s.dds", "ddsCompression": "bc2"})).unwrap(); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let want = [ + ("t.dds".to_string(), DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }), + ("copy.dds".to_string(), DdsOptions { compression: DdsCompression::None, mipmaps: true }), + ("s.dds".to_string(), DdsOptions { compression: DdsCompression::Bc2, mipmaps: false }), + ]; + assert_eq!(writes.borrow().as_slice(), &want); + let steps = &h.state().session.actions.list[0].steps; + assert_eq!( + steps, + &[ + ("file.saveAs".into(), json!({"path": "t.dds", "ddsCompression": "bc1", "ddsMipmaps": false})), + ("file.saveACopy".into(), json!({"path": "copy.dds", "ddsCompression": "none", "ddsMipmaps": true})), + ("file.saveAs".into(), json!({"path": "s.dds", "ddsCompression": "bc2", "ddsMipmaps": false})) + ] + ); + writes.borrow_mut().clear(); + let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(h.state().dds_options.is_none(), "playback doesn't ask"); + assert_eq!(writes.borrow().as_slice(), &want); +} + +/// File › Save confirming the document's own texture asks DDS Options, and an action being +/// recorded keeps it as a plain Save with the answer (scripted options too): played back, it +/// writes the texture the action is played on as recorded, without asking (#3531). +#[test] +fn recorded_plain_save_of_a_dds_texture_keeps_its_options() { + let (mut h, writes) = dds_app("own.dds"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.dds", "ddsCompression": "none"})).unwrap(); + assert_eq!(h.state().session.active().unwrap().path.as_deref(), Some("own.dds")); + h.state_mut().run("actions.record", json!({})).unwrap(); + crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap(); + h.run_steps(3); + assert!(h.state().dds_options.is_some(), "confirming its own texture asks DDS Options"); + h.get_by_label("BC1 / DXT1").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + h.state_mut().services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo("own.dds".into()))]).0); + crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({"ddsCompression": "bc3", "ddsMipmaps": true})).unwrap(); + h.run_steps(3); + assert!(h.state().dds_options.is_none(), "scripted options don't ask"); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let bc1 = DdsOptions { compression: DdsCompression::Bc1, mipmaps: false }; + let bc3 = DdsOptions { compression: DdsCompression::Bc3, mipmaps: true }; + assert_eq!(&writes.borrow()[1..], &[("own.dds".to_string(), bc1), ("own.dds".to_string(), bc3)]); + let steps = &h.state().session.actions.list[0].steps; + assert_eq!( + steps, + &[ + ("file.save".into(), json!({"ddsCompression": "bc1", "ddsMipmaps": false})), + ("file.save".into(), json!({"ddsCompression": "bc3", "ddsMipmaps": true})) + ] + ); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.dds", "ddsCompression": "none"})).unwrap(); + writes.borrow_mut().clear(); + let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(h.state().dds_options.is_none(), "playback doesn't ask"); + assert_eq!(writes.borrow().as_slice(), &[("other.dds".to_string(), bc1), ("other.dds".to_string(), bc3)]); +} + +/// Enter on a focused Cancel cancels: egui clicks the focused button on Enter without consuming +/// the key, so the dialog's Enter-for-OK must not save as well. +#[test] +fn enter_on_a_focused_cancel_writes_nothing() { + let (mut h, writes) = dds_app("unused.dds"); + h.state_mut().save_as(Some("t.dds".into())).unwrap(); + h.run_steps(2); + h.get_by_label("Cancel").focus(); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + assert!(h.state().dds_options.is_none()); + assert!(writes.borrow().is_empty(), "nothing written"); + assert_eq!(h.state().ui.status, "Save cancelled"); +} diff --git a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs b/crates/ui-egui/src/discard_ui/tests/targa_tests.rs index 565fe01037..0a05370ecf 100644 --- a/crates/ui-egui/src/discard_ui/tests/targa_tests.rs +++ b/crates/ui-egui/src/discard_ui/tests/targa_tests.rs @@ -201,3 +201,46 @@ fn closing_after_a_targa_save_waits_for_targa_options() { assert!(h.state().discard.is_none()); assert!(h.state().session.documents().is_empty()); } + +/// File › Save confirming the document's own Targa asks Targa Options, and an action being +/// recorded keeps it as a plain Save with the bits chosen: played back, it writes the Targa the +/// action is played on with them, without asking (#3531). +#[test] +fn recorded_plain_save_of_a_targa_keeps_its_bits() { + let (mut h, writes) = targa_app(false, "own.tga"); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "own.tga", "tgaBits": 24})).unwrap(); + h.state_mut().run("actions.record", json!({})).unwrap(); + crate::menus::invoke(h.state_mut(), &ctx, "file.save", json!({})).unwrap(); + h.run_steps(3); + assert!(h.state().targa_options.is_some(), "confirming its own Targa asks Targa Options"); + h.get_by_label("32 bits/pixel").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(3); + h.state_mut().run("actions.stop", json!({})).unwrap(); + let steps = &h.state().session.actions.list[0].steps; + assert_eq!(steps, &[("file.save".into(), json!({"tgaBits": 32}))]); + crate::menus::invoke(h.state_mut(), &ctx, "file.saveAs", json!({"path": "other.tga", "tgaBits": 24})).unwrap(); + writes.borrow_mut().clear(); + let played = h.state_mut().run("actions.play", json!({"action": 0})).unwrap(); + assert!(played.get("failed").is_none(), "{played}"); + assert!(h.state().targa_options.is_none(), "playback doesn't ask"); + assert_eq!(writes.borrow().as_slice(), &[("other.tga".to_string(), asked(Some(32)))]); +} + +/// Enter on a focused Cancel cancels: egui clicks the focused button on Enter without consuming +/// the key, so the dialog's Enter-for-OK must not save as well. +#[test] +fn enter_on_a_focused_cancel_writes_nothing() { + let (mut h, writes) = targa_app(false, "unused.tga"); + h.state_mut().save_as(Some("t.tga".into())).unwrap(); + h.run_steps(2); + h.get_by_label("Cancel").focus(); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + assert!(h.state().targa_options.is_none()); + assert!(writes.borrow().is_empty(), "nothing written"); + assert_eq!(h.state().ui.status, "Save cancelled"); +} diff --git a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs index f42de68ea0..eb52dfb5a8 100644 --- a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs +++ b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs @@ -79,7 +79,7 @@ fn closing_after_tiff_save_waits_for_options_and_writes_the_requested_document() #[test] fn cancelling_failing_or_copying_a_tiff_keeps_the_original_unsaved() { - for outcome in ["cancel", "export error", "write error", "copy"] { + for outcome in ["cancel", "enter on cancel", "export error", "write error", "copy"] { let (mut h, writes, saved, _) = tiff_prompt("file.close"); h.key_press(Key::Y); h.run_steps(3); @@ -90,6 +90,11 @@ fn cancelling_failing_or_copying_a_tiff_keeps_the_original_unsaved() { h.get_by_label("Discard Layers and Save a Copy").click(); h.run_steps(2); } + // Enter on a focused Cancel is its click, not OK. + "enter on cancel" => { + h.get_by_label("Cancel").focus(); + h.run_steps(2); + } _ => {} } h.key_press(if outcome == "cancel" { Key::Escape } else { Key::Enter }); diff --git a/crates/ui-egui/src/disk_change_prompt.rs b/crates/ui-egui/src/disk_change_prompt.rs index dd9b8215b9..b65985cd40 100644 --- a/crates/ui-egui/src/disk_change_prompt.rs +++ b/crates/ui-egui/src/disk_change_prompt.rs @@ -47,11 +47,11 @@ pub fn confirm(app: &mut PhotocraftApp, fields: &Map) -> Result, + /// DDS: the compression and mip chain from DDS Options (uncompressed without mipmaps unless + /// chosen). + pub dds: photocraft_io::DdsOptions, /// PSD/PSB: embed a thumbnail (Preferences › File Handling › Image Previews; see /// [`PhotocraftApp::save_settings`]). pub image_previews: bool, @@ -298,6 +302,7 @@ impl Default for ExportSettings { tiff_layers: true, xmp_all: true, tga_bits: None, + dds: photocraft_io::DdsOptions::default(), image_previews: true, psd_maximize_compatibility: true, embed_icc: true, @@ -324,6 +329,7 @@ impl ExportSettings { opts.tiff_layers = self.tiff_layers; opts.xmp = if self.xmp_all { photocraft_io::XmpEmbed::All } else { photocraft_io::XmpEmbed::None }; opts.tga_bits = self.tga_bits; + opts.encode.dds = self.dds; opts.image_previews = self.image_previews; opts.psd_maximize_compatibility = self.psd_maximize_compatibility; opts.document_path = self.document_path.clone(); @@ -331,6 +337,37 @@ impl ExportSettings { } } +/// The format answers a save takes instead of asking: the Targa bits per pixel and the DDS options +/// (`"tgaBits"`, `"ddsCompression"`, `"ddsMipmaps"`). `None` asks in Save As and takes the +/// default in automation saves, which never prompt. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct FormatChoices { + pub tga_bits: Option, + pub dds: Option, +} + +impl FormatChoices { + /// The answers in command `cmd`'s params; a bad value is an error. + pub fn from_params(params: &Value, cmd: &str) -> Result { + Ok(FormatChoices { tga_bits: targa_options_ui::bits_param(params, cmd)?, dds: dds_options_ui::options_param(params, cmd)? }) + } + + /// The export settings with these answers applied. + pub(crate) fn apply(self, settings: ExportSettings) -> ExportSettings { + ExportSettings { tga_bits: self.tga_bits, dds: self.dds.unwrap_or(settings.dds), ..settings } + } + + /// Adds the answers to a recorded save step. + fn record(self, step: &mut Value) { + if let Some(bits) = self.tga_bits { + step["tgaBits"] = bits.bits().into(); + } + if let Some(dds) = self.dds { + dds_options_ui::record(dds, step); + } + } +} + /// The document's lone layer when it is a plain raster a flat file keeps: visible, at full /// opacity, in Normal mode, with no masks, effects or blending restrictions (#2234). pub(crate) fn plain_raster(doc: &Document) -> Option<&photocraft_doc::Layer> { @@ -840,6 +877,8 @@ pub struct PhotocraftApp { pub(crate) disk_stamps: HashMap, /// A save to an RGB Targa parked behind the Targa Options prompt (see `targa_options_ui`). pub(crate) targa_options: Option, + /// A save to a DDS texture parked behind the DDS Options prompt (see `dds_options_ui`). + pub(crate) dds_options: Option, /// Files read but not opened yet: the first waits on its profile prompt, the rest behind it /// (see `open_prompt`). pub(crate) held_opens: std::collections::VecDeque, @@ -991,6 +1030,7 @@ impl PhotocraftApp { save_dirs: HashMap::new(), disk_stamps: HashMap::new(), targa_options: None, + dds_options: None, held_opens: Default::default(), allow_close: false, stylus: Default::default(), @@ -1442,21 +1482,22 @@ impl PhotocraftApp { /// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export /// warnings are also shown to the user). pub fn save_as(&mut self, path: Option) -> Result { - self.save_as_with(path, None) + self.save_as_with(path, FormatChoices::default()) } - /// [`Self::save_as`], writing a Targa with `tga_bits` per pixel when given (no Targa Options - /// prompt): `file.save` and `file.saveAs` with `tgaBits`. - pub fn save_as_with(&mut self, path: Option, tga_bits: Option) -> Result { - self.save_dialog_flow(path, tga_bits, false) + /// [`Self::save_as`], writing a Targa or DDS texture with the `choices` given instead of + /// asking for them (no Targa or DDS Options prompt): `file.save` and `file.saveAs` with + /// `tgaBits`, `ddsCompression` or `ddsMipmaps`. + pub fn save_as_with(&mut self, path: Option, choices: FormatChoices) -> Result { + self.save_dialog_flow(path, choices, false) } /// [`Self::save_as_with`]. `plain_save` marks File › Save that had to ask for a file name /// (a flat file): confirming the document's own file is recorded as a `file.save` step, /// which writes whichever file the action is played on, not as a Save As to a fixed path. - pub(crate) fn save_dialog_flow(&mut self, path: Option, tga_bits: Option, plain_save: bool) -> Result { + pub(crate) fn save_dialog_flow(&mut self, path: Option, choices: FormatChoices, plain_save: bool) -> Result { if self.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } // Edit Contents documents save back into their smart object. if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") { @@ -1464,7 +1505,7 @@ impl PhotocraftApp { return Ok(serde_json::json!({"path": "smart object", "warnings": []})); } if let Some(path) = path { - return self.save_to(path, tga_bits); + return self.save_to(path, choices); } let st = self.session.active().ok_or("no document")?; // PDN imports default to our native format, which preserves Paint.NET's blend modes; @@ -1504,7 +1545,7 @@ impl PhotocraftApp { { return r; } - let r = app.save_to(path.clone(), tga_bits)?; + let r = app.save_to(path.clone(), choices)?; if plain_save && own.as_deref() == Some(path.as_str()) { app.journal_as_plain_save(&path); } @@ -1514,70 +1555,89 @@ impl PhotocraftApp { } /// [`Self::save_as_with`] once the path is known. - pub(crate) fn save_to(&mut self, path: String, tga_bits: Option) -> Result { - // An RGB Targa asks for its bits per pixel, unless the caller chose them; the save - // continues from the prompt (still a copy when it would be one without the prompt), - // which records the step once answered. - if tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { + pub(crate) fn save_to(&mut self, path: String, choices: FormatChoices) -> Result { + // An RGB Targa asks for its bits per pixel, and a DDS texture for its compression, unless + // the caller chose them; the save continues from the prompt (still a copy when it would + // be one without the prompt), which records the step once answered. + if choices.tga_bits.is_none() && targa_options_ui::wants_prompt(self, &path) { let copy = self.saves_copy(&path, None)?; targa_options_ui::park(self, path.clone(), copy, "file.saveAs")?; return Ok(serde_json::json!({"path": path, "warnings": []})); } + if choices.dds.is_none() && dds_options_ui::wants_prompt(&path) { + let copy = self.saves_copy(&path, None)?; + dds_options_ui::park(self, path.clone(), copy, "file.saveAs")?; + return Ok(serde_json::json!({"path": path, "warnings": []})); + } // A layered TIFF asks about its layers first (Preferences › File Handling); the save // continues from the prompt, which records the step once answered. if tiff_options_ui::wants_prompt(self, &path) { tiff_options_ui::park(self, path.clone())?; return Ok(serde_json::json!({"path": path, "warnings": []})); } - self.save_as_step(path, None, tga_bits) + self.save_as_step(path, None, choices) } - /// File › Save back to the document's own layered file, recorded as a `file.save` step. - pub(crate) fn save_in_place(&mut self, path: String) -> Result { + /// File › Save back to the document's own file, recorded as a `file.save` step with the + /// Targa or DDS answer in `choices` (a replayed Save of a flat file brings its own). + pub(crate) fn save_in_place(&mut self, path: String, choices: FormatChoices) -> Result { if self.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } - let r = self.write_save(path, None, None)?; - self.session.journal.push(("file.save".into(), Value::Object(Default::default()))); + let r = self.write_save(path, None, choices)?; + let mut step = Value::Object(Default::default()); + choices.record(&mut step); + self.session.journal.push(("file.save".into(), step)); Ok(r) } - /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF or - /// Targa answer), so an action being recorded keeps it (#2032). - fn save_as_step(&mut self, path: String, tiff_layers: Option, tga_bits: Option) -> Result { - let r = self.write_save(path.clone(), tiff_layers, tga_bits)?; + /// Writes the Save As and journals it as a `file.saveAs` step with its path (and TIFF, + /// Targa or DDS answer), so an action being recorded keeps it (#2032). + fn save_as_step(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { + let r = self.write_save(path.clone(), tiff_layers, choices)?; let mut step = serde_json::json!({"path": path}); if let Some(layers) = tiff_layers { step["tiffLayers"] = layers.into(); } - if let Some(bits) = tga_bits { - step["tgaBits"] = bits.bits().into(); - } + choices.record(&mut step); self.session.journal.push(("file.saveAs".into(), step)); Ok(r) } - /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]). + /// Re-label the Save As just journaled for `path` as File › Save (see [`Self::save_dialog_flow`]), + /// keeping its Targa or DDS answer so playback writes the file the same way. A save parked + /// behind Targa or DDS Options hasn't been journaled yet: it is recorded as File › Save once + /// answered. pub(crate) fn journal_as_plain_save(&mut self, path: &str) { + let parked = [self.targa_options.as_mut().map(|p| (&p.path, &mut p.record)), self.dds_options.as_mut().map(|p| (&p.path, &mut p.record))]; + if let Some((_, record)) = parked.into_iter().flatten().find(|(p, record)| p.as_str() == path && **record == "file.saveAs") { + *record = "file.save"; + return; + } if let Some(last) = self.session.journal.last_mut() && last.0 == "file.saveAs" && last.1.get("path").and_then(Value::as_str) == Some(path) - && last.1.as_object().is_some_and(|o| o.len() == 1) + && let Some(step) = last.1.as_object() + && step.keys().all(|k| matches!(k.as_str(), "path" | "tgaBits" | "ddsCompression" | "ddsMipmaps")) { - *last = ("file.save".into(), Value::Object(Default::default())); + let mut step = step.clone(); + step.remove("path"); + *last = ("file.save".into(), Value::Object(step)); } } /// Replays a recorded `file.save` / `file.saveAs` / `file.saveACopy` step: no dialog or prompt, and the - /// recorded TIFF or Targa answer (if any) stands in for the TIFF or Targa Options prompt. + /// recorded TIFF, Targa or DDS answer (if any) stands in for the TIFF, Targa or DDS Options prompt. pub(crate) fn replay_save(&mut self, id: &str, params: &Value) -> Result { if self.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } if id == "file.save" { // The file the action is played on: one that holds the whole document, or a flat // file a recorded Save confirmed in the dialog while the document is still a plain - // raster, so it is never flattened over (#3531, #3806). + // raster, so it is never flattened over (#3531, #3806). A flat file's recorded Targa + // or DDS answer stands in for the prompt. + let choices = FormatChoices::from_params(params, id)?; let st = self.session.active().ok_or("no document")?; let flat_own = |p: &str| { !photocraft_engine::file_cmds::saves_in_place(p) @@ -1587,16 +1647,16 @@ impl PhotocraftApp { let path = st.path.clone().filter(|p| photocraft_engine::file_cmds::holds_at(&st.doc, p) || flat_own(p)).ok_or( "Save writes back only to the document's own PSD, PSB, .pcraft or OpenRaster file (OpenRaster only when it holds everything), or to its own flat file while the document is a single plain layer", )?; - return self.save_in_place(path); + return self.save_in_place(path, choices); } let path = params.get("path").and_then(Value::as_str).filter(|p| !p.is_empty()).ok_or("Save As needs a `path`")?; - let tga_bits = targa_options_ui::bits_param(params, id)?; + let choices = FormatChoices::from_params(params, id)?; if id == "file.saveACopy" { // A copy: the document keeps its own file and unsaved state, as when recorded (#4373). let doc = self.session.active().ok_or("no document")?.doc.clone(); - return crate::view_cmds::write_copy(self, &doc, path, tga_bits); + return crate::view_cmds::write_copy(self, &doc, path, choices); } - self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), tga_bits) + self.save_as_step(path.to_string(), params.get("tiffLayers").and_then(Value::as_bool), choices) } /// What a save writes by default under the preferences: File Handling › Image Previews @@ -1636,11 +1696,11 @@ impl PhotocraftApp { } /// Writes the active document to a known path. `tiff_layers` is the TIFF Options answer: - /// `Some(false)` discards the layers and saves a copy. `tga_bits` is the Targa bits per - /// pixel (`None`: 32 with an alpha channel or transparency, else 24). - fn write_save(&mut self, path: String, tiff_layers: Option, tga_bits: Option) -> Result { + /// `Some(false)` discards the layers and saves a copy. `choices` are the Targa bits per + /// pixel (`None`: 32 with an alpha channel or transparency, else 24) and the DDS options. + fn write_save(&mut self, path: String, tiff_layers: Option, choices: FormatChoices) -> Result { let copy = self.saves_copy(&path, tiff_layers)?; - let settings = ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), tga_bits, ..self.save_settings() }; + let settings = choices.apply(ExportSettings { tiff_layers: tiff_layers.unwrap_or(ExportSettings::default().tiff_layers), ..self.save_settings() }); match self.write_document(path.clone(), &settings, copy)? { Some((path, warnings)) => Ok(serde_json::json!({"path": path, "warnings": warnings})), None => Ok(serde_json::json!({"path": path, "warnings": [], "pending": true, "job": self.jobs.last_started.map(|j| j.0)})), @@ -1746,9 +1806,9 @@ impl PhotocraftApp { own == path && self.services.file_stamp.as_ref().and_then(|stamp| stamp(path)).is_some_and(|now| now != *then) } - /// TIFF Options or Targa Options is waiting on an answer before a save is written. + /// TIFF, Targa or DDS Options is waiting on an answer before a save is written. pub(crate) fn save_options_open(&self) -> bool { - self.tiff_options.is_some() || self.targa_options.is_some() + self.tiff_options.is_some() || self.targa_options.is_some() || self.dds_options.is_some() } /// A print worker may still be handing a job to the system queue. @@ -1765,12 +1825,13 @@ impl PhotocraftApp { /// picker or ambient writer is reachable from this path. Returns the path /// written and the export warnings (also shown to the user). pub fn save_automation(&mut self, path: Option) -> Result { - self.save_automation_with(path, None) + self.save_automation_with(path, FormatChoices::default()) } - /// [`Self::save_automation`] writing a Targa with `tga_bits` per pixel (`None`: 32 with an - /// alpha channel or transparency, else 24). Automation saves never prompt. - pub fn save_automation_with(&mut self, path: Option, tga_bits: Option) -> Result { + /// [`Self::save_automation`] writing a Targa or DDS texture with the `choices` given (a + /// Targa's `None`: 32 with an alpha channel or transparency, else 24; a DDS texture's: + /// uncompressed without mipmaps). Automation saves never prompt. + pub fn save_automation_with(&mut self, path: Option, choices: FormatChoices) -> Result { let target = { let state = self.session.active().ok_or("no document")?; // As File › Save: without `path` only a layered file is written back (#416). @@ -1783,7 +1844,7 @@ impl PhotocraftApp { if self.background_jobs && let Some(save) = self.services.automation_save.clone() { - return match jobs_ui::start_save(self, target.clone(), ExportSettings { tga_bits, ..self.save_settings() }, false, save, true)? { + return match jobs_ui::start_save(self, target.clone(), choices.apply(self.save_settings()), false, save, true)? { Some((path, warnings)) => Ok(reply(&path, &warnings)), None => { let job = self.jobs.last_started; @@ -1793,7 +1854,7 @@ impl PhotocraftApp { } let state = self.session.active().ok_or("no document")?; let (doc, revision) = (state.doc.id, state.revision); - let settings = ExportSettings { tga_bits, ..self.save_settings() }; + let settings = choices.apply(self.save_settings()); let export = self.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(&state.doc, &target, &settings)?; let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?; @@ -2093,6 +2154,7 @@ impl eframe::App for PhotocraftApp { discard_ui::show(self, &ctx); tiff_options_ui::show(self, &ctx); targa_options_ui::show(self, &ctx); + dds_options_ui::show(self, &ctx); distort_ui::show(self, &ctx); camera_raw_ui::show(self, &ctx); wide_angle_ui::show(self, &ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ea94379685..79632791d5 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -231,16 +231,17 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: "file.save" => { // Writes back only to a layered file that holds the whole document; anything else // goes through Save As, so the original is never overwritten with less (#3806). - let tga_bits = crate::targa_options_ui::bits_param(¶ms, id)?; + let choices = crate::FormatChoices::from_params(¶ms, id)?; match params.get("path").and_then(Value::as_str) { - Some(path) => app.save_as_with(Some(path.to_string()), tga_bits), + Some(path) => app.save_as_with(Some(path.to_string()), choices), None => { let own = app.session.active().and_then(|d| d.path.clone().map(|p| (photocraft_engine::file_cmds::holds_at(&d.doc, &p), p, d))); match own { Some((true, path, d)) => { // Another app changed the file since it was opened or saved: ask first (#6596). let doc = d.doc.id; - crate::disk_change_prompt::intercept(app, doc, &path, false).unwrap_or_else(|| app.save_in_place(path)) + crate::disk_change_prompt::intercept(app, doc, &path, false) + .unwrap_or_else(|| app.save_in_place(path, crate::FormatChoices::default())) } Some((false, path, d)) if photocraft_engine::file_cmds::saves_in_place(&path) => { // Its own file is layered but can't hold what the document has now. @@ -250,11 +251,11 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: let mut lines = losses; lines.push(tl!("Choose a format that keeps it, such as Photoshop (PSD), or save a copy.").to_string()); crate::notices::post(app, title, lines, false, None); - app.save_as_with(None, tga_bits) + app.save_as_with(None, choices) } // A flat file asks for its name; confirming its own file records a // plain Save that writes the file an action is played on (#3531). - _ => app.save_dialog_flow(None, tga_bits, true), + _ => app.save_dialog_flow(None, choices, true), } } } @@ -288,8 +289,8 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: } } "file.saveAs" => { - let tga_bits = crate::targa_options_ui::bits_param(¶ms, id)?; - app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), tga_bits) + let choices = crate::FormatChoices::from_params(¶ms, id)?; + app.save_as_with(params.get("path").and_then(Value::as_str).map(str::to_string), choices) } "view.zoomIn" | "view.zoomOut" | "view.fitOnScreen" | "view.actualPixels" => app.run(id, params), "window.newWindowForDocument" => { diff --git a/crates/ui-egui/src/targa_options_ui.rs b/crates/ui-egui/src/targa_options_ui.rs index c2161a0c9b..5a8b47d589 100644 --- a/crates/ui-egui/src/targa_options_ui.rs +++ b/crates/ui-egui/src/targa_options_ui.rs @@ -21,8 +21,9 @@ pub struct Prompt { /// Save a Copy: the document keeps its path and unsaved changes. pub copy: bool, /// The step the answered save is recorded as, so an action being recorded keeps it: - /// `file.saveAs` for Save As (#2032, even when a flat Targa is written as a copy) and - /// `file.saveACopy` for Save a Copy (#4373). + /// `file.saveAs` for Save As (#2032, even when a flat Targa is written as a copy), + /// `file.saveACopy` for Save a Copy (#4373), and `file.save` when File › Save confirmed the + /// document's own Targa (#3531), which plays back on the file the action is played on. pub record: &'static str, } @@ -46,7 +47,7 @@ pub fn bits_param(params: &serde_json::Value, cmd: &str) -> Result Result<(), String> { if app.save_options_open() { - return Err("Answer TIFF or Targa Options before starting another save".into()); + return Err("Answer the TIFF, Targa or DDS Options before starting another save".into()); } let doc = app.active_doc_id()?; let bits = app.session.active().map_or(TgaBits::Bits24, |st| photocraft_io::tga_default_bits(&st.doc)); @@ -76,10 +77,12 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { }); cancel |= modal.should_close(); p.bits = bits; - if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels. + if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) { let Some(p) = app.targa_options.take() else { return }; let settings = ExportSettings { tga_bits: Some(p.bits), ..app.save_settings() }; - let step = serde_json::json!({"path": p.path, "tgaBits": p.bits.bits()}); + let mut step = if p.record == "file.save" { serde_json::json!({}) } else { serde_json::json!({"path": p.path}) }; + step["tgaBits"] = p.bits.bits().into(); let written = app.with_document(p.doc, |app| app.write_document(p.path, &settings, p.copy)); if written.is_ok() { // An action being recorded keeps the Save As or Save a Copy with this answer (#2032). diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rs index febd5964cb..eed78830a1 100644 --- a/crates/ui-egui/src/tiff_options_ui.rs +++ b/crates/ui-egui/src/tiff_options_ui.rs @@ -65,7 +65,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { cancel |= modal.should_close(); p.discard_layers = discard; p.dont_ask_again = dont_ask; - if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + // A focused button takes Enter as its click without consuming the key: Enter on Cancel cancels. + if ok || (!cancel && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter))) { let Some(p) = app.tiff_options.take() else { return }; if p.dont_ask_again { app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false); diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rs index 1da1f918d2..ae19bfa6a3 100644 --- a/crates/ui-egui/src/view_cmds.rs +++ b/crates/ui-egui/src/view_cmds.rs @@ -1442,32 +1442,32 @@ fn save_a_copy(app: &mut PhotocraftApp) -> Result { let suggested = format!("{stem} copy.psd"); // The copy is of the document as it was when asked. app.pick_save(&suggested, move |app, path| { - // An RGB Targa asks for its bits per pixel first; the copy is written from the prompt. + // An RGB Targa asks for its bits per pixel first, and a DDS texture for its compression; + // the copy is written from the prompt. let parked = app.with_document(doc.id, |app| { - let ask = crate::targa_options_ui::wants_prompt(app, &path); - if ask { + if crate::targa_options_ui::wants_prompt(app, &path) { crate::targa_options_ui::park(app, path.clone(), true, "file.saveACopy")?; + return Ok(true); } - Ok(ask) + if crate::dds_options_ui::wants_prompt(&path) { + crate::dds_options_ui::park(app, path.clone(), true, "file.saveACopy")?; + return Ok(true); + } + Ok(false) })?; if parked { return Ok(json!({"path": path, "warnings": []})); } - let r = write_copy(app, &doc, &path, None)?; + let r = write_copy(app, &doc, &path, crate::FormatChoices::default())?; app.session.journal.push(("file.saveACopy".into(), json!({"path": path}))); Ok(r) }) } /// Writes `doc` to `path` as a copy (Save a Copy, and its replayed action step): the document's -/// path and saved state are untouched. `tga_bits` is the Targa answer, when there is one. -pub(crate) fn write_copy( - app: &mut PhotocraftApp, - doc: &photocraft_doc::Document, - path: &str, - tga_bits: Option, -) -> Result { - let settings = crate::ExportSettings { tga_bits, ..app.save_settings() }; +/// path and saved state are untouched. `choices` are the Targa and DDS answers, when there are any. +pub(crate) fn write_copy(app: &mut PhotocraftApp, doc: &photocraft_doc::Document, path: &str, choices: crate::FormatChoices) -> Result { + let settings = choices.apply(app.save_settings()); let export = app.services.export.as_ref().ok_or("no exporter configured")?; let (bytes, warnings) = export(doc, path, &settings)?; let write = app.services.write.as_mut().ok_or("no writer configured")?; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 78f44b07d7..918a9f811b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -88,7 +88,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i base64 PNG data; a path is relative to the automation write root. Raises the window first (default) because occluded macOS windows stop rendering - `ui.focus`: bring the main window to the front -- `app.open {path}` / `app.save {path?, tgaBits?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. Automation saves never show TGA or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands)) +- `app.open {path}` / `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name` (directory `.pcraft` — the native on-disk form — loads through the read root's capability; the single-file (zip) form takes the bytes path), `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. `tgaBits` (24 or 32) sets a TGA's bits per pixel: 32 writes the alpha channel (or else the transparency) as its alpha, 24 none; without it, 32 with an alpha channel or transparency, else 24. `ddsCompression` (`none`, `bc1`, `bc2` or `bc3`) and `ddsMipmaps` (bool) set a DDS texture's compression and mip chain; without them, uncompressed without mipmaps. Automation saves never show TGA, DDS or TIFF options. Automation opens and saves never fire script events. Use these two rather than `file.open`, `file.save`, `file.saveAs` or `file.saveACopy`, which the control channel refuses (see [Engine commands](#engine-commands)) - `app.quit` ## Engine commands @@ -321,7 +321,7 @@ How each MCP tool maps onto control methods in bridge mode: | `doc_export_layers {dir, …}` | `engine.execute {command: "file.export.layersToFiles", params}` | | `doc_export_data_sets {dir, …}` | `engine.execute {command: "file.export.dataSetsAsFiles", params}` | | `doc_import_data_sets {path, …}` | `engine.execute {command: "file.import.variableDataSets", params}` | -| `doc_save {path?, tgaBits?}` / `doc_export {path, tgaBits?}` | `app.save {path?, tgaBits?}` | +| `doc_save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` / `doc_export {path, tgaBits?, ddsCompression?, ddsMipmaps?}` | `app.save {path?, tgaBits?, ddsCompression?, ddsMipmaps?}` | | `doc_render_preview {max_side?}` | `ui.screenshot`, returned directly as PNG image content | | `session_list`, `ui_inspect` | `ui.inspect` | | `ui_screenshot {max_side?}` | `ui.screenshot`, returned as PNG image content | @@ -378,7 +378,7 @@ no MCP framing, no app start-up per command. Configure its file access with the | `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, count}`: one file per exported layer, named like `file.export.layersToFiles` names them. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | -| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | +| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?, ddsCompression?, ddsMipmaps?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, and `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | | `doc.inspect` | `{index?}`: same JSON as `document.inspect` | | `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` | | `doc.select` / `doc.close` | `{index}` / `{index?}` | diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9b878583a0..938a723b69 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File-format parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (PNG `sTER` stereo pairing kept on save, #6063; earlier: PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-15 · **Change:** minor (DDS textures save: uncompressed or BC1–BC3, optional mip chain, DDS Options in Save As (#1327); earlier: PNG `sTER` stereo pairing kept on save, #6063; PDF write one flattened page via Save As / Save a Copy / CLI, #3401; CMYK Invert, Posterize and Threshold on the inks; smart filter masks on PSD open and save; Photoshop-oracle floor 188/258; lossy DNG, compression 34892, decodes with its levels and LinearizationTable applied to the stored 8-bit samples, FILE-215-11; CMYK Hue/Saturation and Color Balance keep the black ink; CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026 Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity and tests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write @@ -90,7 +90,7 @@ D5100 colour profile. Counts and the G14 estimate are unchanged. | Paint.NET `.pdn` | yes | no | [pdn.md](pdn.md) | | OpenRaster `.ora` | yes | yes | [ora.md](ora.md) | | ICO, QOI | yes | yes | | -| DirectDraw Surface `.dds` | yes | no | Top mip level of a 2D texture: uncompressed RGB, RGBA or luminance, BC1–BC3 (DXT1/3/5), legacy or DX10 header. Cubemaps, arrays, volumes and BC4–BC7 are refused (#1327). Photoshop needs a plug-in | +| DirectDraw Surface `.dds` | yes | yes | Opens the top mip level of a 2D texture: uncompressed RGB, RGBA or luminance, BC1–BC3 (DXT1/3/5), legacy or DX10 header. Saves a 2D texture uncompressed (BGRA, BGRX, luminance with or without alpha) or BC1–BC3 with the legacy header, optionally with its full mip chain (box filter); Save As and Save a Copy ask (DDS Options), scripts pass `ddsCompression` and `ddsMipmaps` (`--dds-compression`, `--dds-mipmaps` on the CLI). Cubemaps, arrays, volumes and BC4–BC7 are refused (#1327). Photoshop needs a plug-in | | Krita `.kra`, GIMP `.xcf`, Procreate | no | no | Not in Photoshop either | ### Affinity import notes (moved from `roadmap.md`) @@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| +| 2026-10-15 | minor | DDS textures save (#1327): uncompressed or BC1/BC2/BC3 (DXT1/3/5) from a clean-room block encoder, optional box-filtered mip chain, legacy header; DDS Options in Save As and Save a Copy, `ddsCompression`/`ddsMipmaps` for scripts, the CLI and MCP | | 2026-10-15 | minor | PNG: a stereo PNG's `sTER` pairing (PNG Extensions 1.4.0 §3.6) is read on open and written back on save, so the file still says it is a stereo pair (#6063) | | 2026-10-15 | minor | PSD guides: image resource 1092 (guides v2) gives guides their own colours on import; 1092 and 1097 (guide GUIDs) are written back only while they still describe the document's guides, so an edit no longer leaves Photoshop a stale second guide list (#5966) | | 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 |