PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Dodge and Burn tone each pixel once per stroke (#1041)
jason4shortfe6e90e676f1
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rsindex 0de1c1b0e..abcc76ded 100644--- a/crates/engine/src/retouch_cmds.rs+++ b/crates/engine/src/retouch_cmds.rs@@ -658,6 +658,77 @@ fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32}}+/// Dodge and Burn: a stroke tones each pixel once, from its original colour, mixed in by the+/// stroke's coverage there (`toned` is the full-exposure colour). Dabs build up coverage as in a+/// brush stroke, capped at full coverage, so Exposure caps a stroke the way Opacity caps a paint+/// stroke: overlapping dabs and passes within one stroke don't compound the tone curve, and a+/// new stroke builds on the last.+fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) -> DabEffect {+ /// Side of the cells that remember, per touched pixel, the coverage applied so far and the+ /// original pixel (copied from the working pixels the first time a dab reaches it). Dense+ /// cells rather than a map per pixel: a map lookup per covered pixel made long strokes with+ /// large brushes over ten times slower.+ const CELL: i32 = 64;+ struct Cell {+ cov: Vec<f32>,+ orig: Vec<f32>,+ }+ let mut cells: std::collections::HashMap<(i32, i32), Cell> = std::collections::HashMap::new();+ let a = alpha_index(&fmt);+ let n = fmt.channels();+ Box::new(move |work, fp| {+ let r = fp.rect.intersect(&work.rect);+ if r.is_empty() {+ return;+ }+ let mut enc = [0.0f32; 8];+ for cy in r.y0.div_euclid(CELL)..=(r.y1 - 1).div_euclid(CELL) {+ for cx in r.x0.div_euclid(CELL)..=(r.x1 - 1).div_euclid(CELL) {+ let cr = Rect::new(cx * CELL, cy * CELL, cx * CELL + CELL, cy * CELL + CELL);+ let part = r.intersect(&cr);+ if part.is_empty() {+ continue;+ }+ let len = (CELL * CELL) as usize;+ // Coverage -1: not touched yet, so `orig` isn't filled in for that pixel.+ let cell = cells.entry((cx, cy)).or_insert_with(|| Cell { cov: vec![-1.0; len], orig: vec![0.0; len * n] });+ for y in part.y0..part.y1 {+ for x in part.x0..part.x1 {+ let k = fp.at(x, y).clamp(0.0, 1.0);+ if k <= 0.0 {+ continue;+ }+ let i = ((y - cr.y0) * CELL + (x - cr.x0)) as usize;+ let (Some(prev), Some(src)) = (cell.cov.get_mut(i), cell.orig.get_mut(i * n..i * n + n)) else { continue };+ if *prev < 0.0 {+ // First touch: the working pixel is still the original.+ src.copy_from_slice(work.px(x, y));+ *prev = 0.0;+ }+ // Dabs build up the stroke's coverage as a brush stroke's do (flow), up+ // to full coverage; the tone is applied once, from the original.+ let k = *prev + k * (1.0 - *prev);+ if k <= *prev {+ continue;+ }+ *prev = k;+ let o = to_rgba(&fmt, src);+ let t = toned([o[0], o[1], o[2]]);+ let m = [o[0] + (t[0] - o[0]) * k, o[1] + (t[1] - o[1]) * k, o[2] + (t[2] - o[2]) * k];+ from_rgba_into(&fmt, [m[0], m[1], m[2], o[3]], &mut enc);+ let px = work.px_mut(x, y);+ for c in 0..n {+ if Some(c) != a {+ px[c] = enc[c];+ }+ }+ }+ }+ }+ }+ })+}+fn tone_range(p: &Value, cmd: &str) -> Result<ToneRange> {match string(p, "range", "midtones") {"shadows" => Ok(ToneRange::Shadows),@@ -732,9 +803,7 @@ impl DabTool {fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect {let sp = spacing;match self.clone() {- Self::Tone { burn, range, exposure, protect } => {- Box::new(move |work, fp| color_dab(&fmt, work, fp, exposure, sp, |c, k| dodge_burn(c, k, range, burn, protect)))- }+ Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)),// Flow is already in each dab's coverage; a full-flow pass moves colours half-way.Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))),Self::Focus { sharpen, strength, protect, sigma } => {diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rsindex aae6d6dc6..1b6ddd13c 100644--- a/crates/engine/src/retouch_cmds/tests.rs+++ b/crates/engine/src/retouch_cmds/tests.rs@@ -229,6 +229,22 @@ fn dodge_brightens_midtones_more_than_shadows_and_burn_darkens() {assert_eq!(s.active().unwrap().doc.mode, ColorMode::Grayscale);}+#[test]+fn dodge_does_not_compound_within_a_stroke() {+ // Going back over the same spot in one stroke tones it no further; a second stroke does.+ let once = |pts: Value| {+ let mut s = session(80, 20, 8, "rgb");+ paint_layer(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]);+ s.execute("paint.dodge", json!({"points": pts, "size": 10, "hardness": 100})).unwrap();+ (rgba(&s, 40, 10)[0], s)+ };+ let (single, mut s) = once(json!([[5, 10], [75, 10]]));+ let (scrubbed, _) = once(json!([[5, 10], [75, 10], [5, 10], [75, 10]]));+ assert!(single > 0.55 && (single - scrubbed).abs() < 1.0 / 255.0, "{single} {scrubbed}");+ s.execute("paint.dodge", json!({"points": [[5, 10], [75, 10]], "size": 10, "hardness": 100})).unwrap();+ assert!(rgba(&s, 40, 10)[0] > single + 0.02);+}+#[test]fn sponge_reduces_and_increases_saturation() {for depth in DEPTHS {@@ -1116,3 +1132,35 @@ fn live_clone_matches_the_commit() {}}}++/// The live Dodge shows what the commit paints, also where a stroke doubles back across the+/// cells that remember each pixel's original colour (the live stroke edits one dab at a time).+/// 32-bit, so the live working copy isn't quantised between dabs.+#[test]+fn live_dodge_matches_the_commit_across_cells() {+ let mut s = session(200, 90, 32, "rgb");+ paint_layer(&mut s, texture);+ let all = [[10.0, 40.0], [100.0, 60.0], [180.0, 40.0], [60.0, 30.0], [150.0, 70.0]];+ let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::<Vec<_>>();+ let opts = |p: &[[f64; 2]]| json!({"points": p, "size": 40, "hardness": 30, "exposure": 60, "range": "midtones"});+ let mut live = LiveDab::begin(&s, "paint.dodge", &opts(&all[..1])).unwrap();+ live.push(&pts(&all[1..3])).unwrap();+ live.push(&pts(&all[3..])).unwrap();+ let shown = live.doc.clone();+ s.execute("paint.dodge", opts(&all)).unwrap();+ let id = s.active().unwrap().active_layer.unwrap();+ let (a, b) = (shown.layer(id).unwrap().surface().unwrap(), s.active().unwrap().doc.layer(id).unwrap().surface().unwrap());+ let (mut changed, mut worst) = (false, 0.0f32);+ for y in 0..90 {+ for x in 0..200 {+ let (got, want) = (a.rgba(x, y), b.rgba(x, y));+ changed |= (want[0] - texture(x, y)[0]).abs() > 0.02;+ // The commit also lays the stroke's last dab, which the live stroke shows on release.+ if (x - 150).pow(2) + (y - 70).pow(2) > 25 * 25 {+ worst = (0..4).map(|c| (got[c] - want[c]).abs()).fold(worst, f32::max);+ }+ }+ }+ assert!(changed);+ assert!(worst <= 1e-4, "live and commit differ by {worst}");+}