PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Nearest Neighbor: sample single source pixels on reductions without averaging (#1114) (#1141)
MokuLakshithReddy7de2b5f20e38
diff --git a/crates/algo/src/resample.rs b/crates/algo/src/resample.rsindex 6362dafae..a54c98a5c 100644--- a/crates/algo/src/resample.rs+++ b/crates/algo/src/resample.rs@@ -85,7 +85,7 @@ fn taps(dst0: i32, dst1: i32, scale: f64, filter: Resample, edge: Option<(i32, i(dst0..dst1).map(|o| {let u = (o as f64 + 0.5) / scale - 0.5;- if filter == Resample::Nearest && scale >= 1.0 {+ if filter == Resample::Nearest {let i = clamp((u + 0.5).floor() as i32);return if (content.0..=content.1).contains(&i) {Taps { start: i, weights: vec![1.0], outside: 0.0 }@@ -484,4 +484,24 @@ mod tests {let c = crop_surface(&s, Rect::new(0, 0, 10, 10));assert_eq!(c.content_bounds(), Rect::new(0, 0, 10, 10));}++ /// #1114: nearest neighbor reduction must sample single source pixels, never average.+ #[test]+ fn nearest_neighbor_reduction_does_not_average() {+ let mut s = Surface::new(PixelFormat::GRAY8);+ for y in 0..8 {+ for x in 0..8 {+ if (x + y) % 2 == 0 {+ s.fill_rect(Rect::new(x, y, x + 1, y + 1), &[1.0]);+ }+ }+ }+ let reduced = resize_surface(&s, 0.5, 0.5, Resample::Nearest);+ for y in 0..4 {+ for x in 0..4 {+ let p = reduced.pixel(x, y)[0];+ assert!(p == 0.0 || p == 1.0, "nearest produced an averaged value {p} at ({x}, {y})");+ }+ }+ }}diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rsindex 6dd46318b..d6d42678c 100644--- a/crates/engine/src/image_cmds.rs+++ b/crates/engine/src/image_cmds.rs@@ -599,6 +599,33 @@ mod tests {assert_eq!(doc(&s).resolution_dpi, 300.0);}+ /// #1114: nearest neighbor reduction keeps source values without averaging.+ #[test]+ fn nearest_neighbor_reduction_keeps_source_values() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();+ s.execute("tools.setColors", json!({"foreground": "#000000", "background": "#ffffff"})).unwrap();+ for y in 0..8 {+ for x in 0..8 {+ if (x + y) % 2 == 0 {+ s.execute("select.rect", json!({"x": x, "y": y, "width": 1, "height": 1})).unwrap();+ s.execute("edit.fill", json!({"contents": "foreground"})).unwrap();+ }+ }+ }+ s.execute("select.deselect", json!({})).unwrap();+ let st = s.active().unwrap();+ let before = st.doc.layers[0].surface().unwrap().rgba(0, 0);+ assert!(before[0] < 0.01, "setup: (0,0) should be black, got {before:?}");+ s.execute("image.imageSize", json!({"width": 4, "height": 4, "resample": "nearest"})).unwrap();+ let st = s.active().unwrap();+ let surf = st.doc.layers[0].surface().unwrap();+ for (x, y) in [(0, 0), (1, 1), (2, 3)] {+ let v = surf.rgba(x, y)[0];+ assert!(v < 0.01 || v > 0.99, "nearest produced an averaged value {v} at ({x},{y})");+ }+ }+#[test]fn canvas_size_anchors_and_extends_background() {let mut s = session();