Skip to content

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

Puppet Warp: a linked layer mask moves with the pixels (#4910) (#4989)

DeWarePebd740ea638d4c
diff --git a/crates/algo/src/puppet.rs b/crates/algo/src/puppet.rs
index e21b7874e..c3c5c3693 100644
--- a/crates/algo/src/puppet.rs
+++ b/crates/algo/src/puppet.rs
@@ -1277,11 +1277,18 @@ pub const MAX_WARP_PIXELS: f64 = (1u64 << 30) as f64;
/// Applies a puppet warp to `src` (content inside `bounds`). `None` when the deformed mesh would
/// span more than [`MAX_WARP_PIXELS`].
pub fn puppet_warp(src: &Surface, bounds: Rect, w: &PuppetWarp, interp: Interp) -> Option<Surface> {
+ puppet_warp_with_mask(src, bounds, w, interp, None).map(|(out, _)| out)
+}
+
+/// [`puppet_warp`], also moving `mask` (a one-channel layer mask linked to `src`) with the same
+/// mesh, as Photoshop moves a linked mask with its layer (#4910). The mask is `None` in the
+/// result when none was given.
+pub fn puppet_warp_with_mask(src: &Surface, bounds: Rect, w: &PuppetWarp, interp: Interp, mask: Option<&Surface>) -> Option<(Surface, Option<Surface>)> {
let (solver, v, order) = deform(src, bounds, w, ITERATIONS);
// No triangles (an expansion that shrinks every pixel away): nothing to warp. Rendering the
// empty mesh would drop every pixel of the layer.
if solver.mesh.tris.is_empty() {
- return Some(src.clone());
+ return Some((src.clone(), mask.cloned()));
}
let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
for p in &v {
@@ -1291,7 +1298,57 @@ pub fn puppet_warp(src: &Surface, bounds: Rect, w: &PuppetWarp, interp: Interp)
if area.is_nan() || area > MAX_WARP_PIXELS {
return None;
}
- Some(render(src, bounds, &solver.mesh, &v, &order, interp))
+ let out = render(src, bounds, &solver.mesh, &v, &order, interp);
+ Some((out, mask.map(|m| render_mask(m, &solver.mesh, &v, &order, interp))))
+}
+
+/// Moves a one-channel layer mask with a deformed mesh: the mask under the mesh is lifted,
+/// deformed like the layer's pixels and laid over the rest. The area the mesh leaves takes the
+/// mask's default value (as [`crate::warp::warp_mesh_gray`] leaves it); outside the mesh the
+/// mask keeps its values.
+pub fn render_mask(mask: &Surface, mesh: &PuppetMesh, deformed: &[[f64; 2]], order: &[usize], interp: Interp) -> Surface {
+ let mut out = mask.clone();
+ if mesh.tris.is_empty() || deformed.len() != mesh.verts.len() || mask.format().channels() != 1 {
+ return out;
+ }
+ let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
+ for p in &mesh.verts {
+ (x0, y0, x1, y1) = (x0.min(p[0]), y0.min(p[1]), x1.max(p[0]), y1.max(p[1]));
+ }
+ if !(x0.is_finite() && y0.is_finite() && x1.is_finite() && y1.is_finite()) {
+ return out;
+ }
+ // The mesh's source area, a pixel wider so its edge samples stay inside.
+ let lim = f64::from(1 << 20);
+ let src = Rect::new(x0.max(-lim).floor() as i32 - 1, y0.max(-lim).floor() as i32 - 1, x1.min(lim).ceil() as i32 + 1, y1.min(lim).ceil() as i32 + 1);
+ if src.is_empty() {
+ return out;
+ }
+ let default = mask.default_pixel().first().copied().unwrap_or(0.0);
+ let fmt = mask.format();
+ let mut tmp = Surface::new(photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true));
+ tmp.write_region(src, &mask.read_region(src).iter().flat_map(|g| [*g, 1.0]).collect::<Vec<f32>>());
+ let tris: Vec<[usize; 3]> = order.iter().filter_map(|&t| mesh.tris.get(t).copied()).collect();
+ // Lift: where the undeformed mesh covers the mask, the mask takes its default value.
+ let still: Vec<([f64; 2], [f64; 2])> = mesh.verts.iter().map(|s| (*s, *s)).collect();
+ let lifted = crate::warp::warp_triangles(&tmp, src, &still, &tris, Interp::Nearest);
+ let b = lifted.content_bounds();
+ if !b.is_empty() {
+ let under = out.read_region(b);
+ let flat: Vec<f32> = lifted.read_region(b).as_chunks::<2>().0.iter().zip(&under).map(|(p, u)| default * p[1] + u * (1.0 - p[1])).collect();
+ out.write_region(b, &flat);
+ }
+ // Lay the deformed mask over what is left.
+ let moved: Vec<([f64; 2], [f64; 2])> = deformed.iter().zip(&mesh.verts).map(|(d, s)| (*d, *s)).collect();
+ let warped = crate::warp::warp_triangles(&tmp, src, &moved, &tris, interp);
+ let b = warped.content_bounds();
+ if !b.is_empty() {
+ let under = out.read_region(b);
+ let flat: Vec<f32> = warped.read_region(b).as_chunks::<2>().0.iter().zip(&under).map(|(p, u)| p[0] * p[1] + u * (1.0 - p[1])).collect();
+ out.write_region(b, &flat);
+ }
+ out.prune();
+ out
}
#[cfg(test)]
@@ -1434,6 +1491,33 @@ mod tests {
assert!(!near.content_bounds().is_empty());
}
+ #[test]
+ fn a_linked_mask_moves_with_the_mesh_and_leaves_its_default_behind() {
+ // #4910. A hide-all mask (default 0) that reveals the bar's top (y 10..30): moved down by
+ // 8, the revealed patch moves along, what it left is hidden again, and the mask away
+ // from the puppet keeps its values.
+ let s = blob(SampleType::U8);
+ let b = s.content_bounds();
+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut mask = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, sample, false), &[0.0]);
+ mask.fill_rect(Rect::new(20, 10, 36, 30), &[1.0]);
+ mask.fill_rect(Rect::new(90, 90, 94, 94), &[0.5]);
+ let w = PuppetWarp {
+ pins: vec![PuppetPin { src: [28.0, 30.0], dst: [28.0, 38.0], rotate: None, depth: 0 }],
+ mode: PuppetMode::Rigid,
+ density: PuppetDensity::Normal,
+ expansion: 2.0,
+ };
+ let (_, moved) = puppet_warp_with_mask(&s, b, &w, Interp::Bilinear, Some(&mask)).expect("warps");
+ let m = moved.expect("a mask in, a mask out");
+ let at = |x, y| m.sample_channel(x, y, 0);
+ assert!(at(28, 20) > 0.99 && at(28, 36) > 0.99, "{sample:?}: the revealed patch moved down");
+ assert!(at(28, 15) < 0.01, "{sample:?}: its old top is hidden again");
+ assert!((at(91, 91) - 0.5).abs() <= 1.0 / 255.0, "{sample:?}: away from the mesh nothing changes");
+ assert!(puppet_warp_with_mask(&s, b, &w, Interp::Bilinear, None).expect("warps").1.is_none());
+ }
+ }
+
#[test]
fn a_single_pin_translates_rigidly() {
let s = blob(SampleType::U8);
diff --git a/crates/engine/src/distort_cmds.rs b/crates/engine/src/distort_cmds.rs
index 55556c53d..ed56e5002 100644
--- a/crates/engine/src/distort_cmds.rs
+++ b/crates/engine/src/distort_cmds.rs
@@ -10,9 +10,11 @@
//! resampling. The params are the data in every case (strokes, pins and planes are small
//! compared with a field or a mesh, and replay is deterministic), so nothing needs a blob.
+use std::cell::RefCell;
+
use photocraft_algo::liquify::{LiquifyField, LiquifyStroke, apply_liquify, auto_cell};
use photocraft_algo::perspective::{PerspectiveMap, Plane, Straighten, straighten};
-use photocraft_algo::puppet::{PuppetDensity, PuppetMode, PuppetPin, PuppetWarp, puppet_warp};
+use photocraft_algo::puppet::{PuppetDensity, PuppetMode, PuppetPin, PuppetWarp, puppet_warp, puppet_warp_with_mask};
use photocraft_algo::transform::Interp;
use photocraft_algo::warp::{warp_mesh_gray, warp_mesh_surface};
use photocraft_color::PixelFormat;
@@ -328,7 +330,23 @@ fn puppet(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
}
let it = interp(p);
let too_far = || bad(cmd, "the pins stretch the content too far: the result would cover more than 2^30 pixels");
- run_on_layer(s, cmd, "Puppet Warp", p, true, &|surf, sel, _| deform_selected(surf, sel, &|x| puppet_surface(x, &w, it).ok_or_else(too_far)), None)
+ // A linked layer mask moves with the pixels on the same mesh (#4910): the layer's warp
+ // solves the mesh once and leaves the moved mask here for the mask step.
+ let linked = s.active().and_then(|d| d.doc.layer(id)).and_then(|l| l.mask.as_ref()).filter(|m| m.linked).map(|m| m.surface.clone());
+ let moved_mask: RefCell<Option<Surface>> = RefCell::new(None);
+ let layer_fn = |surf: &Surface, sel: Option<&Surface>, _: Rect| {
+ deform_selected(surf, sel, &|x| {
+ let b = x.content_bounds();
+ if b.is_empty() {
+ return Ok(x.clone());
+ }
+ let (out, mask) = puppet_warp_with_mask(x, b, &w, it, linked.as_ref()).ok_or_else(too_far)?;
+ *moved_mask.borrow_mut() = mask;
+ Ok(out)
+ })
+ };
+ let mask_fn = |m: &Surface, _: Option<&Surface>| Ok(moved_mask.borrow_mut().take().unwrap_or_else(|| m.clone()));
+ run_on_layer(s, cmd, "Puppet Warp", p, true, &layer_fn, Some(&mask_fn))
}
fn perspective(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
diff --git a/crates/engine/src/distort_cmds/tests.rs b/crates/engine/src/distort_cmds/tests.rs
index 50a8a49e6..81d17c28c 100644
--- a/crates/engine/src/distort_cmds/tests.rs
+++ b/crates/engine/src/distort_cmds/tests.rs
@@ -124,6 +124,68 @@ fn puppet_identity_translation_and_undo() {
}
}
+fn mask_at(s: &Session, x: i32, y: i32) -> f32 {
+ let st = s.active().unwrap();
+ st.doc.layer(st.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0)
+}
+
+/// [`session`] with a reveal-all mask that hides the stripes `stripes` (x ranges, y 10..40).
+fn masked_session(depth: u64, stripes: &[(i32, i32)]) -> Session {
+ let mut s = session(depth);
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ s.edit("mask", |doc, active| {
+ let m = doc.layer_mut(active.unwrap()).unwrap().mask.as_mut().unwrap();
+ for &(x0, x1) in stripes {
+ m.surface.fill_rect(Rect::new(x0, 10, x1, 40), &[0.0]);
+ }
+ Ok(())
+ })
+ .unwrap();
+ s
+}
+
+#[test]
+fn puppet_moves_a_linked_mask_with_the_pixels() {
+ // #4910: Puppet Warp warped only the pixels and left a linked mask behind. A one-pin rigid
+ // warp moves the block by (6, 4); the stripe the mask hides (x 20..24) must move with it.
+ for depth in [8u64, 16, 32] {
+ let mut s = masked_session(depth, &[(20, 24)]);
+ let before = s.active().unwrap().doc.clone();
+ s.execute(PUPPET, json!({"pins": [{"src": [30, 25], "dst": [36, 29]}], "mode": "rigid", "interpolation": "bilinear"})).unwrap();
+ for y in [16, 30, 42] {
+ assert!(mask_at(&s, 27, y) < 0.01, "{depth}: the stripe moved to x 26..30 (y {y})");
+ assert!(mask_at(&s, 21, y) > 0.99, "{depth}: and left x 20..24 (y {y})");
+ }
+ assert!(mask_at(&s, 27, 12) > 0.99, "{depth}: and down by 4");
+ // Pixels and mask still line up: the same layer pixel is hidden as before the warp.
+ let was = before.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().pixel(21, 26);
+ assert!(worst_px(&active_surface(&s).pixel(27, 30), &was) <= 1.0 / 255.0, "{depth}");
+ s.undo();
+ assert!(mask_at(&s, 21, 30) < 0.01 && mask_at(&s, 27, 30) > 0.99, "{depth}: undo puts the mask back");
+ }
+}
+
+#[test]
+fn puppet_leaves_an_unlinked_mask_in_place() {
+ let mut s = masked_session(8, &[(20, 24)]);
+ s.execute("layer.layerMask.linked", json!({"linked": false})).unwrap();
+ s.execute(PUPPET, json!({"pins": [{"src": [30, 25], "dst": [36, 29]}], "mode": "rigid"})).unwrap();
+ assert!(mask_at(&s, 21, 30) < 0.01 && mask_at(&s, 27, 30) > 0.99);
+ assert_eq!(active_surface(&s).content_bounds(), Rect::new(16, 14, 66, 44), "the pixels still moved");
+}
+
+#[test]
+fn puppet_with_a_selection_moves_only_the_selected_part_of_a_linked_mask() {
+ // The selection lifts the block's left part (x 10..30): the stripe hidden there moves with
+ // it, the one outside (x 40..44) stays over its pixels.
+ let mut s = masked_session(8, &[(20, 24), (40, 44)]);
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 30, "height": 60})).unwrap();
+ s.execute(PUPPET, json!({"pins": [{"src": [20, 25], "dst": [26, 29]}], "mode": "rigid"})).unwrap();
+ assert!(mask_at(&s, 27, 30) < 0.01 && mask_at(&s, 21, 30) > 0.99, "the selected stripe moved");
+ assert!(mask_at(&s, 41, 30) < 0.01 && mask_at(&s, 45, 30) > 0.99, "the other stayed");
+ assert_eq!(active_surface(&s).pixel(41, 30)[3], 1.0, "over its pixels");
+}
+
#[test]
fn puppet_with_an_expansion_that_empties_the_mesh_keeps_the_layer() {
// #951: a pinned warp over an empty mesh panicked in the solver; it must not erase the layer