PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Free Transform: refuse a result the warp would clip, not only one too large (#7807)
Brian Torresc5ba77e5d986
diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rsindex 2a25a02d8..428ae3cd0 100644--- a/crates/algo/src/transform.rs+++ b/crates/algo/src/transform.rs@@ -254,6 +254,21 @@ pub fn warp_output_size(src_rect: Rect, h: &Homography) -> Option<(u64, u64)> {Some((((x1 - x0) as u64).saturating_add(2), ((y1 - y0) as u64).saturating_add(2)))}+/// The farthest from the origin (px) [`warp_surface`] places a pixel: each side of+/// [`warp_output_bounds`] is clamped to ±2²⁰.+pub const WARP_REACH: i32 = 1 << 20;++/// Would [`warp_surface`] clip the result of warping `src_rect` by `h`: does a warped corner land+/// past [`WARP_REACH`], whether the result is that large or only placed that far out? A caller+/// refuses such a warp rather than lose the pixels beyond it. Empty and singular inputs have no+/// output to clip.+pub fn warp_output_clipped(src_rect: Rect, h: &Homography) -> bool {+ let Some(corners) = warp_corners(src_rect, h) else { return false };+ let lim = f64::from(WARP_REACH);+ let within = |v: f64| v.is_finite() && v.floor() >= -lim && v.ceil() <= lim;+ !corners.iter().all(|&(x, y)| within(x) && within(y))+}+fn warp_corners(src_rect: Rect, h: &Homography) -> Option<[(f64, f64); 4]> {if src_rect.is_empty() || h.inverse().is_none() {return None;@@ -264,11 +279,13 @@ fn warp_corners(src_rect: Rect, h: &Homography) -> Option<[(f64, f64); 4]> {)}+/// The pixel rectangle over the warped `corners` plus a pixel for filter support, each side+/// clamped to [`WARP_REACH`]; `None` when a corner is not finite.fn corner_bounds(corners: &[(f64, f64); 4]) -> Option<Rect> {if !corners.iter().all(|c| c.0.is_finite() && c.1.is_finite()) {return None;}- let lim = (1 << 20) as f64;+ let lim = f64::from(WARP_REACH);let bx0 = corners.iter().map(|c| c.0).fold(f64::MAX, f64::min).floor().max(-lim) as i32 - 1;let by0 = corners.iter().map(|c| c.1).fold(f64::MAX, f64::min).floor().max(-lim) as i32 - 1;let bx1 = corners.iter().map(|c| c.0).fold(f64::MIN, f64::max).ceil().min(lim) as i32 + 1;@@ -547,6 +564,8 @@ mod tests {}}+ /// The unclipped size matches the clipped bounds where nothing is clipped, saturates when it+ /// can't be represented, and is `None` for empty or singular inputs.#[test]fn output_size_saturates_overflows_and_preserves_filter_support() {let src = Rect::new(0, 0, 24, 16);@@ -559,6 +578,20 @@ mod tests {assert_eq!(warp_output_size(src, &Homography([0.0; 9])), None);}+ /// [`warp_output_clipped`] says yes exactly when [`warp_output_bounds`] clamps a side (#7807).+ #[test]+ fn output_clipped_matches_the_clamped_bounds() {+ let src = Rect::new(0, 0, 24, 16);+ let at = |dx: f64| Homography([1.0, 0.0, dx, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);+ let edge = f64::from(WARP_REACH) - 24.0;+ assert!(!warp_output_clipped(src, &at(edge)), "the right edge lands on the reach");+ assert_eq!(warp_output_bounds(src, &at(edge)).map(|b| b.x1), Some(WARP_REACH + 1));+ assert!(warp_output_clipped(src, &at(edge + 1.0)), "one pixel past it");+ assert_eq!(warp_output_bounds(src, &at(edge + 1.0)).map(|b| b.x1), Some(WARP_REACH + 1), "clamped");+ assert!(warp_output_clipped(src, &at(-f64::from(WARP_REACH) - 1.0)));+ assert!(!warp_output_clipped(Rect::EMPTY, &at(1e12)), "nothing to clip");+ }+#[test]fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() {let mut s = Surface::new(PixelFormat::RGBA8);diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rsindex 7c724e154..2f914d99e 100644--- a/crates/engine/src/prefs.rs+++ b/crates/engine/src/prefs.rs@@ -564,6 +564,7 @@ impl Performance {}impl Default for Performance {+ /// What a new install starts with, [`DEFAULT_MEMORY_USAGE_MB`] of Memory Usage among it.fn default() -> Self {Self {memory_usage_mb: DEFAULT_MEMORY_USAGE_MB,diff --git a/crates/engine/src/select_extra_cmds.rs b/crates/engine/src/select_extra_cmds.rsindex 88ed55b59..85df00dba 100644--- a/crates/engine/src/select_extra_cmds.rs+++ b/crates/engine/src/select_extra_cmds.rs@@ -148,6 +148,8 @@ fn affine_params(p: &Value, r: [f64; 4]) -> Homography {t(px + dx, py + dy).mul(&rot).mul(&skew).mul(&scale).mul(&t(-px, -py))}+/// Select › Transform Selection: warps the selection outline by the params' matrix, quad or+/// scale/rotate/move, refused when the result would not fit the transform budget.fn transform_selection(s: &mut Session, p: &Value) -> Result<Value> {const CMD: &str = "select.transformSelection";let d = s.active().ok_or(EngineError::NoDocument)?;diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rsindex 27ffcec42..c4d1036cd 100644--- a/crates/engine/src/transform_cmds.rs+++ b/crates/engine/src/transform_cmds.rs@@ -1,6 +1,6 @@//! Edit › Free Transform / Transform: projective transforms of layers (and the selection).-use photocraft_algo::transform::{Homography, Interp, warp_output_size, warp_surface, warp_surface_with};+use photocraft_algo::transform::{Homography, Interp, WARP_REACH, warp_output_clipped, warp_output_size, warp_surface, warp_surface_with};use photocraft_color::PixelFormat;use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks};use photocraft_geom::{Affine, Rect};@@ -262,8 +262,9 @@ pub fn locked_for_transform(doc: &Document, id: LayerId) -> bool {/// Memory Usage, which [`Session::apply_prefs`] sets, rather than a fixed 2³⁰ px, so a stitched/// layer of a few gigapixels transforms on a machine that has the memory for it (#7807). Only the/// size of the result counts, not where it lands, so moving a layer far off the canvas stays-/// allowed. A scale past it is refused rather than clipped (#3773): the warp would otherwise fill-/// every tile of a result up to 2²¹ px on a side before anything could fail.+/// allowed as far as the warp reaches ([`WARP_REACH`]). A scale past it is refused rather than+/// clipped (#3773): the warp would otherwise fill every tile of a result up to 2²¹ px on a side+/// before anything could fail.static BUDGET: AtomicU64 = AtomicU64::new((crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20);/// Set the memory (bytes) one transform's result may take (see [`budget`]).@@ -290,8 +291,9 @@ fn active_budget() -> u64 {}/// Refuse a warp of the content inside `src` (pixels of `format`) by `h` whose result would take-/// more memory than the budget, before anything is built. `what` names the surface in the message,-/// which names Memory Usage rather than a shortage: nothing has been allocated yet.+/// more memory than the budget, or reach past where the warp places pixels (it would be clipped),+/// before anything is built. `what` names the surface in the message, which names the setting or+/// the reach rather than a shortage: nothing has been allocated yet.pub(crate) fn check_budget(src: Rect, h: &Homography, what: &str, format: PixelFormat) -> Result<()> {check_budget_with_limit(src, h, what, format, active_budget())}@@ -311,6 +313,11 @@ fn check_budget_with_limit(src: Rect, h: &Homography, what: &str, format: PixelFbudget >> 20)));}+ if warp_output_clipped(src, h) {+ return Err(EngineError::Other(format!(+ "too large to transform: the transformed {what} would reach past ±{WARP_REACH} px, the farthest a transform places pixels; the document was not changed"+ )));+ }Ok(())}@@ -763,6 +770,7 @@ mod tests {s}+ /// The content bounds of the active layer's pixels.fn active_bounds(s: &Session) -> Rect {let st = s.active().unwrap();st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds()@@ -774,6 +782,7 @@ mod tests {/// Memory Usage's default, in bytes.const DEFAULT_BUDGET: u64 = (crate::prefs::DEFAULT_MEMORY_USAGE_MB as u64) << 20;+ /// Scales of 10⁷ and past are refused by the real budget too, whatever the axis or sign.#[test]fn huge_transform_scales_exceed_the_production_budget_before_clipping() {let src = Rect::new(0, 0, 24, 16);@@ -785,13 +794,38 @@ mod tests {}}+ /// A 240000 px wide stretch, placed far from the canvas but within the warp's reach, fits.#[test]fn an_ordinary_transform_remains_within_the_production_budget() {let src = Rect::new(0, 0, 24, 16);- let h = Homography([10_000.0, 0.0, 900_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]);+ let h = Homography([10_000.0, 0.0, 800_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]);assert!(check_budget_with_limit(src, &h, "layer", PixelFormat::RGBA8, DEFAULT_BUDGET).is_ok());}+ /// The warp places pixels only within ±2²⁰ px ([`WARP_REACH`]): a result that fits Memory+ /// Usage but would reach past it, by its size or by where it lands, is refused, not clipped.+ #[test]+ fn a_result_past_the_warps_reach_is_refused_not_clipped() {+ let src = Rect::new(0, 0, 24, 16);+ let check = |h: [f64; 9]| check_budget_with_limit(src, &Homography(h), "layer", PixelFormat::RGBA8, DEFAULT_BUDGET);+ // 2000016 x 18 px, 138 MB of 8-bit RGBA: from x = 0 it would be cut at 2²⁰; centred it fits.+ let err = check([83_334.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).unwrap_err().to_string();+ assert!(err.contains("would reach past ±1048576 px") && err.ends_with("the document was not changed"), "{err}");+ assert!(check([83_334.0, 0.0, -1_000_000.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]).is_ok());+ // A small layer moved past the reach, either way on either axis.+ for (dx, dy) in [(1_100_000.0, 0.0), (-1_100_000.0, 0.0), (0.0, 1_100_000.0), (0.0, -1_100_000.0)] {+ assert!(check([1.0, 0.0, dx, 0.0, 1.0, dy, 0.0, 0.0, 1.0]).is_err(), "{dx}, {dy}");+ }+ // Through the command: nothing moves, nothing is lost.+ let mut s = session();+ let st = s.active().unwrap();+ let (before, steps) = (st.doc.clone(), st.history.past_len());+ let err = s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 2_000_000, 0]})).unwrap_err().to_string();+ assert!(err.contains("the transformed layer \"Layer 1\" would reach past ±1048576 px"), "{err}");+ let st = s.active().unwrap();+ assert!(st.doc == before && st.history.past_len() == steps, "the document is untouched");+ }+/// #7807: the stitched layer's 90 % and 15°, a 37708 x 35259 px result that the old 2³⁰ px limit/// refused, fits the default Memory Usage at 8 bits (5072 MB); at 16 bits it needs Memory Usage/// raised, and the message says so.@@ -884,6 +918,8 @@ mod tests {assert!(&l == st.doc.layer(group).unwrap(), "no child was transformed");}+ /// Only the result's size is priced: a small layer moved 900000 px away (within the warp's+ /// reach) and back keeps every pixel.#[test]fn moving_a_small_layer_far_off_the_canvas_is_within_budget() {let mut s = session();diff --git a/crates/engine/tests/transform_budget_unclamped.rs b/crates/engine/tests/transform_budget_unclamped.rsindex b03defd14..267667f33 100644--- a/crates/engine/tests/transform_budget_unclamped.rs+++ b/crates/engine/tests/transform_budget_unclamped.rs@@ -17,6 +17,8 @@ fn painted() -> Session {session}+/// `command` with `params` is refused as too large, and the document, its revision and History+/// are as they were.fn assert_refused_without_changes(session: &mut Session, command: &str, params: Value) {let state = session.active().unwrap();let (document, revision, history) = (state.doc.clone(), state.revision, state.history.past_len());@@ -38,6 +40,7 @@ fn extreme_layer_scales_are_refused_before_a_clipped_strip_is_warped() {}}+/// Transform Selection refuses the same extreme scales and keeps the selection.#[test]fn extreme_selection_scales_are_refused_without_losing_the_selection() {let mut session = painted();