diff --git a/Cargo.lock b/Cargo.lock index 75e1ea9149..e0c59b1aa8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4742,7 +4742,7 @@ dependencies = [ [[package]] name = "photocraft" -version = "0.15.1" +version = "0.16.0" dependencies = [ "arboard", "async-io", @@ -4792,7 +4792,7 @@ dependencies = [ [[package]] name = "photocraft-affinity" -version = "0.15.1" +version = "0.16.0" dependencies = [ "crc32fast", "flate2", @@ -4802,7 +4802,7 @@ dependencies = [ [[package]] name = "photocraft-algo" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4816,7 +4816,7 @@ dependencies = [ [[package]] name = "photocraft-automation" -version = "0.15.1" +version = "0.16.0" dependencies = [ "base64 0.22.1", "cap-std", @@ -4840,7 +4840,7 @@ dependencies = [ [[package]] name = "photocraft-cli" -version = "0.15.1" +version = "0.16.0" dependencies = [ "clap", "clap_complete", @@ -4859,7 +4859,7 @@ dependencies = [ [[package]] name = "photocraft-cms" -version = "0.15.1" +version = "0.16.0" dependencies = [ "moxcms", "rayon", @@ -4867,7 +4867,7 @@ dependencies = [ [[package]] name = "photocraft-codecs" -version = "0.15.1" +version = "0.16.0" dependencies = [ "craft-jpeg", "exr", @@ -4889,7 +4889,7 @@ dependencies = [ [[package]] name = "photocraft-color" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-cms", "serde", @@ -4897,7 +4897,7 @@ dependencies = [ [[package]] name = "photocraft-compose" -version = "0.15.1" +version = "0.16.0" dependencies = [ "criterion", "photocraft-cms", @@ -4913,7 +4913,7 @@ dependencies = [ [[package]] name = "photocraft-doc" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -4924,7 +4924,7 @@ dependencies = [ [[package]] name = "photocraft-engine" -version = "0.15.1" +version = "0.16.0" dependencies = [ "blake3", "chrono", @@ -4965,7 +4965,7 @@ dependencies = [ [[package]] name = "photocraft-format" -version = "0.15.1" +version = "0.16.0" dependencies = [ "blake3", "crc32fast", @@ -4988,14 +4988,14 @@ dependencies = [ [[package]] name = "photocraft-geom" -version = "0.15.1" +version = "0.16.0" dependencies = [ "serde", ] [[package]] name = "photocraft-gpu" -version = "0.15.1" +version = "0.16.0" dependencies = [ "bytemuck", "half", @@ -5015,14 +5015,14 @@ dependencies = [ [[package]] name = "photocraft-heif" -version = "0.15.1" +version = "0.16.0" dependencies = [ "heic-rs", ] [[package]] name = "photocraft-io" -version = "0.15.1" +version = "0.16.0" dependencies = [ "blake3", "craft-docpath", @@ -5055,18 +5055,18 @@ dependencies = [ [[package]] name = "photocraft-ipp" -version = "0.15.1" +version = "0.16.0" [[package]] name = "photocraft-ops" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-doc", ] [[package]] name = "photocraft-paint" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-cms", "photocraft-color", @@ -5079,7 +5079,7 @@ dependencies = [ [[package]] name = "photocraft-plugins" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5095,7 +5095,7 @@ dependencies = [ [[package]] name = "photocraft-psd" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "photocraft-psd", @@ -5106,7 +5106,7 @@ dependencies = [ [[package]] name = "photocraft-raster" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-geom", @@ -5117,7 +5117,7 @@ dependencies = [ [[package]] name = "photocraft-raw" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "image", @@ -5132,7 +5132,7 @@ dependencies = [ [[package]] name = "photocraft-tablet" -version = "0.15.1" +version = "0.16.0" dependencies = [ "block2 0.6.2", "objc2 0.6.4", @@ -5144,7 +5144,7 @@ dependencies = [ [[package]] name = "photocraft-testkit" -version = "0.15.1" +version = "0.16.0" dependencies = [ "memory-stats", "serde_json", @@ -5152,7 +5152,7 @@ dependencies = [ [[package]] name = "photocraft-text" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "parley", @@ -5167,7 +5167,7 @@ dependencies = [ [[package]] name = "photocraft-ui-egui" -version = "0.15.1" +version = "0.16.0" dependencies = [ "base64 0.22.1", "craft-print", @@ -5210,7 +5210,7 @@ dependencies = [ [[package]] name = "photocraft-vector" -version = "0.15.1" +version = "0.16.0" dependencies = [ "photocraft-color", "photocraft-doc", @@ -5221,7 +5221,7 @@ dependencies = [ [[package]] name = "photocraft-web" -version = "0.15.1" +version = "0.16.0" dependencies = [ "eframe", "egui", @@ -5243,7 +5243,7 @@ dependencies = [ [[package]] name = "photocraft-web-boot" -version = "0.15.1" +version = "0.16.0" dependencies = [ "flate2", "js-sys", @@ -8897,7 +8897,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "xtask" -version = "0.15.1" +version = "0.16.0" dependencies = [ "chrono", "serde", diff --git a/Cargo.toml b/Cargo.toml index 68d6ae90b1..43e4c87e27 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.15.1" +version = "0.16.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/crates/algo/src/vanishing.rs b/crates/algo/src/vanishing.rs index 1cf39b23ec..53fe23c237 100644 --- a/crates/algo/src/vanishing.rs +++ b/crates/algo/src/vanishing.rs @@ -324,33 +324,110 @@ pub fn paste(scene: &Scene, i: usize, src: &Surface, src_rect: Rect, at: [f64; 2 Ok(Some(out)) } +/// The fixed frame of one clone stroke: the source and destination planes, the source offset in +/// plane-metric units and the brush radius, all set at the stroke's anchor (its first dab). +struct CloneFrame { + hs: Homography, + ls: (f64, f64), + hd: Homography, + hd_inv: Homography, + ld: (f64, f64), + offset: [f64; 2], + r_m: f64, +} + +impl CloneFrame { + fn new(scene: &Scene, source: [f64; 2], anchor: [f64; 2], size: f64) -> Option { + let (ps, pd) = (scene.plane_at(source)?, scene.plane_at(anchor)?); + let ((hs, lus, lvs), (hd, lud, lvd)) = (scene.frame(ps)?, scene.frame(pd)?); + let (hs_inv, hd_inv) = (hs.inverse()?, hd.inverse()?); + let ms = metric(&hs_inv, (lus, lvs), source); + let md0 = metric(&hd_inv, (lud, lvd), anchor); + // Brush radius in metric units (from the image size at the anchor). + let probe = metric(&hd_inv, (lud, lvd), [anchor[0] + size / 2.0, anchor[1]]); + let r_m = ((probe[0] - md0[0]).hypot(probe[1] - md0[1])).max(1e-9); + let offset = [ms[0] - md0[0], ms[1] - md0[1]]; + (offset.iter().all(|v| v.is_finite()) && r_m.is_finite()).then_some(CloneFrame { hs, ls: (lus, lvs), hd, hd_inv, ld: (lud, lvd), offset, r_m }) + } + + /// The source point (image px) that destination `p` copies from. + fn source_of(&self, p: [f64; 2]) -> [f64; 2] { + let m = metric(&self.hd_inv, self.ld, p); + let (x, y) = self.hs.apply((m[0] + self.offset[0]) / self.ls.0, (m[1] + self.offset[1]) / self.ls.1); + [x, y] + } +} + +/// Image point → plane-metric coordinates through the plane's inverse homography. +fn metric(inv: &Homography, l: (f64, f64), p: [f64; 2]) -> [f64; 2] { + let (u, v) = inv.apply(p[0], p[1]); + [u * l.0, v * l.1] +} + /// Perspective clone stamp: one stroke of dabs at image points `points` on the destination /// plane, copying from `source` (image px) with the offset fixed in plane-metric units at the /// first dab. `size` is the brush diameter in px at the first dab; `hardness` 0..=1. pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: &[[f64; 2]], size: f64, hardness: f64, opacity: f32) -> usize { let Some(first) = points.first() else { return 0 }; - let (Some(ps), Some(pd)) = (scene.plane_at(source), scene.plane_at(*first)) else { return 0 }; - let (Some((hs, lus, lvs)), Some((hd, lud, lvd))) = (scene.frame(ps), scene.frame(pd)) else { return 0 }; - let (Some(hs_inv), Some(hd_inv)) = (hs.inverse(), hd.inverse()) else { return 0 }; - let metric = |inv: &Homography, lu: f64, lv: f64, p: [f64; 2]| { - let (u, v) = inv.apply(p[0], p[1]); - [u * lu, v * lv] - }; - let ms = metric(&hs_inv, lus, lvs, source); - let md0 = metric(&hd_inv, lud, lvd, *first); - let offset = [ms[0] - md0[0], ms[1] - md0[1]]; - // Brush radius in metric units (from the image size at the first dab). - let probe = metric(&hd_inv, lud, lvd, [first[0] + size / 2.0, first[1]]); - let r_m = ((probe[0] - md0[0]).hypot(probe[1] - md0[1])).max(1e-9); + clone_dabs(scene, surf, source, *first, points, size, hardness, opacity).0 +} + +/// Where a clone stroke that starts at `anchor` copying from `source` samples for destination +/// `p`: the same plane-metric offset. A live preview paints a stroke in pieces with it, and +/// Aligned strokes keep the first stroke's offset. `None` when `source` or `anchor` is off the +/// planes. +pub fn clone_source(scene: &Scene, source: [f64; 2], anchor: [f64; 2], p: [f64; 2]) -> Option<[f64; 2]> { + let s = CloneFrame::new(scene, source, anchor, 1.0)?.source_of(p); + s.iter().all(|v| v.is_finite()).then_some(s) +} + +/// [`clone_stroke`]'s dabs at `points` for a stroke anchored at `anchor` (its first dab, which +/// fixes the offset and the brush's metric size). Samples a snapshot taken at this call. +/// For incremental painting use [`clone_dabs_from`] with one snapshot per stroke. +/// Returns the dabs painted and the area they changed. +#[allow(clippy::too_many_arguments)] +pub fn clone_dabs( + scene: &Scene, + surf: &mut Surface, + source: [f64; 2], + anchor: [f64; 2], + points: &[[f64; 2]], + size: f64, + hardness: f64, + opacity: f32, +) -> (usize, Rect) { let src_copy = surf.clone(); + clone_dabs_from(scene, surf, &src_copy, source, anchor, points, size, hardness, opacity) +} + +/// Paint a batch of one stroke using the same immutable source snapshot for every batch. +/// Source and destination must have the same pixel format; otherwise no dabs are painted. +#[allow(clippy::too_many_arguments)] +pub fn clone_dabs_from( + scene: &Scene, + surf: &mut Surface, + src_copy: &Surface, + source: [f64; 2], + anchor: [f64; 2], + points: &[[f64; 2]], + size: f64, + hardness: f64, + opacity: f32, +) -> (usize, Rect) { + if surf.format() != src_copy.format() { + return (0, Rect::EMPTY); + } + let Some(f) = CloneFrame::new(scene, source, anchor, size) else { return (0, Rect::EMPTY) }; + let CloneFrame { hs, ls: (lus, lvs), hd, hd_inv, ld: (lud, lvd), offset, r_m } = f; let fmt = surf.format(); let n = fmt.channels(); // Scratch for `sample`: the dab's source pixels, the four bilinear corners, the result. let mut win = Window { area: Rect::new(0, 0, 0, 0), data: Vec::new() }; let (mut corners, mut s) = (vec![0.0f32; 4 * n], vec![0.0f32; n]); let mut dabs = 0; + let mut changed_area = Rect::EMPTY; for p in points { - let mc = metric(&hd_inv, lud, lvd, *p); + let mc = metric(&hd_inv, (lud, lvd), *p); // Image-space footprint: map a metric circle's bounding points. let footprint = |h: &Homography, lu: f64, lv: f64, c: [f64; 2]| { let mut bb = [f64::MAX, f64::MAX, f64::MIN, f64::MIN]; @@ -359,6 +436,9 @@ pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: let (x, y) = h.apply((c[0] + r_m * a.cos()) / lu, (c[1] + r_m * a.sin()) / lv); bb = [bb[0].min(x), bb[1].min(y), bb[2].max(x), bb[3].max(y)]; } + if bb.iter().any(|v| !v.is_finite()) { + return Rect::EMPTY; + } Rect::new(bb[0].floor() as i32, bb[1].floor() as i32, (bb[2].ceil() as i32).saturating_add(1), (bb[3].ceil() as i32).saturating_add(1)) }; let area = footprint(&hd, lud, lvd, mc); @@ -385,9 +465,9 @@ pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: let mut changed = false; for (i, px) in data.chunks_exact_mut(n).enumerate() { let (x, y) = (area.x0 as f64 + (i % w) as f64 + 0.5, area.y0 as f64 + (i / w) as f64 + 0.5); - let m = metric(&hd_inv, lud, lvd, [x, y]); + let m = metric(&hd_inv, (lud, lvd), [x, y]); let d = (m[0] - mc[0]).hypot(m[1] - mc[1]) / r_m; - if d >= 1.0 { + if d >= 1.0 || d.is_nan() { continue; } let hard = hardness.clamp(0.0, 0.99); @@ -396,7 +476,7 @@ pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: // Source pixel at the same metric offset. let sm = [m[0] + offset[0], m[1] + offset[1]]; let (sx, sy) = hs.apply(sm[0] / lus, sm[1] / lvs); - sample(&src_copy, &win, sx - 0.5, sy - 0.5, &mut corners, &mut s); + sample(src_copy, &win, sx - 0.5, sy - 0.5, &mut corners, &mut s); for c in 0..n { px[c] += (s[c] - px[c]) * k; } @@ -405,9 +485,10 @@ pub fn clone_stroke(scene: &Scene, surf: &mut Surface, source: [f64; 2], points: if changed { surf.write_region(area, &data); dabs += 1; + changed_area = if changed_area.is_empty() { area } else { changed_area.union(&area) }; } } - dabs + (dabs, changed_area) } /// Pixels of `area` read from the source surface (`read_region` layout). @@ -421,6 +502,10 @@ struct Window { /// read from `s`. fn sample(s: &Surface, win: &Window, x: f64, y: f64, corners: &mut Vec, out: &mut [f32]) { let n = out.len(); + if !x.is_finite() || !y.is_finite() { + out.fill(0.0); + return; + } let (x0, y0) = (x.floor() as i32, y.floor() as i32); let (tx, ty) = ((x - x0 as f64) as f32, (y - y0 as f64) as f32); let (x1, y1) = (x0.saturating_add(1), y0.saturating_add(1)); @@ -537,6 +622,27 @@ mod tests { let n = clone_stroke(&sc, &mut s, [sx, sy], &[[dx, dy]], 10.0, 0.8, 1.0); assert_eq!(n, 1); assert!(s.rgba(dx as i32, dy as i32)[0] > 0.8, "{:?}", s.rgba(dx as i32, dy as i32)); + // The stroke's anchor copies from the source itself. + let back = clone_source(&sc, [sx, sy], [dx, dy], [dx, dy]).unwrap(); + assert!((back[0] - sx).abs() < 1e-6 && (back[1] - sy).abs() < 1e-6, "{back:?}"); + } + #[test] + fn incremental_clone_uses_one_source_snapshot_per_stroke() { + let sc = Scene::new(VpPlane { corners: [[0.0, 0.0], [100.0, 0.0], [100.0, 100.0], [0.0, 100.0]] }, [50.0, 50.0], None, 800.0); + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut original = Surface::new(fmt); + for x in 0..100 { + original.fill_rect(Rect::new(x, 0, x + 1, 100), &[x as f32 / 100.0, (x % 7) as f32 / 6.0, 0.3, 1.0]); + } + let points = [[40.0, 50.0], [44.0, 50.0], [48.0, 50.0], [52.0, 50.0]]; + let mut whole = original.clone(); + assert_eq!(clone_stroke(&sc, &mut whole, [36.0, 50.0], &points, 12.0, 0.8, 1.0), 4); + let mut pieces = original.clone(); + for part in points.chunks(2) { + clone_dabs_from(&sc, &mut pieces, &original, [36.0, 50.0], points[0], part, 12.0, 0.8, 1.0); + } + assert_eq!(whole.read_region(Rect::new(0, 0, 100, 100)), pieces.read_region(Rect::new(0, 0, 100, 100))); + } } #[test] diff --git a/crates/engine/src/vp_cmds.rs b/crates/engine/src/vp_cmds.rs index 185930298a..9809888446 100644 --- a/crates/engine/src/vp_cmds.rs +++ b/crates/engine/src/vp_cmds.rs @@ -3,7 +3,7 @@ //! ([`photocraft_algo::vanishing`]). The edit lands on the active pixel layer, or on a new layer //! with `"newLayer": true` (Photoshop's advice for non-destructive Vanishing Point work). -use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_stroke, paste}; +use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_dabs, paste}; use photocraft_doc::{Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; use photocraft_raster::Surface; @@ -13,6 +13,11 @@ use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; pub const VP: &str = "filter.vanishingPoint"; +/// Most planes a scene holds. +pub const MAX_PLANES: usize = 64; +/// Most clone strokes, and dabs over all of them, one run paints. +pub const MAX_CLONE_STROKES: usize = 4096; +pub const MAX_CLONE_DABS: usize = 200_000; fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: VP.into(), msg: msg.into() } @@ -29,6 +34,9 @@ pub fn scene(p: &Value, canvas: Rect) -> Result { .and_then(Value::as_array) .filter(|a| !a.is_empty()) .ok_or_else(|| bad("pass `planes`: [{\"corners\":[[x,y]×4]}, {\"from\":0,\"edge\":\"top\",\"angle\":90}]"))?; + if planes.len() > MAX_PLANES { + return Err(bad(format!("at most {MAX_PLANES} planes"))); + } let center = [(canvas.x0 + canvas.x1) as f64 / 2.0, (canvas.y0 + canvas.y1) as f64 / 2.0]; let corners = |v: &Value| -> Option<[[f64; 2]; 4]> { let a = v.get("corners")?.as_array()?; @@ -67,6 +75,12 @@ pub fn scene(p: &Value, canvas: Rect) -> Result { }; let angle = pl.get("angle").and_then(Value::as_f64).unwrap_or(90.0); let depth = pl.get("depth").and_then(Value::as_f64).unwrap_or(1.0); + if !angle.is_finite() || !(0.0..=360.0).contains(&angle) { + return Err(bad(format!("plane {i}: `angle` must be 0..360 degrees"))); + } + if !depth.is_finite() || depth <= 0.0 || depth > 1000.0 { + return Err(bad(format!("plane {i}: `depth` must be above 0 and at most 1000"))); + } sc.tear_off(from, edge, angle, depth).ok_or_else(|| bad(format!("plane {i} would lie behind the camera")))?; } if sc.planes.iter().any(|p| p.homography().is_none()) { @@ -75,6 +89,88 @@ pub fn scene(p: &Value, canvas: Rect) -> Result { Ok(sc) } +/// One stroke of `"clone"`. +#[derive(Clone, Debug, PartialEq)] +pub struct CloneSpec { + pub source: [f64; 2], + pub points: Vec<[f64; 2]>, + pub size: f64, + pub hardness: f64, + pub opacity: f64, +} + +/// Reads `"clone"`: finite points, at most [`MAX_CLONE_STROKES`] strokes and +/// [`MAX_CLONE_DABS`] dabs in all. +pub fn clone_specs(p: &Value) -> Result> { + let Some(v) = p.get("clone").filter(|v| !v.is_null()) else { return Ok(Vec::new()) }; + let strokes = v.as_array().ok_or_else(|| bad("`clone` is a list of strokes"))?; + if strokes.len() > MAX_CLONE_STROKES { + return Err(bad(format!("at most {MAX_CLONE_STROKES} clone strokes"))); + } + let finite = |q: [f64; 2]| q.iter().all(|v| v.is_finite() && v.abs() < 1e7); + let num = |c: &Value, k: &str, default: f64, lo: f64, hi: f64| -> Result { + match c.get(k) { + None | Some(Value::Null) => Ok(default), + Some(v) => v.as_f64().filter(|x| x.is_finite()).map(|x| x.clamp(lo, hi)).ok_or_else(|| bad(format!("clone `{k}` must be a number"))), + } + }; + let mut dabs = 0usize; + let mut out = Vec::with_capacity(strokes.len()); + for (k, c) in strokes.iter().enumerate() { + let source = c.get("source").and_then(pt).filter(|q| finite(*q)).ok_or_else(|| bad(format!("clone {k}: `source` [x,y]")))?; + let raw = c.get("points").and_then(Value::as_array).ok_or_else(|| bad(format!("clone {k}: `points` [[x,y], …]")))?; + dabs = dabs.saturating_add(raw.len()); + if dabs > MAX_CLONE_DABS { + return Err(bad(format!("at most {MAX_CLONE_DABS} clone points in all"))); + } + let points = + raw.iter().map(|q| pt(q).filter(|q| finite(*q))).collect::>>().ok_or_else(|| bad(format!("clone {k}: every point is [x,y]")))?; + out.push(CloneSpec { + source, + points, + size: num(c, "size", 40.0, 1.0, 2000.0)?, + hardness: num(c, "hardness", 50.0, 0.0, 100.0)? / 100.0, + opacity: num(c, "opacity", 100.0, 0.0, 100.0)? / 100.0, + }); + } + Ok(out) +} + +/// Paints clone stroke `c` on `surf`, or, with `work` (the image it samples), on `work` and copies +/// the pixels it changed inside `canvas` to `surf`. Returns the dabs painted. +pub fn clone_into(sc: &Scene, surf: &mut Surface, work: Option<&mut Surface>, c: &CloneSpec, canvas: Rect) -> usize { + let Some(first) = c.points.first() else { return 0 }; + let Some(work) = work else { + return clone_dabs(sc, surf, c.source, *first, &c.points, c.size, c.hardness, c.opacity as f32).0; + }; + let before = work.clone(); + let (dabs, area) = clone_dabs(sc, work, c.source, *first, &c.points, c.size, c.hardness, c.opacity as f32); + // The dabs' boxes can span far off the canvas (points up to 1e7 px apart): reading their + // union back would allocate without bound. + copy_changed(surf, &before, work, area.intersect(&canvas)); + dabs +} + +/// Copies to `dst` the pixels of `area` where `after` differs from `before` (same format). +pub fn copy_changed(dst: &mut Surface, before: &Surface, after: &Surface, area: Rect) { + if area.is_empty() { + return; + } + let n = dst.format().channels(); + let (nw, ow, mut cur) = (after.read_region(area), before.read_region(area), dst.read_region(area)); + for ((c, a), b) in cur.chunks_exact_mut(n).zip(nw.chunks_exact(n)).zip(ow.chunks_exact(n)) { + if a != b { + c.copy_from_slice(a); + } + } + dst.write_region(area, &cur); +} + +/// The image a `"newLayer"` run's clone strokes sample: the visible document. +pub fn visible_image(doc: &Document) -> Surface { + crate::file_cmds::flattened(doc, doc.pixel_format()) +} + fn has_layer(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; match d.active_layer.and_then(|id| d.doc.layer(id)).map(|l| &l.content) { @@ -84,8 +180,16 @@ fn has_layer(s: &Session) -> std::result::Result<(), String> { } } +/// Pastes `src` (content in `rect`) onto plane `plane` of `sc` over `surf`, as the command's +/// `"paste"` does. Returns the area the paste covers. +pub fn paste_onto(sc: &Scene, surf: &mut Surface, plane: usize, src: &Surface, rect: Rect, at: [f64; 2], width: f64) -> Result { + let Some(out) = paste(sc, plane, src, rect, at, width)? else { return Ok(Rect::EMPTY) }; + over(surf, &out); + Ok(out.content_bounds()) +} + /// Composites `top` over `dst` (premultiplied source-over), same format. -fn over(dst: &mut Surface, top: &Surface) { +pub fn over(dst: &mut Surface, top: &Surface) { let b = top.content_bounds(); if b.is_empty() { return; @@ -134,20 +238,31 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { let width = item.get("width").and_then(Value::as_f64).unwrap_or(0.5).clamp(0.01, 10.0); pastes.push((plane, surf, rect, at, width)); } - let clones: Vec = p.get("clone").and_then(Value::as_array).cloned().unwrap_or_default(); + let clones = clone_specs(p)?; let new_layer = p.get("newLayer").and_then(Value::as_bool).unwrap_or(false); + // The layer the mode was opened on (the UI passes it: other layers can be picked meanwhile). + let layer = crate::commands::explicit_layer(s, p)?; let mut dabs = 0usize; let target = s.edit("Vanishing Point", |doc: &mut Document, active| { + if let Some(l) = layer + && doc.layer(l).is_none() + { + return Err(EngineError::NoLayer(l)); + } + let on = layer.or(*active); let id = if new_layer { let l = Layer::raster(doc.next_layer_name("Vanishing Point"), doc.pixel_format()); - let nid = doc.insert_above(*active, l); + let nid = doc.insert_above(on, l); *active = Some(nid); nid } else { - active.ok_or_else(|| EngineError::Other("no active layer".into()))? + // The painted layer becomes active, so Fade and a colour-channel target follow it. + let id = on.ok_or_else(|| EngineError::Other("no active layer".into()))?; + *active = Some(id); + id }; // A new layer clones from the visible image; otherwise from the layer itself. - let base: Option = new_layer.then(|| crate::file_cmds::flattened(doc, doc.pixel_format())); + let base: Option = new_layer.then(|| visible_image(doc)); let locks = doc.effective_locks(id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; if locks.all || locks.pixels { @@ -155,40 +270,16 @@ fn vanishing_point(s: &mut Session, p: &Value) -> Result { } let surf = l.surface_mut().ok_or_else(|| EngineError::Other("Vanishing Point needs a pixel layer".into()))?; for (plane, src, rect, at, width) in &pastes { - if let Some(out) = paste(&sc, *plane, src, *rect, *at, *width)? { - over(surf, &out); - } + paste_onto(&sc, surf, *plane, src, *rect, *at, *width)?; } - for (k, c) in clones.iter().enumerate() { - let source = c.get("source").and_then(pt).ok_or_else(|| bad(format!("clone {k}: `source` [x,y]")))?; - let points: Vec<[f64; 2]> = c.get("points").and_then(Value::as_array).map(|a| a.iter().filter_map(pt).collect()).unwrap_or_default(); - let size = c.get("size").and_then(Value::as_f64).unwrap_or(40.0).clamp(1.0, 2000.0); - let hardness = c.get("hardness").and_then(Value::as_f64).unwrap_or(50.0).clamp(0.0, 100.0) / 100.0; - let opacity = (c.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) / 100.0) as f32; - // Sample from the original pixels (merged with what's been pasted). - let mut work = match &base { - Some(b) => { - let mut w = b.clone(); - over(&mut w, surf); - w - } - None => surf.clone(), - }; - let before = work.clone(); - dabs += clone_stroke(&sc, &mut work, source, &points, size, hardness, opacity); - // Copy back only what the stroke changed. - let b = work.content_bounds().union(&before.content_bounds()); - if !b.is_empty() { - let (nw, ow) = (work.read_region(b), before.read_region(b)); - let n = surf.format().channels(); - let mut cur = surf.read_region(b); - for i in 0..cur.len() / n { - if nw[i * n..(i + 1) * n] != ow[i * n..(i + 1) * n] { - cur[i * n..(i + 1) * n].copy_from_slice(&nw[i * n..(i + 1) * n]); - } - } - surf.write_region(b, &cur); - } + // A new layer samples the visible image (merged with what's been pasted) and takes only + // the pixels the strokes change; otherwise the strokes paint the layer itself. + let mut work = base.map(|mut w| { + over(&mut w, surf); + w + }); + for c in &clones { + dabs += clone_into(&sc, surf, work.as_mut(), c, canvas); } surf.prune(); Ok(id) @@ -211,7 +302,7 @@ pub fn specs() -> Vec { label: "Vanishing Point…", menu: &["Filter"], shortcut: Some("Cmd+Alt+V"), - params: r##"{"planes":[{"corners":[[x,y]×4]} | {"from":plane,"edge":"top|right|bottom|left","angle":deg=90,"depth":1}],"focalLength":px=0,"paste":[{"plane":0,"layer":id? (else the clipboard),"at":[u,v]=[0.25,0.25],"width":0..1=0.5}],"clone":[{"source":[x,y],"points":[[x,y]],"size":px=40,"hardness":0..100=50,"opacity":0..100=100}],"newLayer":bool=false}"##, + params: r##"{"planes":[{"corners":[[x,y]×4]} | {"from":plane,"edge":"top|right|bottom|left","angle":deg=90,"depth":1}],"focalLength":px=0,"paste":[{"plane":0,"layer":id? (else the clipboard),"at":[u,v]=[0.25,0.25],"width":0..1=0.5}],"clone":[{"source":[x,y],"points":[[x,y]],"size":px=40,"hardness":0..100=50,"opacity":0..100=100}],"newLayer":bool=false,"layer":id|name? (else the active layer)}"##, enabled: has_layer, run: vanishing_point, journal: true, @@ -282,4 +373,103 @@ mod tests { } assert!(s.execute(VP, json!({"planes": [{"corners": square}]})).is_ok()); } + + #[test] + fn rejects_hostile_clone_and_tear_off_params() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "depth": 32})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + let floor = json!({"corners": [[60, 60], [140, 60], [190, 190], [10, 190]]}); + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + for torn in [json!({"from": 0, "angle": 1e9}), json!({"from": 0, "depth": -1}), json!({"from": 0, "depth": 1e300})] { + let e = s.execute(VP, json!({"planes": [floor, torn]})).unwrap_err().to_string(); + assert!(e.contains("plane 1"), "{e}"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + } + let many: Vec<[f64; 2]> = vec![[100.0, 150.0]; MAX_CLONE_DABS + 1]; + for clone in [ + json!([{"points": [[100, 150]]}]), + json!([{"source": [100, 180], "points": [[100, 150], "x"]}]), + json!([{"source": [100, 180], "points": [[100, 150]], "size": "big"}]), + json!([{"source": [100, 180], "points": many}]), + json!({"source": [100, 180]}), + ] { + let label: String = clone.to_string().chars().take(80).collect(); + assert!(s.execute(VP, json!({"planes": [floor], "clone": clone, "newLayer": true})).is_err(), "{label}"); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + } + let planes: Vec = std::iter::repeat_n(floor.clone(), MAX_PLANES + 1).collect(); + assert!(s.execute(VP, json!({"planes": planes})).is_err()); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + // A clone on a torn-off wall, at 32 bits, sampling the floor. + let r = s + .execute(VP, json!({"planes": [floor, {"from": 0, "edge": "top", "angle": 90, "depth": 0.5}], "clone": [{"source": [100, 150], "points": [[100, 50], [104, 50]], "size": 8}]})) + .unwrap(); + assert_eq!(r["planes"].as_array().unwrap().len(), 2); + assert!(r["dabs"].as_u64().unwrap() >= 1, "{r}"); + } + + #[test] + fn new_layer_clone_stays_on_the_canvas() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", json!({"color": "#40c040"})).unwrap(); + // A red stripe where the first dab samples, so cloning it changes pixels. + s.edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(140, 80, 160, 120), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let planes = json!([{"corners": [[0, 0], [200, 0], [200, 200], [0, 200]]}]); + // The second dab lies left of the canvas and samples the canvas 50 px to its right; the + // third is far off it (its box joined with the first's once asked for petabytes). + for points in [json!([[100, 100], [-30, 100]]), json!([[100, 100], [-30, 100], [9_000_000, 9_000_000]])] { + let r = s.execute(VP, json!({"planes": planes, "newLayer": true, "clone": [{"source": [150, 100], "points": points, "size": 20}]})).unwrap(); + let l = s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap().surface().unwrap(); + let b = l.content_bounds(); + assert!(!b.is_empty() && Rect::new(0, 0, 200, 200).contains_rect(&b), "{b:?}"); + assert!(l.rgba(100, 100)[0] > 0.9, "{:?}", l.rgba(100, 100)); + s.undo(); + } + } + + #[test] + fn layer_param_paints_that_layer_not_the_active_one() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + s.execute("layer.new.layer", json!({"name": "floor"})).unwrap(); + s.execute("edit.fill", json!({"color": "#40c040"})).unwrap(); + s.edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(140, 80, 160, 120), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let floor = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + let other = s.active().unwrap().active_layer.unwrap(); + let planes = json!([{"corners": [[0, 0], [200, 0], [200, 200], [0, 200]]}]); + let clone = json!([{"source": [150, 100], "points": [[100, 100]], "size": 20}]); + let surf = |s: &Session, id| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().clone(); + let r = s.execute(VP, json!({"planes": planes, "clone": clone, "layer": floor.0})).unwrap(); + assert_eq!(r["layer"].as_u64(), Some(floor.0)); + assert!(surf(&s, floor).rgba(100, 100)[0] > 0.9, "{:?}", surf(&s, floor).rgba(100, 100)); + assert!(surf(&s, other).content_bounds().is_empty(), "the active layer stays untouched"); + s.undo(); + // A new layer goes right above the named layer. + let r = s.execute(VP, json!({"planes": planes, "clone": clone, "layer": floor.0, "newLayer": true})).unwrap(); + let d = &s.active().unwrap().doc; + let ids: Vec = d.layers.iter().map(|l| l.id.0).collect(); + let at = |id: u64| ids.iter().position(|&i| i == id).unwrap(); + assert_eq!(at(r["layer"].as_u64().unwrap()), at(floor.0) + 1, "{ids:?}"); + s.undo(); + let before = s.active().unwrap().doc.clone(); + assert!(s.execute(VP, json!({"planes": planes, "clone": clone, "layer": 999_999})).is_err()); + assert!(s.execute(VP, json!({"planes": planes, "clone": clone, "layer": 999_999, "newLayer": true})).is_err()); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + } } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 2eab97da0a..c2ee262b1c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1479,6 +1479,9 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> (std::sync::Ar if let Some(shown) = crate::type_font_preview::display_doc(app, idx) { return shown; } + // Vanishing Point's strokes over the document as it is now (the Layers panel may have + // changed it since the options bar synced them this frame). + crate::vp_ui::sync_preview(app); // Puppet / Perspective Warp previews hide the layer they draw on a mesh. if let Some(shown) = crate::distort_ui::display_doc(app, idx) { return shown; @@ -2032,6 +2035,13 @@ pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), no { return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); } + // Between Vanishing Point stamp previews (and the document): the areas the strokes painted. + if seen.0 == now.0 + && let Some(st) = app.session.documents().get(idx) + && let Some(r) = crate::vp_ui::damage(app, st.doc.id, now.0, seen.1 ^ display_key, now.1) + { + return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) }); + } // Between hovered blend modes (and the document): where the layer's blending shows. if seen.0 == now.0 && let Some(st) = app.session.documents().get(idx) diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rs index 0c25bfcd6c..3a5c765da6 100644 --- a/crates/ui-egui/src/distort_ui.rs +++ b/crates/ui-egui/src/distort_ui.rs @@ -138,12 +138,13 @@ pub fn cancel_stale(app: &mut PhotocraftApp) { } } -/// The document shown on the canvas while Puppet or Perspective Warp previews a layer. +/// The document shown on the canvas while Puppet or Perspective Warp previews a layer, or +/// Vanishing Point's Stamp has painted. pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc, u64)> { if app.session.active_index() != Some(idx) { return None; } - let id = app.session.documents().get(idx).map(|st| st.doc.id)?; + let (id, revision) = app.session.documents().get(idx).map(|st| (st.doc.id, st.revision))?; if let Some(p) = &app.distort.puppet && p.document == id { @@ -154,7 +155,8 @@ pub fn display_doc(app: &PhotocraftApp, idx: usize) -> Option<(Arc, u6 { return Some((p.preview_doc.clone(), (1 << 42) + p.key)); } - None + // Vanishing Point: the clone strokes painted so far, on the document as they were painted. + app.distort.vanishing.as_ref().and_then(|v| v.shown_on(id, revision)) } /// Menu / control routing. `Some` when this module handles the invocation. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 59cea8bbdb..a7938f317e 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3589,6 +3589,8 @@ curves Smooth Vyhladit Vanishing Point is not active Úběžník není aktivní Apply Vanishing Point ({key}) Použít úběžník ({key}) Fix the red plane first: its corners must form a convex quad Nejprve opravte červenou rovinu: její rohy musí tvořit konvexní čtyřúhelník + Alt-click a plane to set the clone source Klepnutím s Alt na rovinu nastavte zdroj klonování + Too many clone strokes: apply Vanishing Point first Příliš mnoho tahů klonování: nejprve použijte Úběžník # Select and Mask view modes (#1754) Onion Skin Cibulová slupka Marching Ants Pochodující mravenci diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 6ce1f80274..07707b8512 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2785,6 +2785,8 @@ curves Smooth Glätten Vanishing Point is not active Fluchtpunkt ist nicht aktiv Apply Vanishing Point ({key}) Fluchtpunkt anwenden ({key}) Fix the red plane first: its corners must form a convex quad Korrigieren Sie zuerst die rote Ebene: Ihre Ecken müssen ein konvexes Viereck bilden + Alt-click a plane to set the clone source Alt-Klick auf eine Ebene legt die Kopierquelle fest + Too many clone strokes: apply Vanishing Point first Zu viele Kopierstriche: Wenden Sie zuerst Fluchtpunkt an # Select and Mask view modes (#1754) Onion Skin Zwiebelschicht Marching Ants Laufende Ameisen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e6ecd1a010..e429672300 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3834,6 +3834,8 @@ curves Smooth Εξομάλυνση Vanishing Point is not active Το Σημείο φυγής δεν είναι ενεργό Apply Vanishing Point ({key}) Εφαρμογή σημείου φυγής ({key}) Fix the red plane first: its corners must form a convex quad Διορθώστε πρώτα το κόκκινο επίπεδο: οι γωνίες του πρέπει να σχηματίζουν κυρτό τετράπλευρο + Alt-click a plane to set the clone source Alt-κλικ σε ένα επίπεδο για να ορίσετε την πηγή κλωνοποίησης + Too many clone strokes: apply Vanishing Point first Πάρα πολλές πινελιές κλωνοποίησης: εφαρμόστε πρώτα το Σημείο φυγής # Select and Mask view modes (#1754) Onion Skin Φλούδα κρεμμυδιού Marching Ants Κινούμενο περίγραμμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 20c0d62e2c..74885088c6 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2821,6 +2821,8 @@ curves Smooth Suavizar Vanishing Point is not active Punto de fuga no está activo Apply Vanishing Point ({key}) Aplicar punto de fuga ({key}) Fix the red plane first: its corners must form a convex quad Corrija primero el plano rojo: sus esquinas deben formar un cuadrilátero convexo + Alt-click a plane to set the clone source Haga Alt-clic en un plano para definir el origen de clonación + Too many clone strokes: apply Vanishing Point first Demasiados trazos de clonación: aplique primero Punto de fuga # Select and Mask view modes (#1754) Onion Skin Papel cebolla Marching Ants Hormigas en marcha diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 7085401552..b457b1f875 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3157,6 +3157,8 @@ curves Smooth Lisser Vanishing Point is not active Point de fuite n’est pas actif Apply Vanishing Point ({key}) Appliquer le point de fuite ({key}) Fix the red plane first: its corners must form a convex quad Corrigez d’abord le plan rouge : ses coins doivent former un quadrilatère convexe + Alt-click a plane to set the clone source Alt-clic sur un plan pour définir la source de duplication + Too many clone strokes: apply Vanishing Point first Trop de traits de duplication : appliquez d’abord Point de fuite # Select and Mask view modes (#1754) Onion Skin Pelure d'oignon Marching Ants Fourmis en marche diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c40735a26a..c89fdfa596 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4037,6 +4037,8 @@ cameraRaw Yellow Sárga Amount: Mérték: Apply Vanishing Point ({key}) Enyészpont alkalmazása ({key}) Apply the removal ({key}) Eltávolítás alkalmazása ({key}) + Alt-click a plane to set the clone source Alt-kattintás egy síkra a klónforrás beállításához + Too many clone strokes: apply Vanishing Point first Túl sok klónvonás: először alkalmazza az Enyészpontot Drag to draw the curve · {key}-click draws a straight line Húzással rajzold meg a görbét · {key}+kattintás: egyenes vonal Draw to modify the curve Rajzolj a görbe módosításához Edit points to modify the curve Szerkeszd a pontokat a görbe módosításához diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 3012fd4db1..8f41815088 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3161,6 +3161,8 @@ curves Smooth Haluskan Vanishing Point is not active Vanishing Point tidak aktif Apply Vanishing Point ({key}) Terapkan Vanishing Point ({key}) Fix the red plane first: its corners must form a convex quad Perbaiki bidang merah dulu: sudut-sudutnya harus membentuk segi empat cembung + Alt-click a plane to set the clone source Alt-klik sebuah bidang untuk menetapkan sumber kloning + Too many clone strokes: apply Vanishing Point first Terlalu banyak goresan kloning: terapkan Vanishing Point terlebih dahulu # Select and Mask view modes (#1754) Onion Skin Kulit Bawang Marching Ants Semut Berbaris diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 700d120cff..fe89d44a33 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2806,6 +2806,8 @@ curves Smooth Leviga Vanishing Point is not active Punto di fuga non è attivo Apply Vanishing Point ({key}) Applica punto di fuga ({key}) Fix the red plane first: its corners must form a convex quad Correggi prima il piano rosso: i suoi angoli devono formare un quadrilatero convesso + Alt-click a plane to set the clone source Alt-clic su un piano per impostare l’origine della clonazione + Too many clone strokes: apply Vanishing Point first Troppi tratti di clonazione: applica prima Punto di fuga # Select and Mask view modes (#1754) Onion Skin Velina Marching Ants Formiche in marcia diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 85e3f0f8e6..52265feae2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3747,6 +3747,8 @@ curves Smooth スムーズ Vanishing Point: click four corners to create a plane 消点: 4 つの角をクリックして面を作成します Vanishing Point is not active 消点はアクティブではありません Apply Vanishing Point ({key}) 消点を適用({key}) + Alt-click a plane to set the clone source Alt キーを押しながら平面をクリックしてコピー元を設定 + Too many clone strokes: apply Vanishing Point first コピースタンプのストロークが多すぎます:先に消点を適用してください Fix the red plane first: its corners must form a convex quad 先に赤い面を修正してください: 角が凸四角形になる必要があります # Select and Mask view modes (#1754) Onion Skin オニオンスキン diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e9b0cb26d4..adf5efb7b3 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3350,6 +3350,8 @@ curves Smooth 매끄럽게 Vanishing Point is not active 소실점이 활성화되어 있지 않습니다 Apply Vanishing Point ({key}) 소실점 적용 ({key}) Fix the red plane first: its corners must form a convex quad 먼저 빨간색 평면을 수정하십시오: 모서리가 볼록 사각형을 이루어야 합니다 + Alt-click a plane to set the clone source Alt 키를 누른 채 평면을 클릭하여 복제 소스를 설정하십시오 + Too many clone strokes: apply Vanishing Point first 복제 획이 너무 많습니다. 먼저 소실점을 적용하십시오 # Select and Mask view modes (#1754) Onion Skin 어니언 스킨 Marching Ants 점선 윤곽 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 1f2b36c2df..67209f2f2b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3890,6 +3890,8 @@ curves Smooth Vloeiend maken Vanishing Point is not active Verdwijnpunt is niet actief Apply Vanishing Point ({key}) Verdwijnpunt toepassen ({key}) Fix the red plane first: its corners must form a convex quad Herstel eerst het rode vlak: de hoeken moeten een convexe vierhoek vormen + Alt-click a plane to set the clone source Alt-klik op een vlak om de kloonbron in te stellen + Too many clone strokes: apply Vanishing Point first Te veel kloonstreken: pas eerst Verdwijnpunt toe # Select and Mask view modes (#1754) Onion Skin Uienschil Marching Ants Mierenmars diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 3acc77dd61..5c7411a49d 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3766,6 +3766,8 @@ curves Smooth Wygładź Vanishing Point is not active Punkt zbieżności nie jest aktywny Apply Vanishing Point ({key}) Zastosuj punkt zbieżności ({key}) Fix the red plane first: its corners must form a convex quad Najpierw popraw czerwoną płaszczyznę: jej narożniki muszą tworzyć czworokąt wypukły + Alt-click a plane to set the clone source Kliknij płaszczyznę z Alt, aby ustawić źródło klonowania + Too many clone strokes: apply Vanishing Point first Zbyt wiele pociągnięć klonowania: najpierw zastosuj Punkt zbieżności # Select and Mask view modes (#1754) Onion Skin Skórka cebuli Marching Ants Maszerujące mrówki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 7584dd705c..aa4e33c14e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3159,6 +3159,8 @@ curves Smooth Suavizar Vanishing Point is not active Ponto de fuga não está ativo Apply Vanishing Point ({key}) Aplicar ponto de fuga ({key}) Fix the red plane first: its corners must form a convex quad Corrija primeiro o plano vermelho: seus cantos devem formar um quadrilátero convexo + Alt-click a plane to set the clone source Clique com Alt em um plano para definir a origem da clonagem + Too many clone strokes: apply Vanishing Point first Traços de clonagem demais: aplique Ponto de fuga primeiro # Select and Mask view modes (#1754) Onion Skin Papel vegetal Marching Ants Formigas marchando diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index cfd4d7c737..f7dc4457f1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3082,6 +3082,8 @@ curves Smooth Сгладить Vanishing Point is not active Точка схода не активна Apply Vanishing Point ({key}) Применить точку схода ({key}) Fix the red plane first: its corners must form a convex quad Сначала исправьте красную плоскость: ее углы должны образовывать выпуклый четырехугольник + Alt-click a plane to set the clone source Щёлкните плоскость с Alt, чтобы задать источник клонирования + Too many clone strokes: apply Vanishing Point first Слишком много мазков клонирования: сначала примените «Точку схода» # Select and Mask view modes (#1754) Onion Skin Калька Marching Ants Бегущие муравьи diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index 3c5ece3ecc..b609494875 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -3086,6 +3086,8 @@ curves Smooth Izgladi Vanishing Point is not active Tačka nestajanja nije aktivna Apply Vanishing Point ({key}) Primeni tačku nestajanja ({key}) Fix the red plane first: its corners must form a convex quad Prvo ispravite crvenu ravan: njeni uglovi moraju činiti konveksan četvorougao + Alt-click a plane to set the clone source Alt-kliknite ravan da postavite izvor kloniranja + Too many clone strokes: apply Vanishing Point first Previše poteza kloniranja: prvo primenite tačku nestajanja # Select and Mask view modes (#1754) Onion Skin Prozirni prikaz Marching Ants Pokretne crtice diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 412b967873..8cd7cb5db8 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3838,6 +3838,8 @@ cameraData Lens Lens Draw to modify the curve Eğriyi değiştirmek için çiz Edit points to modify the curve Eğriyi değiştirmek için noktaları düzenle Fix the red plane first: its corners must form a convex quad Önce kırmızı düzlemi düzeltin: köşeleri dışbükey bir dörtgen oluşturmalı + Alt-click a plane to set the clone source Klon kaynağını ayarlamak için bir düzleme Alt+tıklayın + Too many clone strokes: apply Vanishing Point first Çok fazla klon darbesi: önce Kaybolma Noktası'nı uygulayın Grid Size: Izgara Boyutu: Light Blue Açık Mavi Light Gray Açık Gri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index ff5afa42bd..15a50e19f7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3824,6 +3824,8 @@ curves Smooth Згладити Vanishing Point is not active Точка сходження не активна Apply Vanishing Point ({key}) Застосувати точку сходження ({key}) Fix the red plane first: its corners must form a convex quad Спершу виправте червону площину: її кути мають утворювати опуклий чотирикутник + Alt-click a plane to set the clone source Клацніть площину з Alt, щоб задати джерело клонування + Too many clone strokes: apply Vanishing Point first Забагато мазків клонування: спочатку застосуйте «Точку сходження» # Select and Mask view modes (#1754) Onion Skin Калька Marching Ants Мурашки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index d56fb6f20b..e09bd39de2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2462,6 +2462,8 @@ shape Appearance Diện mạo Fill with {mode}-neutral color (black) Tô bằng màu trung tính của {mode} (đen) Fill with {mode}-neutral color (white) Tô bằng màu trung tính của {mode} (trắng) Fix the red plane first: its corners must form a convex quad Hãy sửa mặt phẳng đỏ trước: các góc phải tạo thành tứ giác lồi + Alt-click a plane to set the clone source Nhấp Alt vào một mặt phẳng để đặt nguồn sao chép + Too many clone strokes: apply Vanishing Point first Quá nhiều nét sao chép: hãy áp dụng Điểm tụ trước Float Panel Thả nổi bảng Functions Hàm Grid Size: Cỡ lưới: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 740006cb61..a79b84a2ba 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2790,6 +2790,9 @@ curves Smooth 平滑 Vanishing Point is not active 消失点未处于活动状态 Apply Vanishing Point ({key}) 应用消失点({key}) Fix the red plane first: its corners must form a convex quad 请先修正红色平面:其四个角必须构成凸四边形 + Alt-click a plane to set the clone source 按住 Alt 键单击平面以设置仿制源 + Too many clone strokes: apply Vanishing Point first 仿制描边过多:请先应用消失点 + Stamp 图章 # Select and Mask view modes (#1754) Onion Skin 洋葱皮 Marching Ants 蚂蚁线 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 729cbbf3ec..198ae1faa0 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2739,6 +2739,9 @@ curves Smooth 平滑 Vanishing Point is not active 消失點未啟用 Apply Vanishing Point ({key}) 套用消失點 ({key}) Fix the red plane first: its corners must form a convex quad 請先修正紅色平面:其四個角必須構成凸四邊形 + Alt-click a plane to set the clone source 按住 Alt 鍵按一下平面以設定仿製來源 + Too many clone strokes: apply Vanishing Point first 仿製筆畫過多:請先套用消失點 + Stamp 印章 # Select and Mask view modes (#1754) Onion Skin 洋蔥皮 Marching Ants 螞蟻線 diff --git a/crates/ui-egui/src/vp_ui.rs b/crates/ui-egui/src/vp_ui.rs index 61ad0a4425..d93cc9dc20 100644 --- a/crates/ui-egui/src/vp_ui.rs +++ b/crates/ui-egui/src/vp_ui.rs @@ -2,19 +2,27 @@ //! //! **Create Plane** (C): four clicks set a plane's corners, in any order. **Edit Plane** (V): //! drag a corner node, or an edge node to slide that edge along the plane's own perspective; -//! click a plane to select it, Delete removes it. The plane's grid is drawn at the Grid Size and, +//! click a plane to select it, Delete removes it. Ctrl/Cmd-dragging an edge node tears off a +//! perpendicular plane; dragging the torn plane's far edge node sets its depth and Alt-dragging +//! it its angle (it stays a torn-off plane, so it follows its parent). The plane's grid is drawn +//! at the Grid Size and, //! like Photoshop's, in the accent colour when the plane is valid, yellow when its perspective is //! doubtful and red when it is invalid ([`VpPlane::check`]). With an image on the clipboard the -//! selected plane shows it pasted in perspective; drag it to move it on the plane. ↩ / OK runs -//! `filter.vanishingPoint` with the planes and the paste, so it is one history step and an -//! action or agent can replay it exactly. +//! selected plane shows it pasted in perspective; drag it to move it on the plane. **Stamp** (S): +//! Alt-click a plane to set the source, then paint to clone in perspective (Diameter, Hardness, +//! Opacity, Aligned); the canvas shows the strokes as they are painted. ↩ / OK runs +//! `filter.vanishingPoint` with the planes, the paste and the strokes, so the whole session is +//! one history step and an action or agent can replay it exactly. + +use std::sync::Arc; use egui::{Color32, Pos2, Stroke, TextureHandle, pos2}; use photocraft_algo::transform::Homography; -use photocraft_algo::vanishing::{PlaneCheck, Scene, VpPlane}; -use photocraft_doc::{DocId, LayerContent, LayerId}; -use photocraft_engine::vp_cmds::VP; +use photocraft_algo::vanishing::{Edge, PlaneCheck, Scene, VpPlane, clone_dabs_from, clone_source}; +use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; +use photocraft_engine::vp_cmds::{CloneSpec, MAX_CLONE_DABS, MAX_CLONE_STROKES, VP, copy_changed, over, paste_onto, visible_image}; use photocraft_geom::Rect; +use photocraft_raster::Surface; use serde_json::{Value, json}; use crate::PhotocraftApp; @@ -26,6 +34,45 @@ use crate::edit_history::{EditHistory, Step}; pub enum VpTool { EditPlane, CreatePlane, + Stamp, +} + +/// A plane torn off an edge of an earlier plane: the engine's +/// `{"from", "edge", "angle", "depth"}`, so it follows its parent when that is edited. +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] +pub struct Torn { + pub from: usize, + pub edge: Edge, + /// Degrees between the planes (90 = perpendicular). + pub angle: f64, + /// Extent as a multiple of the parent's adjacent side. + pub depth: f64, +} + +/// The Stamp tool's options. +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StampOptions { + /// Brush diameter in px where a stroke starts. + pub diameter: f64, + /// 0..=100. + pub hardness: f64, + /// 0..=100. + pub opacity: f64, + /// Later strokes keep the first stroke's source offset instead of restarting at the source. + pub aligned: bool, +} + +/// Edge node `i` (0 top, 1 right, 2 bottom, 3 left) as the engine's edge. +const EDGES: [Edge; 4] = [Edge::Top, Edge::Right, Edge::Bottom, Edge::Left]; + +fn edge_index(e: Edge) -> usize { + match e { + Edge::Top => 0, + Edge::Right => 1, + Edge::Bottom => 2, + Edge::Left => 3, + } } enum Drag { @@ -36,10 +83,41 @@ enum Drag { Edge { plane: usize, edge: usize, h: Homography, inv: Homography }, /// The pasted image, and the pointer offset from its top-left in plane coordinates. Paste { offset: [f64; 2] }, + /// The far edge node of torn-off plane `plane` (or of one being torn off): the drag sets + /// its depth, or with `rotate` (Alt) its angle, once it has left `start`. + Torn { plane: usize, rotate: bool, start: [f64; 2], moved: bool }, + /// Painting the last of the clone strokes. + Stamp, +} + +/// The clone strokes painted onto the target layer, shown on the canvas while stamping. +struct StampPreview { + /// The session's `rev`, New Layer and paste it was painted with (any changing repaints it). + rev: u64, + new_layer: bool, + /// The paste (plane, top-left, width) baked in under the strokes, as OK pastes before it clones. + paste: Option<(usize, [f64; 2], f64)>, + /// The paste landed in `out` (it can fail, or miss the plane). + baked: bool, + /// On a new layer: the visible image the strokes sample, with the strokes so far. + work: Option, + /// The sampled image before the current stroke, retained across frame batches. + source: Option<(usize, Surface)>, + /// The target layer's pixels as painted so far. + out: Surface, + /// Strokes painted: those before `.0`, and the first `.1` points of stroke `.0`. + done: (usize, usize), + /// Preview keys shown, each with the area changed since the previous one (the first since + /// the document). + keys: Vec<(u64, Rect)>, + shown: Arc, } /// The clipboard image shown pasted onto the plane. struct Clip { + /// The clipboard pixels and their content bounds, which the preview pastes like OK does. + surface: Surface, + rect: Rect, texture: TextureHandle, width: f64, height: f64, @@ -50,7 +128,10 @@ pub struct VpSession { pub document: DocId, pub layer: LayerId, canvas: Rect, + /// The planes' corners; torn-off planes' are derived from their parents ([`Self::resolve`]). pub planes: Vec, + /// Per plane: how it was torn off, or `None` for a drawn plane (always the first one). + pub torn: Vec>, pub tool: VpTool, /// Corners clicked so far with Create Plane. pending: Vec<[f64; 2]>, @@ -66,26 +147,76 @@ pub struct VpSession { pub new_layer: bool, clip: Option, drag: Option, + pub stamp: StampOptions, + /// Stamp source (Alt-click), image px. + pub source: Option<[f64; 2]>, + /// Clone strokes painted so far, sent as `"clone"` on OK. + pub strokes: Vec, + /// The first stroke's (source, start) since the source was set: Aligned strokes keep its offset. + aligned_ref: Option<([f64; 2], [f64; 2])>, + /// Bumped whenever the planes or the strokes change other than by painting on. + rev: u64, + /// The document as the session began (the preview paints over it). + base: Arc, + doc_revision: u64, + preview: Option, history: EditHistory, } -/// What ⌘Z steps through: the planes and where the paste sits on them. -type VpEdit = (Vec, [f64; 2], f64); +/// What ⌘Z steps through: the planes (and how they were torn off), where the paste sits on +/// them, and the clone source and strokes. +#[derive(Clone, PartialEq)] +struct VpEdit { + planes: Vec, + torn: Vec>, + paste_at: [f64; 2], + paste_width: f64, + source: Option<[f64; 2]>, + strokes: Vec, + aligned_ref: Option<([f64; 2], [f64; 2])>, +} /// Most planes a session holds (the control channel can't make it allocate without bound). const MAX_PLANES: usize = 64; /// Most grid lines drawn per direction. const MAX_LINES: usize = 200; +/// Preview keys of the stamp preview: `PREVIEW_KEY + id` (see `canvas::display_doc`). +const PREVIEW_KEY: u64 = 1 << 42; + +fn union(a: Rect, b: Rect) -> Rect { + if a.is_empty() { + b + } else if b.is_empty() { + a + } else { + a.union(&b) + } +} impl VpSession { pub fn describe(&self) -> Value { let center = self.center(); - let planes: Vec = self.planes.iter().map(|p| json!({"corners": p.corners, "check": p.check(center)})).collect(); + let planes: Vec = self + .planes + .iter() + .enumerate() + .map(|(i, p)| { + let mut v = json!({"corners": p.corners, "check": p.check(center)}); + if let Some(t) = self.torn.get(i).copied().flatten() { + v["tornOff"] = json!(t); + } + v + }) + .collect(); json!({ "document": self.document.0, "layer": self.layer.0, "tool": self.tool, "planes": planes, + "stamp": self.stamp, + "source": self.source, + "strokes": self.strokes.len(), + "dabs": self.dabs(), "pending": self.pending, "selected": self.selected, "gridSize": self.grid_size, @@ -127,25 +258,98 @@ impl VpSession { self.selected.filter(|i| *i < self.planes.len()).or_else(|| (!self.planes.is_empty()).then_some(0)) } + /// What OK pastes: the plane, the top-left and the width. + fn paste_key(&self) -> Option<(usize, [f64; 2], f64)> { + self.paste_plane().map(|i| (i, self.paste_at, self.paste_width)) + } + + /// The stamp preview is current and already shows the paste under the strokes. + fn preview_has_paste(&self) -> bool { + self.preview.as_ref().is_some_and(|p| p.baked && p.rev == self.rev && p.paste == self.paste_key()) + } + + /// The paste is dragged while the stamp preview holds it in its old place. + fn moving_baked_paste(&self) -> bool { + matches!(self.drag, Some(Drag::Paste { .. })) && self.preview.as_ref().is_some_and(|p| p.baked) + } + + /// [`draw_content`] draws the paste overlay: not when the stamp preview shows the paste, and + /// not while a plane drag freezes that preview (as it freezes the strokes) until release. + fn paste_overlay(&self) -> bool { + let frozen = matches!(self.drag, Some(Drag::Corner { .. } | Drag::Edge { .. } | Drag::Torn { .. })) && self.preview.as_ref().is_some_and(|p| p.baked); + !self.preview_has_paste() && !frozen + } + /// Size of the pasted image in plane coordinates (the engine keeps its metric aspect). fn paste_extent(&self, lu: f64, lv: f64) -> Option<[f64; 2]> { let c = self.clip.as_ref()?; Some([self.paste_width, self.paste_width * lu / lv * c.height / c.width.max(1.0)]) } - /// The command's params: the planes, and the paste when there is one. + /// The command's params: the planes (torn-off ones as such), the paste and the clone + /// strokes when there are any. pub fn params(&self) -> Value { - let planes: Vec = self.planes.iter().map(|p| json!({"corners": p.corners})).collect(); + let planes: Vec = self + .planes + .iter() + .enumerate() + .map(|(i, p)| match self.torn.get(i).copied().flatten() { + Some(t) => json!({"from": t.from, "edge": t.edge, "angle": t.angle, "depth": t.depth}), + None => json!({"corners": p.corners}), + }) + .collect(); let mut p = json!({"planes": planes}); if let Some(i) = self.paste_plane() { p["paste"] = json!([{"plane": i, "at": self.paste_at, "width": self.paste_width}]); } + if !self.strokes.is_empty() { + let clone: Vec = self + .strokes + .iter() + .map(|c| json!({"source": c.source, "points": c.points, "size": c.size, "hardness": c.hardness * 100.0, "opacity": c.opacity * 100.0})) + .collect(); + p["clone"] = json!(clone); + } if self.new_layer { p["newLayer"] = json!(true); } p } + fn dabs(&self) -> usize { + self.strokes.iter().map(|c| c.points.len()).sum() + } + + /// Recomputes the torn-off planes' corners from their parents, in order (the way the engine + /// builds the scene), so they follow every edit. A plane that can't be torn off any more + /// (it would lie behind the camera) collapses to an invalid one. + fn resolve(&mut self) { + self.rev += 1; + self.torn.resize(self.planes.len(), None); + let Some(first) = self.planes.first().cloned() else { return }; + let fallback = f64::from(self.canvas.width().max(self.canvas.height())); + let mut sc = Scene::new(first, self.center(), None, fallback); + for i in 1..self.planes.len() { + match self.torn.get(i).copied().flatten().filter(|t| t.from < i) { + Some(t) => { + if sc.tear_off(t.from, t.edge, t.angle, t.depth).is_none() { + sc.planes.push(VpPlane { corners: [[0.0; 2]; 4] }); + } + } + None => sc.planes.push(self.planes[i].clone()), + } + } + self.planes = sc.planes; + } + + fn push_plane(&mut self, plane: VpPlane, torn: Option) { + self.torn.resize(self.planes.len(), None); + self.planes.push(plane); + self.torn.push(torn); + self.selected = Some(self.planes.len() - 1); + self.resolve(); + } + fn add_corner(&mut self, p: [f64; 2]) { if self.planes.len() >= MAX_PLANES { return; @@ -153,15 +357,22 @@ impl VpSession { self.pending.push(p); if let Ok(corners) = <[[f64; 2]; 4]>::try_from(self.pending.as_slice()) { self.pending.clear(); - self.planes.push(VpPlane { corners }.normalized()); - self.selected = Some(self.planes.len() - 1); + self.push_plane(VpPlane { corners }.normalized(), None); // Photoshop hands over to Edit Plane once a plane is closed. self.tool = VpTool::EditPlane; } } fn edit(&self) -> VpEdit { - (self.planes.clone(), self.paste_at, self.paste_width) + VpEdit { + planes: self.planes.clone(), + torn: self.torn.clone(), + paste_at: self.paste_at, + paste_width: self.paste_width, + source: self.source, + strokes: self.strokes.clone(), + aligned_ref: self.aligned_ref, + } } fn settle(&mut self, busy: bool) { @@ -172,19 +383,268 @@ impl VpSession { pub(crate) fn step(&mut self, step: Step) { let mut now = self.edit(); if self.history.step(&mut now, step) { - (self.planes, self.paste_at, self.paste_width) = now; + let VpEdit { planes, torn, paste_at, paste_width, source, strokes, aligned_ref } = now; + (self.planes, self.torn, self.paste_at, self.paste_width) = (planes, torn, paste_at, paste_width); + (self.source, self.strokes, self.aligned_ref) = (source, strokes, aligned_ref); self.drag = None; + self.pending.clear(); self.selected = self.selected.filter(|i| *i < self.planes.len()); + // The stamp preview repaints from scratch. + self.rev += 1; } } + /// Deletes the selected plane; planes torn off it keep their place as drawn planes. fn delete_selected(&mut self) { if let Some(i) = self.selected.take().filter(|i| *i < self.planes.len()) { + self.torn.resize(self.planes.len(), None); self.planes.remove(i); + self.torn.remove(i); + for t in self.torn.iter_mut() { + match t { + Some(c) if c.from == i => *t = None, + Some(c) if c.from > i => c.from -= 1, + _ => {} + } + } self.drag = None; + self.resolve(); } } + /// Starts tearing a plane off edge `edge` of plane `from` at the press `p`. + fn tear_off(&mut self, from: usize, edge: usize, p: [f64; 2]) { + if self.planes.len() >= MAX_PLANES { + return; + } + let Some(&e) = EDGES.get(edge) else { return }; + self.push_plane(VpPlane { corners: [[0.0; 2]; 4] }, Some(Torn { from, edge: e, angle: 90.0, depth: 0.5 })); + // As after closing a plane, Edit Plane takes over. + self.tool = VpTool::EditPlane; + self.pending.clear(); + self.drag = Some(Drag::Torn { plane: self.planes.len() - 1, rotate: false, start: p, moved: false }); + } + + /// Fits torn plane `i`'s depth (or with `rotate` its angle) so its far edge's middle is as + /// near `p` as it can get. + fn fit_torn(&mut self, i: usize, rotate: bool, p: [f64; 2]) { + let Some(t) = self.torn.get(i).copied().flatten() else { return }; + let Some(first) = self.planes.first().cloned() else { return }; + if t.from >= i || i >= self.planes.len() { + return; + } + let fallback = f64::from(self.canvas.width().max(self.canvas.height())); + let mut sc = Scene::new(first, self.center(), None, fallback); + sc.planes.extend(self.planes.iter().take(i).skip(1).cloned()); + let e = edge_index(t.edge); + let mut miss = |angle: f64, depth: f64| -> f64 { + if sc.tear_off(t.from, t.edge, angle, depth).is_none() { + return f64::MAX; + } + let Some(c) = sc.planes.pop().map(|pl| pl.corners) else { return f64::MAX }; + let (a, b) = (c[e], c[(e + 1) % 4]); + let d = ((a[0] + b[0]) / 2.0 - p[0]).hypot((a[1] + b[1]) / 2.0 - p[1]); + if d.is_finite() { d } else { f64::MAX } + }; + let best = |values: &mut dyn Iterator, miss: &mut dyn FnMut(f64) -> f64| { + values.map(|v| (miss(v), v)).filter(|m| m.0 < f64::MAX).min_by(|a, b| a.0.total_cmp(&b.0)).map(|m| m.1) + }; + let (angle, depth) = if rotate { + let Some(a) = best(&mut (1..180).map(f64::from), &mut |a| miss(a, t.depth)) else { return }; + let a = best(&mut (-10..=10).map(|k| a + f64::from(k) / 10.0), &mut |a| miss(a, t.depth)).unwrap_or(a); + (a.clamp(1.0, 179.0), t.depth) + } else { + let Some(d) = best(&mut (0..=160).map(|k| 0.02 * 1.06f64.powi(k)), &mut |d| miss(t.angle, d)) else { return }; + let d = best(&mut (-10..=10).map(|k| d * (1.0 + f64::from(k) * 0.006)), &mut |d| miss(t.angle, d)).unwrap_or(d); + (t.angle, d.clamp(0.02, 1000.0)) + }; + if let Some(Some(t)) = self.torn.get_mut(i) { + t.angle = angle; + t.depth = depth; + } + self.resolve(); + } + + /// Stamp press: Alt sets the source, otherwise a stroke starts. Returns a status message. + fn stamp_press(&mut self, p: [f64; 2], alt: bool) -> Option<&'static str> { + let sc = self.scene()?; + let on_plane = |q: [f64; 2]| sc.plane_at(q).is_some(); + if alt { + if !on_plane(p) { + return Some(tl!("Alt-click a plane to set the clone source")); + } + self.source = Some(p); + self.aligned_ref = None; + return None; + } + let Some(source) = self.source else { return Some(tl!("Alt-click a plane to set the clone source")) }; + if !on_plane(p) { + return None; + } + if self.strokes.len() >= MAX_CLONE_STROKES || self.dabs() >= MAX_CLONE_DABS { + return Some(tl!("Too many clone strokes: apply Vanishing Point first")); + } + let src = match self.aligned_ref.filter(|_| self.stamp.aligned) { + Some((s0, a0)) => clone_source(&sc, s0, a0, p).filter(|s| on_plane(*s)).unwrap_or(source), + None => source, + }; + if self.aligned_ref.is_none() { + self.aligned_ref = Some((src, p)); + } + let o = self.stamp; + self.strokes.push(CloneSpec { source: src, points: vec![p], size: o.diameter, hardness: o.hardness / 100.0, opacity: o.opacity / 100.0 }); + self.drag = Some(Drag::Stamp); + None + } + + /// Extends the current stroke to `p` with dabs a tenth of the brush apart. + fn stamp_to(&mut self, p: [f64; 2]) { + let room = MAX_CLONE_DABS.saturating_sub(self.dabs()); + let Some(c) = self.strokes.last_mut() else { return }; + let Some(last) = c.points.last().copied() else { return }; + let step = (c.size * 0.1).max(1.0); + let d = (p[0] - last[0]).hypot(p[1] - last[1]); + if !d.is_finite() || d < step { + return; + } + let n = ((d / step) as usize).min(room); + c.points.extend((1..=n).map(|k| { + let t = k as f64 * step / d; + [last[0] + (p[0] - last[0]) * t, last[1] + (p[1] - last[1]) * t] + })); + } + + /// Paints what the preview doesn't show yet (all of it after the planes changed). `key` + /// names a new preview. False when nothing changed. + fn paint_preview(&mut self, key: impl FnOnce() -> u64) -> bool { + if self.strokes.is_empty() { + let had = self.preview.is_some(); + self.preview = None; + return had; + } + let Some(sc) = self.scene() else { + // No planes left: nothing to show the strokes on. + return self.preview.take().is_some(); + }; + let paste = self.paste_key(); + let canvas = self.canvas; + let stale = self.preview.as_ref().is_none_or(|p| p.rev != self.rev || p.new_layer != self.new_layer || p.paste != paste); + let mut area = Rect::EMPTY; + let mut baked = false; + if stale { + let Some(layer) = self.base.layer(self.layer).and_then(Layer::surface) else { + // The layer is gone (or no longer pixels): nothing to show the strokes on. + return self.preview.take().is_some(); + }; + let mut out = if self.new_layer { Surface::new(layer.format()) } else { layer.clone() }; + // OK pastes first and the strokes then paint over (and sample) the pasted pixels. + if let (Some((i, at, width)), Some(c)) = (paste, self.clip.as_ref()) + && self.planes.get(i).is_some_and(|p| p.check(self.center()) != PlaneCheck::Invalid) + && let Ok(r) = paste_onto(&sc, &mut out, i, &c.surface, c.rect, at, width) + { + area = r.intersect(&canvas); + baked = !r.is_empty(); + } + let work = self.new_layer.then(|| { + let mut w = visible_image(&self.base); + over(&mut w, &out); + w + }); + // The old preview's area changes back too. + let keys = self.preview.take().map(|p| p.keys).unwrap_or_default(); + area = keys.iter().fold(area, |a, k| union(a, k.1)); + self.preview = Some(StampPreview { + rev: self.rev, + new_layer: self.new_layer, + paste, + baked, + work, + source: None, + out, + done: (0, 0), + keys, + shown: self.base.clone(), + }); + } + let Some(pv) = self.preview.as_mut() else { return false }; + let (from_stroke, from_point) = pv.done; + for (si, c) in self.strokes.iter().enumerate().skip(from_stroke) { + let skip = if si == from_stroke { from_point } else { 0 }; + let (Some(anchor), Some(points)) = (c.points.first(), c.points.get(skip..)) else { continue }; + if points.is_empty() { + continue; + } + if pv.source.as_ref().is_none_or(|(stroke, _)| *stroke != si) { + pv.source = Some((si, pv.work.as_ref().unwrap_or(&pv.out).clone())); + } + let Some((_, source)) = pv.source.as_ref() else { continue }; + let (hard, opacity) = (c.hardness, c.opacity as f32); + let changed = match pv.work.as_mut() { + Some(work) => { + let before = work.clone(); + let (_, a) = clone_dabs_from(&sc, work, source, c.source, *anchor, points, c.size, hard, opacity); + // As OK does: only the canvas (the dabs' boxes can span far off it). + let a = a.intersect(&canvas); + copy_changed(&mut pv.out, &before, work, a); + a + } + None => clone_dabs_from(&sc, &mut pv.out, source, c.source, *anchor, points, c.size, hard, opacity).1.intersect(&canvas), + }; + area = union(area, changed); + } + pv.done = (self.strokes.len() - 1, self.strokes.last().map_or(0, |c| c.points.len())); + if area.is_empty() && !stale { + return false; + } + let mut d = (*self.base).clone(); + if self.new_layer { + let mut l = Layer::raster(d.next_layer_name("Vanishing Point"), d.pixel_format()); + l.content = LayerContent::Raster(pv.out.clone()); + d.insert_above(Some(self.layer), l); + } else if let Some(LayerContent::Raster(s)) = d.layer_mut(self.layer).map(|l| &mut l.content) { + *s = pv.out.clone(); + } + pv.shown = Arc::new(d); + pv.keys.push((key(), area)); + true + } + + /// The document with the strokes painted, and its preview key. Not while the paste is + /// dragged out of its baked-in place: the overlay follows the pointer instead, and the + /// strokes repaint over it on release. + pub(crate) fn shown(&self) -> Option<(Arc, u64)> { + let p = self.preview.as_ref()?; + if self.moving_baked_paste() { + return None; + } + Some((p.shown.clone(), PREVIEW_KEY + p.keys.last()?.0)) + } + + /// [`Self::shown`], only on the document at the revision the strokes were painted on. + pub(crate) fn shown_on(&self, doc: DocId, revision: u64) -> Option<(Arc, u64)> { + if self.document != doc || self.doc_revision != revision { + return None; + } + self.shown() + } + + /// The document changed under the mode (a menu command, the Layers panel): paint the + /// strokes over it as it is now, as OK will. + fn rebase(&mut self, doc: &Arc, revision: u64) { + if doc.id != self.document || revision == self.doc_revision { + return; + } + if Arc::ptr_eq(doc, &self.base) { + // A view change (layer selection, channel view): the same pixels, keep the preview. + self.doc_revision = revision; + return; + } + self.base = doc.clone(); + self.doc_revision = revision; + self.canvas = doc.bounds(); + self.preview = None; + } + /// Image positions of the edge nodes of plane `i`. fn edge_nodes(&self, i: usize) -> Option<[[f64; 2]; 4]> { let h = self.planes.get(i)?.homography()?; @@ -195,20 +655,40 @@ impl VpSession { Some([at(0.5, 0.0), at(1.0, 0.5), at(0.5, 1.0), at(0.0, 0.5)]) } - fn press(&mut self, p: [f64; 2], tol: f64) { - if self.tool == VpTool::CreatePlane { - self.add_corner(p); - return; + fn press(&mut self, p: [f64; 2], tol: f64, mods: egui::Modifiers) -> Option<&'static str> { + if self.tool == VpTool::Stamp { + return self.stamp_press(p, mods.alt); } let near = |c: [f64; 2]| (c[0] - p[0]).hypot(c[1] - p[1]) <= tol; // The selected plane's nodes win over the others'. let order: Vec = self.selected.into_iter().chain((0..self.planes.len()).rev()).filter(|i| *i < self.planes.len()).collect(); + // Ctrl/Cmd on an edge node tears off a perpendicular plane (with either plane tool). + if mods.command + && let Some((i, e)) = order.iter().find_map(|&i| Some((i, self.edge_nodes(i)?.iter().position(|c| near(*c))?))) + { + self.tear_off(i, e, p); + return None; + } + if self.tool == VpTool::CreatePlane { + self.add_corner(p); + return None; + } for &i in &order { + // A torn-off plane follows its parent: only its far edge node drags (depth, or + // with Alt the angle). + if let Some(t) = self.torn.get(i).copied().flatten() { + if self.edge_nodes(i).and_then(|n| n.get(edge_index(t.edge)).copied()).is_some_and(near) { + self.selected = Some(i); + self.drag = Some(Drag::Torn { plane: i, rotate: mods.alt, start: p, moved: false }); + return None; + } + continue; + } if let Some(ci) = self.planes[i].corners.iter().position(|c| near(*c)) { let c = self.planes[i].corners[ci]; self.selected = Some(i); self.drag = Some(Drag::Corner { plane: i, corner: ci, offset: [c[0] - p[0], c[1] - p[1]] }); - return; + return None; } if let Some(e) = self.edge_nodes(i).and_then(|n| n.iter().position(|c| near(*c))) && let Some(h) = self.planes[i].homography() @@ -216,7 +696,7 @@ impl VpSession { { self.selected = Some(i); self.drag = Some(Drag::Edge { plane: i, edge: e, h, inv }); - return; + return None; } } if let Some(i) = self.paste_plane() @@ -228,19 +708,30 @@ impl VpSession { let (a, b) = (self.paste_at, [self.paste_at[0] + ext[0], self.paste_at[1] + ext[1]]); if (a[0]..=b[0]).contains(&u) && (a[1]..=b[1]).contains(&v) { self.drag = Some(Drag::Paste { offset: [a[0] - u, a[1] - v] }); - return; + return None; } } self.selected = self.scene().and_then(|sc| sc.plane_at(p)); + None } fn drag_to(&mut self, p: [f64; 2]) { - match &self.drag { + match &mut self.drag { Some(Drag::Corner { plane, corner, offset }) => { if let Some(c) = self.planes.get_mut(*plane).and_then(|pl| pl.corners.get_mut(*corner)) { *c = [p[0] + offset[0], p[1] + offset[1]]; } + self.resolve(); } + Some(Drag::Torn { plane, rotate, start, moved }) => { + // A click without a drag leaves the plane as it is. + *moved |= (p[0] - start[0]).hypot(p[1] - start[1]) > 2.0; + if *moved { + let (i, r) = (*plane, *rotate); + self.fit_torn(i, r, p); + } + } + Some(Drag::Stamp) => self.stamp_to(p), Some(Drag::Edge { plane, edge, h, inv }) => { let (u, v) = inv.apply(p[0], p[1]); // The plane's (u, v) rectangle after the move. @@ -255,6 +746,7 @@ impl VpSession { { pl.corners = q; } + self.resolve(); } Some(Drag::Paste { offset }) => { let offset = *offset; @@ -303,10 +795,13 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> None => return Err("no active layer".into()), } let canvas = st.doc.bounds(); + let (base, doc_revision) = (st.doc.clone(), st.revision); let key = app.ui.alloc_id(); let clip = app.session.clipboard.as_ref().and_then(|c| { let r = c.surface.content_bounds(); (!r.is_empty()).then(|| Clip { + surface: c.surface.clone(), + rect: r, texture: ctx.load_texture(format!("vp-paste-{key}"), crate::distort_ui::surface_image(&c.surface, r, 1024), egui::TextureOptions::LINEAR), width: f64::from(r.width()), height: f64::from(r.height()), @@ -317,6 +812,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> layer, canvas, planes: Vec::new(), + torn: Vec::new(), tool: VpTool::CreatePlane, pending: Vec::new(), selected: None, @@ -327,14 +823,30 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> new_layer: false, clip, drag: None, - history: EditHistory::new(&(Vec::new(), [0.25, 0.25], 0.5)), + stamp: StampOptions { diameter: 40.0, hardness: 50.0, opacity: 100.0, aligned: true }, + source: None, + strokes: Vec::new(), + aligned_ref: None, + rev: 0, + base, + doc_revision, + preview: None, + history: EditHistory::new(&VpEdit { + planes: Vec::new(), + torn: Vec::new(), + paste_at: [0.25, 0.25], + paste_width: 0.5, + source: None, + strokes: Vec::new(), + aligned_ref: None, + }), }); app.ui.status = tl!("Vanishing Point: click four corners to create a plane").into(); Ok(()) } -/// OK: runs `filter.vanishingPoint` with the planes (and the paste). An invalid plane keeps the -/// mode open; with nothing to paste the mode just closes. +/// OK: runs `filter.vanishingPoint` with the planes (and the paste and the clone strokes). An +/// invalid plane keeps the mode open; with nothing to paste or clone the mode just closes. pub fn commit(app: &mut PhotocraftApp) -> Result { let Some(s) = app.distort.vanishing.as_ref() else { return Ok(Value::Null) }; let center = s.center(); @@ -343,12 +855,27 @@ pub fn commit(app: &mut PhotocraftApp) -> Result { app.ui.status = msg.into(); return Err(msg.into()); } - let params = s.params(); - app.distort.vanishing = None; - if params.get("paste").is_none() { + let mut params = s.params(); + // The layer the mode was opened on, when another one was picked meanwhile (the mode isn't + // modal). Left out otherwise, so a recorded action stays portable. + if let Some(st) = app.session.active() + && st.active_layer != Some(s.layer) + && st.doc.layer(s.layer).is_some() + { + params["layer"] = json!(s.layer.0); + } + let session = app.distort.vanishing.take(); + if params.get("paste").is_none() && params.get("clone").is_none() { return Ok(json!({"committed": false})); } - app.run(VP, params).map(|r| json!({"committed": true, "result": r})) + match app.run(VP, params) { + Ok(r) => Ok(json!({"committed": true, "result": r})), + Err(e) => { + // Keep the planes, source and strokes so the user can fix the cause and retry. + app.distort.vanishing = session; + Err(e) + } + } } /// Control channel: `filter.vanishingPoint {"ui": {...}}` while the mode is active. @@ -365,19 +892,39 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { s.tool = match t { "edit" | "editPlane" => VpTool::EditPlane, "create" | "createPlane" => VpTool::CreatePlane, - other => return Err(format!("tool: edit|create, not `{other}`")), + "stamp" => VpTool::Stamp, + other => return Err(format!("tool: edit|create|stamp, not `{other}`")), }; s.pending.clear(); } if let Some(p) = ui.get("planes") { - let planes: Vec = serde_json::from_value(p.clone()).map_err(|e| format!("bad planes: {e}"))?; - if planes.len() > MAX_PLANES { - return Err(format!("at most {MAX_PLANES} planes")); - } + let (planes, torn) = parse_planes(p)?; s.planes = planes; + s.torn = torn; // A drag holds indices into the old list. s.drag = None; s.selected = (!s.planes.is_empty()).then(|| s.planes.len() - 1); + s.resolve(); + } + if let Some(o) = ui.get("stamp") { + let num = |k: &str, lo: f64, hi: f64| o.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).map(|v| v.clamp(lo, hi)); + let st = &mut s.stamp; + st.diameter = num("diameter", 1.0, 2000.0).unwrap_or(st.diameter); + st.hardness = num("hardness", 0.0, 100.0).unwrap_or(st.hardness); + st.opacity = num("opacity", 0.0, 100.0).unwrap_or(st.opacity); + st.aligned = o.get("aligned").and_then(Value::as_bool).unwrap_or(st.aligned); + } + if let Some(src) = ui.get("source") { + s.source = match src { + Value::Null => None, + v => Some(pt(v).ok_or("source: [x, y]")?), + }; + s.aligned_ref = None; + } + if let Some(c) = ui.get("clone") { + s.strokes = photocraft_engine::vp_cmds::clone_specs(&json!({"clone": c})).map_err(|e| e.to_string())?; + s.drag = None; + s.rev += 1; } if let Some(i) = ui.get("select").and_then(Value::as_u64) { s.selected = usize::try_from(i).ok().filter(|i| *i < s.planes.len()); @@ -398,14 +945,92 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result { s.new_layer = b; } s.settle(false); - Ok(s.describe()) + sync_preview(app); + Ok(app.distort.vanishing.as_ref().map(VpSession::describe).unwrap_or(Value::Null)) } -pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) { +fn pt(v: &Value) -> Option<[f64; 2]> { + let p = [v.get(0)?.as_f64()?, v.get(1)?.as_f64()?]; + p.iter().all(|x| x.is_finite() && x.abs() < 1e7).then_some(p) +} + +/// The control channel's planes, in the command's form: `{"corners": [[x, y]×4]}` or +/// `{"from": earlier plane, "edge", "angle": 90, "depth": 1}`. +fn parse_planes(v: &Value) -> Result<(Vec, Vec>), String> { + let list = v.as_array().ok_or("planes: a list")?; + if list.len() > MAX_PLANES { + return Err(format!("at most {MAX_PLANES} planes")); + } + let (mut planes, mut torn) = (Vec::new(), Vec::new()); + for (i, p) in list.iter().enumerate() { + if let Some(c) = p.get("corners") { + let c = c.as_array().filter(|c| c.len() == 4).ok_or(format!("plane {i}: four corners"))?; + let corners = [0, 1, 2, 3].map(|k| c.get(k).and_then(pt)); + let [Some(a), Some(b), Some(c), Some(d)] = corners else { return Err(format!("plane {i}: corners are [x, y]")) }; + planes.push(VpPlane { corners: [a, b, c, d] }); + torn.push(None); + continue; + } + let from = p + .get("from") + .and_then(Value::as_u64) + .and_then(|f| usize::try_from(f).ok()) + .filter(|f| *f < i) + .ok_or(format!("plane {i}: `corners` or `from` (an earlier plane)"))?; + let edge = match p.get("edge").and_then(Value::as_str).unwrap_or("top") { + "top" => Edge::Top, + "right" => Edge::Right, + "bottom" => Edge::Bottom, + "left" => Edge::Left, + e => return Err(format!("plane {i}: unknown edge `{e}`")), + }; + let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(90.0); + let depth = p.get("depth").and_then(Value::as_f64).unwrap_or(1.0); + if !(0.0..=360.0).contains(&angle) || !(depth > 0.0 && depth <= 1000.0) { + return Err(format!("plane {i}: angle 0..360, depth above 0 and at most 1000")); + } + planes.push(VpPlane { corners: [[0.0; 2]; 4] }); + torn.push(Some(Torn { from, edge, angle, depth })); + } + Ok((planes, torn)) +} + +/// Brings the stamp preview up to date with the strokes (and repaints it after the planes +/// changed, once no plane is being dragged). +pub(crate) fn sync_preview(app: &mut PhotocraftApp) { + let Some(s) = app.distort.vanishing.as_mut() else { return }; + if let Some(st) = app.session.active() { + s.rebase(&st.doc, st.revision); + } + if matches!(s.drag, Some(Drag::Corner { .. } | Drag::Edge { .. } | Drag::Torn { .. } | Drag::Paste { .. })) { + return; + } + let ui = &mut app.ui; + s.paint_preview(|| ui.alloc_id()); +} + +/// What changed between stamp preview (or document) key `seen` and `now` of document `doc` at +/// `revision`: the areas the strokes painted. `None` when either key isn't the session's. +pub(crate) fn damage(app: &PhotocraftApp, doc: DocId, revision: u64, seen: u64, now: u64) -> Option { + let s = app.distort.vanishing.as_ref().filter(|s| s.base.id == doc && s.doc_revision == revision)?; + let keys = &s.preview.as_ref()?.keys; + let at = |k: u64| if k == 0 { Some(0) } else { keys.iter().position(|e| PREVIEW_KEY + e.0 == k).map(|i| i + 1) }; + let (a, b) = (at(seen)?, at(now)?); + if a == b { + return None; + } + Some(keys.get(a.min(b)..a.max(b))?.iter().fold(Rect::EMPTY, |r, k| union(r, k.1))) +} + +pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) { let tol = crate::distort_ui::tolerance(app); let Some(s) = app.distort.vanishing.as_mut() else { return }; match ev { - ToolEvent::Down { x, y, .. } => s.press([x, y], tol), + ToolEvent::Down { x, y, .. } => { + if let Some(msg) = s.press([x, y], tol, mods) { + app.ui.status = msg.into(); + } + } ToolEvent::Move { x, y, .. } => s.drag_to([x, y]), ToolEvent::Up { x, y } => { s.drag_to([x, y]); @@ -413,6 +1038,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, _mods: egui::Modifiers) { } } s.settle(false); + sync_preview(app); } /// Keys while the mode is active (↩ and Esc are handled by `distort_ui::keys`). @@ -428,10 +1054,14 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) { s.pending.clear(); } else if key(Key::C) { s.tool = VpTool::CreatePlane; + } else if key(Key::S) { + s.tool = VpTool::Stamp; + s.pending.clear(); } else if key(Key::Delete) || key(Key::Backspace) { s.delete_selected(); s.settle(false); } + sync_preview(app); } /// Esc: drops a half-clicked plane first, then leaves the mode. @@ -443,10 +1073,12 @@ pub fn escape(app: &mut PhotocraftApp) { } /// The paste on its plane: image content, drawn under the grid and guides like the document so a -/// guide stays visible across it (#7781). The planes and their grids are [`draw`]. +/// guide stays visible across it (#7781). The planes and their grids are [`draw`]. A current +/// stamp preview already shows the paste under its strokes. pub fn draw_content(s: &VpSession, painter: &egui::Painter, xf: &ViewXform) { let scr = |p: [f64; 2]| xf.to_screen(p[0] as f32, p[1] as f32); - if let Some(i) = s.paste_plane() + if s.paste_overlay() + && let Some(i) = s.paste_plane() && s.planes.get(i).is_some_and(|p| p.check(s.center()) != PlaneCheck::Invalid) && let (Some((h, lu, lv)), Some(c)) = (s.frame(i), s.clip.as_ref()) && let Some(ext) = s.paste_extent(lu, lv) @@ -506,6 +1138,50 @@ pub fn draw(s: &VpSession, painter: &egui::Painter, xf: &ViewXform) { painter.rect_filled(egui::Rect::from_center_size(*c, egui::vec2(6.0, 6.0)), 0.0, tokens.accent); } } + if s.tool == VpTool::Stamp { + draw_stamp(s, painter, xf, &scr); + } +} + +/// Stamp: the source as a crosshair and the brush under the pointer as the circle it paints on +/// the plane, foreshortened. +fn draw_stamp(s: &VpSession, painter: &egui::Painter, xf: &ViewXform, scr: &dyn Fn([f64; 2]) -> Pos2) { + let outline = |pts: &[Pos2]| { + painter.add(egui::Shape::closed_line(pts.to_vec(), Stroke::new(2.5, Color32::from_black_alpha(160)))); + painter.add(egui::Shape::closed_line(pts.to_vec(), Stroke::new(1.0, Color32::WHITE))); + }; + if let Some(src) = s.source { + let c = scr(src); + for (a, b) in [(egui::vec2(-7.0, 0.0), egui::vec2(7.0, 0.0)), (egui::vec2(0.0, -7.0), egui::vec2(0.0, 7.0))] { + painter.line_segment([c + a, c + b], Stroke::new(2.5, Color32::from_black_alpha(160))); + painter.line_segment([c + a, c + b], Stroke::new(1.0, Color32::WHITE)); + } + } + let Some(hover) = painter.ctx().pointer_hover_pos() else { return }; + let p = xf.to_doc(hover); + let Some(sc) = s.scene() else { return }; + let Some(i) = sc.plane_at(p) else { return }; + let Some((h, lu, lv)) = s.frame(i) else { return }; + let Some(inv) = h.inverse() else { return }; + let metric = |q: [f64; 2]| { + let (u, v) = inv.apply(q[0], q[1]); + [u * lu, v * lv] + }; + let (m, probe) = (metric(p), metric([p[0] + s.stamp.diameter / 2.0, p[1]])); + let r = (probe[0] - m[0]).hypot(probe[1] - m[1]); + if !r.is_finite() || r <= 0.0 { + return; + } + let ring: Vec = (0..48) + .map(|k| { + let a = f64::from(k) / 48.0 * std::f64::consts::TAU; + let (x, y) = h.apply((m[0] + r * a.cos()) / lu, (m[1] + r * a.sin()) / lv); + scr([x, y]) + }) + .collect(); + if ring.iter().all(|q| q.is_finite()) { + outline(&ring); + } } /// Plane coordinates (0..1, exclusive) of the grid lines across `u` (or `v`) for cells of @@ -552,6 +1228,8 @@ fn draw_paste(painter: &egui::Painter, scr: &dyn Fn([f64; 2]) -> Pos2, h: &Homog } pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { + // New Layer toggled last frame repaints the stamp preview. + sync_preview(app); let Some(s) = app.distort.vanishing.as_mut() else { return }; if crate::widgets::pill_tab(ui, tl!("Edit Plane"), s.tool == VpTool::EditPlane).on_hover_text("V").clicked() { s.tool = VpTool::EditPlane; @@ -560,7 +1238,27 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if crate::widgets::pill_tab(ui, tl!("Create Plane"), s.tool == VpTool::CreatePlane).on_hover_text("C").clicked() { s.tool = VpTool::CreatePlane; } + if crate::widgets::pill_tab(ui, tl!("Stamp"), s.tool == VpTool::Stamp).on_hover_text("S").clicked() { + s.tool = VpTool::Stamp; + s.pending.clear(); + } crate::widgets::vline(ui, 22.0); + if s.tool == VpTool::Stamp { + let st = &mut s.stamp; + for (label, value, range, unit) in [ + (tl!("Diameter:"), &mut st.diameter, 1.0..=2000.0, "px"), + (tl!("Hardness:"), &mut st.hardness, 0.0..=100.0, "%"), + (tl!("Opacity:"), &mut st.opacity, 0.0..=100.0, "%"), + ] { + ui.label(label); + let mut v = *value as f32; + if crate::widgets::value_field(ui, &mut v, range, unit, 56.0).changed() { + *value = f64::from(v); + } + } + crate::widgets::checkbox(ui, &mut st.aligned, tl!("Aligned")); + crate::widgets::vline(ui, 22.0); + } ui.label(tl!("Grid Size:")); let mut g = s.grid_size as f32; if crate::widgets::value_field(ui, &mut g, 2.0..=2000.0, "px", 56.0).changed() { @@ -576,6 +1274,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { s.paste_width = f64::from(w) / 100.0; } } + } + if s.clip.is_some() || !s.strokes.is_empty() || s.tool == VpTool::Stamp { crate::widgets::checkbox(ui, &mut s.new_layer, tl!("New Layer")); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -591,6 +1291,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if let Some(s) = app.distort.vanishing.as_mut() { s.settle(ui.input(|i| i.pointer.any_down())); } + // A paste Width or Paste change shows in this frame's canvas, the paste under the strokes. + sync_preview(app); } #[cfg(test)] @@ -648,4 +1350,365 @@ mod tests { assert!(l.rgba(x as i32, y as i32)[0] > 0.9, "{:?}", l.rgba(x as i32, y as i32)); assert!(l.rgba(230, 20)[0] < 0.5, "outside the plane"); } + + #[test] + fn ctrl_drag_tears_off_a_wall_and_the_stamp_clones_in_one_step() { + let (ctx, mut app) = app_with_layer(); + // A green mark near the floor's front edge to clone. + app.session.execute("select.rect", json!({"x": 100, "y": 135, "width": 40, "height": 8})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#00ff00"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + let ev = |app: &mut PhotocraftApp, e: ToolEvent, m: egui::Modifiers| crate::distort_ui::pointer(app, e, m); + let drag = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], m: egui::Modifiers| { + ev(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); + ev(app, ToolEvent::Move { x: (a[0] + b[0]) / 2.0, y: (a[1] + b[1]) / 2.0, pressure: 1.0 }, m); + ev(app, ToolEvent::Up { x: b[0], y: b[1] }, m); + }; + fn vp(app: &PhotocraftApp) -> &VpSession { + app.distort.vanishing.as_ref().unwrap() + } + + // Ctrl/Cmd-drag the top edge node up: a wall torn off the floor's far edge, 90° to it. + let top = vp(&app).edge_nodes(0).unwrap()[0]; + drag(&mut app, top, [top[0], top[1] - 35.0], egui::Modifiers::COMMAND); + let s = vp(&app); + assert_eq!(s.planes.len(), 2); + let t = s.torn[1].unwrap(); + assert_eq!((t.from, t.edge, t.angle), (0, Edge::Top, 90.0)); + let c = s.planes[1].corners; + assert!((c[0][1] + c[1][1]) / 2.0 < 40.0, "the far edge followed the pointer up: {c:?}"); + assert_ne!(s.describe()["planes"][1]["check"], "invalid"); + assert_eq!(s.params()["planes"][1], json!({"from": 0, "edge": "top", "angle": 90.0, "depth": t.depth})); + // Alt-dragging its far edge node turns it; editing the floor carries it along. + let far = s.edge_nodes(1).unwrap()[0]; + drag(&mut app, far, [far[0], far[1] + 12.0], egui::Modifiers::ALT); + assert_ne!(vp(&app).torn[1].unwrap().angle, 90.0); + let before = vp(&app).planes[1].corners; + drag(&mut app, [220.0, 150.0], [228.0, 150.0], egui::Modifiers::NONE); + assert_ne!(vp(&app).planes[1].corners, before); + assert!(vp(&app).torn[1].is_some()); + + // Stamp: painting needs a source first; Alt-click sets it on the floor's green mark. + control(&mut app, &json!({"tool": "stamp", "stamp": {"diameter": 12, "hardness": 80}})).unwrap(); + drag(&mut app, [120.0, 100.0], [120.0, 100.0], egui::Modifiers::NONE); + assert!(vp(&app).strokes.is_empty() && app.ui.status.contains("Alt-click"), "{}", app.ui.status); + drag(&mut app, [120.0, 139.0], [120.0, 139.0], egui::Modifiers::ALT); + assert_eq!(vp(&app).source, Some([120.0, 139.0])); + drag(&mut app, [118.0, 100.0], [126.0, 100.0], egui::Modifiers::NONE); + assert_eq!(vp(&app).strokes.len(), 1); + assert!(vp(&app).strokes[0].points.len() >= 3, "dabs along the drag"); + // The canvas shows the stroke; the document is untouched until OK. + let layer = app.session.active().unwrap().active_layer.unwrap(); + let green = |d: &Document| d.layer(layer).unwrap().surface().unwrap().rgba(122, 100)[1]; + let (shown, key) = crate::distort_ui::display_doc(&app, 0).expect("a stamp preview"); + assert!(green(&shown) > 0.8, "{}", green(&shown)); + let st = app.session.active().unwrap(); + assert!(green(&st.doc) < 0.6); + let area = damage(&app, st.doc.id, st.revision, 0, key).unwrap(); + assert!(area.contains(122, 100) && !area.contains(20, 20), "only the stroke recomposites: {area:?}"); + + let before = app.session.active().unwrap().history.past_len(); + let r = commit(&mut app).unwrap(); + assert_eq!(r["committed"], true, "{r}"); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), before + 1, "one history step for the whole session"); + assert!(green(&st.doc) > 0.8, "{}", green(&st.doc)); + } + + #[test] + fn undo_steps_back_through_clone_strokes_and_tear_offs() { + let (ctx, mut app) = app_with_layer(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + let drag = |app: &mut PhotocraftApp, a: [f64; 2], b: [f64; 2], m: egui::Modifiers| { + crate::distort_ui::pointer(app, ToolEvent::Down { x: a[0], y: a[1], pressure: 1.0 }, m); + crate::distort_ui::pointer(app, ToolEvent::Move { x: b[0], y: b[1], pressure: 1.0 }, m); + crate::distort_ui::pointer(app, ToolEvent::Up { x: b[0], y: b[1] }, m); + }; + let step = |app: &mut PhotocraftApp, st: Step| { + app.distort.vanishing.as_mut().unwrap().step(st); + sync_preview(app); + }; + let top = app.distort.vanishing.as_ref().unwrap().edge_nodes(0).unwrap()[0]; + drag(&mut app, top, [top[0], top[1] - 35.0], egui::Modifiers::COMMAND); + control(&mut app, &json!({"tool": "stamp", "source": [120, 139]})).unwrap(); + drag(&mut app, [118.0, 100.0], [126.0, 100.0], egui::Modifiers::NONE); + assert_eq!(app.distort.vanishing.as_ref().unwrap().strokes.len(), 1); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + + // ⌘Z takes the stroke back (and its preview), then the source, then the torn-off wall. + step(&mut app, Step::Undo); + assert!(app.distort.vanishing.as_ref().unwrap().strokes.is_empty()); + assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no stamp preview left"); + step(&mut app, Step::Undo); + assert_eq!(app.distort.vanishing.as_ref().unwrap().source, None); + step(&mut app, Step::Undo); + let s = app.distort.vanishing.as_ref().unwrap(); + assert_eq!((s.planes.len(), s.torn.len()), (1, 1)); + // ⇧⌘Z brings them back. + for _ in 0..3 { + step(&mut app, Step::Redo); + } + let s = app.distort.vanishing.as_ref().unwrap(); + assert_eq!((s.planes.len(), s.strokes.len()), (2, 1)); + assert!(s.torn[1].is_some()); + assert!(crate::distort_ui::display_doc(&app, 0).is_some(), "the stroke shows again"); + } + #[test] + fn overlapping_stamp_preview_matches_commit_across_batches() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + app.session + .edit("pattern", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + for x in 0..240 { + surf.fill_rect(Rect::new(x, 0, x + 1, 160), &[x as f32 / 240.0, (x % 7) as f32 / 6.0, 0.3, 1.0]); + } + Ok(()) + }) + .unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + let points = [[80.0, 80.0], [84.0, 80.0], [88.0, 80.0], [92.0, 80.0]]; + let s = app.distort.vanishing.as_mut().unwrap(); + s.new_layer = new_layer; + s.strokes.push(CloneSpec { source: [76.0, 80.0], points: points[..2].to_vec(), size: 12.0, hardness: 0.8, opacity: 1.0 }); + assert!(s.paint_preview(|| 1)); + s.strokes[0].points.extend_from_slice(&points[2..]); + assert!(s.paint_preview(|| 2)); + let (shown, _) = s.shown().unwrap(); + let expected = photocraft_compose::flatten(&shown).px; + assert_ne!(expected, photocraft_compose::flatten(&app.session.active().unwrap().doc).px); + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); + } + } + + /// A red square on the clipboard (copied from the layer's top-left corner). + fn copy_red_square(app: &mut PhotocraftApp) { + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("edit.copy", json!({})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + } + + #[test] + fn stamp_preview_paints_over_the_paste_like_ok() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": new_layer})).unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.paste && s.paste_plane() == Some(0), "the clipboard pastes by default"); + // The paste covers x 65..175 from y 45 down. One stroke clones it onto the base + // layer, the other paints across its right edge. + control( + &mut app, + &json!({"clone": [ + {"source": [100, 60], "points": [[40, 120], [48, 120], [56, 120]], "size": 16, "hardness": 80}, + {"source": [40, 130], "points": [[150, 60], [170, 60], [190, 60]], "size": 16, "hardness": 80}, + ]}), + ) + .unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.preview_has_paste(), "the preview shows the paste, so the overlay isn't drawn over the strokes"); + let (shown, _) = s.shown().unwrap(); + let expected = photocraft_compose::flatten(&shown).px; + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected, "newLayer={new_layer}"); + } + } + + #[test] + fn moving_the_paste_repaints_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); + let red = |app: &PhotocraftApp, x: i32, y: i32| { + let (shown, _) = app.distort.vanishing.as_ref().unwrap().shown().unwrap(); + let l = app.session.active().unwrap().active_layer.unwrap(); + shown.layer(l).unwrap().surface().unwrap().rgba(x, y)[0] + }; + assert!(red(&app, 100, 60) > 0.9); + control(&mut app, &json!({"pasteAt": [0.0, 0.5]})).unwrap(); + assert!(red(&app, 100, 60) < 0.5, "the paste left its old place"); + assert!(red(&app, 30, 100) > 0.9, "and shows at the new one"); + control(&mut app, &json!({"paste": false})).unwrap(); + assert!(red(&app, 30, 100) < 0.5, "paste off: gone from the preview"); + assert!(!app.distort.vanishing.as_ref().unwrap().preview_has_paste()); + } + + #[test] + fn dragging_the_paste_shows_it_once() { + let (ctx, mut app) = app_with_layer(); + copy_red_square(&mut app); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "tool": "edit"})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [200, 130], "points": [[30, 130]], "size": 8}]})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + let red = |app: &PhotocraftApp, x: i32, y: i32| { + let (shown, _) = crate::distort_ui::display_doc(app, 0)?; + Some(shown.layer(layer).unwrap().surface().unwrap().rgba(x, y)[0]) + }; + assert!(red(&app, 100, 60).unwrap() > 0.9, "the paste is in the preview"); + let ev = |app: &mut PhotocraftApp, e: ToolEvent| crate::distort_ui::pointer(app, e, egui::Modifiers::NONE); + ev(&mut app, ToolEvent::Down { x: 100.0, y: 60.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 60.0, y: 100.0, pressure: 1.0 }); + // Mid-drag: no copy left behind at the old place, only the overlay at the pointer. + assert!(red(&app, 100, 60).is_none_or(|r| r < 0.5), "{:?}", red(&app, 100, 60)); + assert!(app.distort.vanishing.as_ref().unwrap().paste_overlay(), "the overlay draws the moving paste"); + ev(&mut app, ToolEvent::Up { x: 60.0, y: 100.0 }); + assert!(red(&app, 100, 60).unwrap() < 0.5); + assert!(red(&app, 60, 100).unwrap() > 0.9, "released: the preview pastes at the new place"); + assert!(!app.distort.vanishing.as_ref().unwrap().paste_overlay()); + // A plane corner drag freezes the preview, paste included, until release: one copy. + ev(&mut app, ToolEvent::Down { x: 230.0, y: 150.0, pressure: 1.0 }); + ev(&mut app, ToolEvent::Move { x: 236.0, y: 156.0, pressure: 1.0 }); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(matches!(s.drag, Some(Drag::Corner { .. }))); + assert!(red(&app, 60, 100).unwrap() > 0.9 && !s.paste_overlay(), "frozen preview, no overlay on top"); + ev(&mut app, ToolEvent::Up { x: 236.0, y: 156.0 }); + let s = app.distort.vanishing.as_ref().unwrap(); + assert!(s.preview_has_paste() && !s.paste_overlay()); + } + + #[test] + fn new_layer_stamp_preview_stays_on_the_canvas() { + let (ctx, mut app) = app_with_layer(); + // A red stripe where the first dab samples, so cloning it changes pixels. + app.session.execute("select.rect", json!({"x": 130, "y": 70, "width": 20, "height": 20})).unwrap(); + app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session.execute("select.deselect", json!({})).unwrap(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}], "newLayer": true})).unwrap(); + // The second dab lies left of the canvas and samples the canvas 100 px to its right. + control(&mut app, &json!({"clone": [{"source": [140, 80], "points": [[40, 80], [-30, 80]], "size": 16}]})).unwrap(); + let s = app.distort.vanishing.as_ref().unwrap(); + let out = s.preview.as_ref().unwrap().out.content_bounds(); + assert!(!out.is_empty() && s.canvas.contains_rect(&out), "{out:?}"); + let st = app.session.active().unwrap(); + let area = damage(&app, st.doc.id, st.revision, 0, s.shown().unwrap().1).unwrap(); + assert!(s.canvas.contains_rect(&area), "{area:?}"); + } + + #[test] + fn deleting_the_last_plane_drops_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + crate::distort_ui::menu(&mut app, &ctx, VP, &json!({})).unwrap().unwrap(); + control(&mut app, &json!({"planes": [{"corners": [[70, 60], [170, 60], [220, 150], [20, 150]]}]})).unwrap(); + control(&mut app, &json!({"clone": [{"source": [120, 139], "points": [[118, 100], [126, 100]], "size": 12}]})).unwrap(); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + let s = app.distort.vanishing.as_mut().unwrap(); + s.selected = Some(0); + s.delete_selected(); + sync_preview(&mut app); + assert!(app.distort.vanishing.as_ref().unwrap().planes.is_empty()); + assert!(crate::distort_ui::display_doc(&app, 0).is_none(), "no strokes shown without a plane"); + } + + /// Opens the mode on the active layer of `app_with_layer` and stamps one stroke. + fn stamp_a_stroke(app: &mut PhotocraftApp, ctx: &egui::Context) { + crate::distort_ui::menu(app, ctx, VP, &json!({})).unwrap().unwrap(); + control(app, &json!({"planes": [{"corners": [[10, 10], [230, 10], [230, 150], [10, 150]]}]})).unwrap(); + control(app, &json!({"clone": [{"source": [60, 80], "points": [[120, 80], [126, 80]], "size": 12}]})).unwrap(); + } + + #[test] + fn stamp_preview_is_not_shown_on_another_document() { + let (ctx, mut app) = app_with_layer(); + stamp_a_stroke(&mut app, &ctx); + assert!(crate::distort_ui::display_doc(&app, 0).is_some()); + app.session.execute("file.new", json!({"width": 32, "height": 32, "depth": 8})).unwrap(); + let active = app.session.active_index().unwrap(); + // The session stays until drop_foreign; the preview must not follow this document (#5115). + assert!(app.distort.vanishing.is_some()); + assert!(crate::distort_ui::display_doc(&app, active).is_none()); + } + + #[test] + fn ok_paints_the_layer_the_mode_was_opened_on() { + for new_layer in [false, true] { + let (ctx, mut app) = app_with_layer(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session + .edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + stamp_a_stroke(&mut app, &ctx); + app.distort.vanishing.as_mut().unwrap().new_layer = new_layer; + sync_preview(&mut app); + // Another layer is picked while the mode is open (it isn't modal). + app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + let other = app.session.active().unwrap().active_layer.unwrap(); + sync_preview(&mut app); + let expected = photocraft_compose::flatten(&crate::distort_ui::display_doc(&app, 0).unwrap().0).px; + commit(&mut app).unwrap(); + let d = &app.session.active().unwrap().doc; + assert!(d.layer(other).unwrap().surface().unwrap().content_bounds().is_empty(), "newLayer={new_layer}"); + if !new_layer { + assert!(d.layer(layer).unwrap().surface().unwrap().rgba(120, 80)[0] > 0.9, "the stroke lands on the session's layer"); + // And it becomes active, so Fade and a colour-channel target follow it. + assert_eq!(app.session.active().unwrap().active_layer, Some(layer)); + } + assert_eq!(photocraft_compose::flatten(d).px, expected, "newLayer={new_layer}"); + } + } + + #[test] + fn an_edit_under_the_mode_shows_on_the_canvas() { + let (ctx, mut app) = app_with_layer(); + app.session + .edit("stripe", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(50, 70, 70, 90), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + stamp_a_stroke(&mut app, &ctx); + let before = crate::distort_ui::display_doc(&app, 0).unwrap(); + app.session + .edit("edit", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(200, 20, 220, 40), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + // Not the stale preview, even before the mode catches up. + assert!(crate::distort_ui::display_doc(&app, 0).is_none_or(|(d, _)| !Arc::ptr_eq(&d, &before.0))); + // The canvas catches up before it draws: the strokes over the edit, no frame without them. + let (shown, key) = crate::canvas::display_doc(&mut app, 0); + assert_ne!(key, before.1); + let st = app.session.active().unwrap(); + let layer = st.active_layer.unwrap(); + let px = shown.layer(layer).unwrap().surface().unwrap(); + assert!(px.rgba(210, 30)[1] > 0.9, "the edit shows: {:?}", px.rgba(210, 30)); + assert!(px.rgba(120, 80) != st.doc.layer(layer).unwrap().surface().unwrap().rgba(120, 80), "and so does the stroke"); + let expected = photocraft_compose::flatten(&shown).px; + commit(&mut app).unwrap(); + assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px, expected); + } + + #[test] + fn selecting_another_layer_keeps_the_stamp_preview() { + let (ctx, mut app) = app_with_layer(); + let layer = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({"name": "other"})).unwrap(); + app.session.execute("layer.select", json!({"layer": layer.0})).unwrap(); + app.sync_views(); + stamp_a_stroke(&mut app, &ctx); + let before = crate::canvas::display_doc(&mut app, 0); + let (doc, revision) = app.session.active().map(|st| (st.doc.clone(), st.revision)).unwrap(); + app.session.execute("layer.select", json!({"layer": "other"})).unwrap(); + let st = app.session.active().unwrap(); + assert!(st.revision != revision && Arc::ptr_eq(&st.doc, &doc), "a selection change leaves the pixels alone"); + // Same preview, same key: nothing to repaint or recomposite. + let after = crate::canvas::display_doc(&mut app, 0); + assert!(Arc::ptr_eq(&after.0, &before.0)); + assert_eq!(after.1, before.1); + } } diff --git a/docs/scorecard.md b/docs/scorecard.md index dfcd4a3c27..b82cda0566 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -167,7 +167,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu | TOOL-214-11 | Stroke Path dialog: pick any brush-based tool, Simulate Pressure | done | [#214](https://github.com/storytold/photocraft/issues/214) | path.stroke tool: Brush, Pencil, Eraser and every other brush-based tool (Background Eraser, Clone/Pattern Stamp, Healing/Spot Healing Brush, History Brush, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Mixer Brush: their paint.* command along the path, one step) plus simulatePressure (taper both ends); Stroke Path dialog from the Pen menu, the Paths panel menu and Alt-click on its Stroke button (#2978) | | TOOL-214-12 | Shapes: on-canvas corner radius handles, shape feather, selection to shape with tolerance | done | [#214](https://github.com/storytold/photocraft/issues/214) | On-canvas corner radius widgets on every selected live rectangle, triangle, polygon and star (LiveShape::Polygon corner_radius, shape.create/edit cornerRadius, vector shapes::round_corners) with Path Selection, the Rectangle/Triangle/Polygon tools and Move + Show Transform Controls: drag rounds every corner of every selected shape alike, Alt one corner of a rectangle, corner radius cursor and R: readout, one history step (corner_radius.rs, 2026-10-13); select.convertToShape with tolerance (vector_cmds.rs:1256); shape Density and Feather (Properties, layer.vectorMask.edit on a shape layer; the path as the fill's soft vector mask, Photoshop's 10 px feather ramp within 1 level; PSD mask parameters and .pcraft, #5846, 2026-10-15) | | TOOL-214-13 | Mask Properties: Density and Feather controls | done | [#214](https://github.com/storytold/photocraft/issues/214) | Properties panel shows Density (%) and Feather (px) sliders for a targeted pixel mask (layer.layerMask.edit) and a targeted vector mask (layer.vectorMask.edit), non-destructive and one undo step per drag, with Photoshop's Refine row (mask_props_ui.rs:34 pixel mask, :48 vector mask, :52 the sliders; mask_props_ui_tests.rs:39 pixel_mask_properties_follow_target_for_raster_and_adjustment_in_both_themes, :81 mask_slider_drags_preview_live_and_undo_as_separate_gestures, :147 vector_mask_properties_edit_density_and_feather) | -| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing | +| TOOL-214-14 | Vanishing Point window: draw and edit planes, paste, clone in perspective | partial | [#214](https://github.com/storytold/photocraft/issues/214) | filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing | | TOOL-214-15 | Content-Aware Fill workspace: paint the sampling area, preview, rotate/scale/mirror, new layer | partial | [#214](https://github.com/storytold/photocraft/issues/214) | Engine sampling auto, rect, custom (edit_menu_cmds.rs:324); generic dialog | | TOOL-214-16 | Liquify: redo (Cmd+Shift+Z) | done | [#214](https://github.com/storytold/photocraft/issues/214) | liquify_ui.rs supports bounded redo through Cmd+Shift+Z and the control channel; new strokes clear redo | | TOOL-213-17 | Red Eye tool: click a pupil to neutralize the red reflection | done | [#213](https://github.com/storytold/photocraft/issues/213) | paint.redEye (redeye_cmds.rs) + Tool::RedEye in the J flyout; Pupil Size and Darken Amount; catchlights kept; a miss is an error | diff --git a/scorecard/tools.toml b/scorecard/tools.toml index 668d94fd7a..9311cc1869 100644 --- a/scorecard/tools.toml +++ b/scorecard/tools.toml @@ -206,7 +206,7 @@ id = "TOOL-214-14" target = "Vanishing Point window: draw and edit planes, paste, clone in perspective" status = "partial" issue = 214 -note = "filter.vanishingPoint (vp_cmds.rs:15); on-canvas plane editor (vp_ui.rs: Create/Edit Plane, edge nodes, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane on OK); clone stamp, marquee and tear-off planes in the window still missing" +note = "filter.vanishingPoint (vp_cmds.rs:15); on-canvas window (vp_ui.rs: Create/Edit Plane, edge nodes, Ctrl/Cmd-drag tear-off planes with depth and Alt-drag angle, valid/doubtful/invalid grid colours, Grid Size, clipboard pasted onto the plane, Stamp tool cloning in perspective with live preview, all applied on OK as one step); the window's Marquee tool and the Stamp's Heal modes are still missing" [[item]] id = "TOOL-214-15"