PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Smart objects keep their four-corner (Distort / Perspective) placement (#426)
jason4short5856866f89a6
diff --git a/crates/algo/src/warp.rs b/crates/algo/src/warp.rsindex bcb86798b..d1c5f8454 100644--- a/crates/algo/src/warp.rs+++ b/crates/algo/src/warp.rs@@ -46,6 +46,19 @@ pub fn place_source(src: &Surface, src_rect: Rect, t: &photocraft_geom::Affine,crate::transform::warp_surface(src, src_rect, &crate::transform::Homography([a, c, e, b, d, f, 0.0, 0.0, 1.0]), Interp::Bicubic)}+/// [`place_source`] through a projective map `h` (source → document; Distort, Perspective): the+/// warp first (in source space), then `h`.+pub fn place_source_projective(src: &Surface, src_rect: Rect, h: &crate::transform::Homography, warp: Option<&photocraft_geom::warp::Warp>) -> Surface {+ if let Some(w) = warp.filter(|w| !w.is_identity()) {+ let map = |x: f64, y: f64| {+ let (u, v) = w.map(x, y);+ h.apply(u, v)+ };+ return warp_mesh_surface(src, src_rect, &map, Interp::Bicubic);+ }+ crate::transform::warp_surface(src, src_rect, h, Interp::Bicubic)+}+/// Warps the content of `src` inside `src_rect` through the forward map `f` (source document/// coordinates → destination document coordinates). Output has `src`'s format with alpha/// added; pixels outside the warped area are transparent.diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex b4a108129..2d3cbf656 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -354,12 +354,27 @@ pub struct SmartObject {/// Layer › Smart Objects › Stack Mode: when set, the source's top-level layers are combined/// per pixel with this statistic instead of composited.pub stack_mode: Option<StackMode>,+ /// Distort / Perspective (or an imported placement whose corners aren't a parallelogram): the+ /// full projective map from source pixels to document pixels, row-major 3×3. It overrides+ /// `transform`, which then holds its affine approximation at the source origin.+ pub perspective: Option<[f64; 9]>,}impl SmartObject {/// A smart object with no filters and no PSD data.pub fn new(source: SmartSource, transform: Affine, cache: Option<Surface>) -> Self {- Self { source, transform, smart_filters: Vec::new(), cache, psd_raw: None, filters_enabled: true, filter_mask: None, warp: None, stack_mode: None }+ Self {+ source,+ transform,+ smart_filters: Vec::new(),+ cache,+ psd_raw: None,+ filters_enabled: true,+ filter_mask: None,+ warp: None,+ stack_mode: None,+ perspective: None,+ }}}diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rsindex 349d4d383..d076dd664 100644--- a/crates/engine/src/canvas_geom.rs+++ b/crates/engine/src/canvas_geom.rs@@ -104,7 +104,7 @@ pub(crate) fn transform_layer_geometry(l: &mut Layer, a: &Affine, content: bool,t.transform = a.mul(&t.transform);retag_text(dpi, t);}- LayerContent::Smart(sm) if content => sm.transform = crate::smart_cmds::snap_affine(a.mul(&sm.transform)),+ LayerContent::Smart(sm) if content => crate::smart_cmds::transform_placement(sm, a),LayerContent::Group(g) => {if let Some(ab) = &mut g.artboard {ab.rect = map_rect(a, ab.rect);diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rsindex 28f7ef0e3..0f89ef85d 100644--- a/crates/engine/src/filters.rs+++ b/crates/engine/src/filters.rs@@ -581,6 +581,7 @@ mod tests {filter_mask: None,warp: None,stack_mode: None,+ perspective: None,}),);*active = Some(doc.insert_above(*active, l));diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rsindex bb2d6017d..fb76d25f2 100644--- a/crates/engine/src/smart_cmds.rs+++ b/crates/engine/src/smart_cmds.rs@@ -23,6 +23,7 @@use std::sync::{Arc, Mutex};use photocraft_algo::resample::translate_surface;+use photocraft_algo::transform::Homography;use photocraft_color::{BlendMode, PixelFormat};use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId, LayerMask, Metadata, SmartObject, SmartSource};use photocraft_geom::{Affine, Rect, Size};@@ -296,7 +297,10 @@ pub fn render(doc: &Document, sm: &SmartObject) -> Result<Option<Surface>> {None => source_image(&name, &bytes, doc.pixel_format())?,};// Through the warp (source space) and the transform in one pass; whole-pixel moves are exact.- let placed = photocraft_algo::warp::place_source(&img.surface, img.bounds, &sm.transform, sm.warp.as_ref());+ let placed = match &sm.perspective {+ Some(p) => photocraft_algo::warp::place_source_projective(&img.surface, img.bounds, &Homography(*p), sm.warp.as_ref()),+ None => photocraft_algo::warp::place_source(&img.surface, img.bounds, &sm.transform, sm.warp.as_ref()),+ };Ok(Some(apply_smart_filters(&placed, sm, doc.bounds())))}@@ -379,9 +383,45 @@ pub(crate) fn snap_affine(a: Affine) -> Affine {Affine { m: a.m.map(|v| if (v - v.round()).abs() < 1e-9 { v.round() } else { v }) }}+/// Where the smart object's source pixels land in the document: its projective map (Distort,+/// Perspective) or its affine transform.+pub fn placement(sm: &SmartObject) -> Homography {+ sm.perspective.map(Homography).unwrap_or_else(|| affine_homography(&sm.transform))+}++pub(crate) fn affine_homography(a: &Affine) -> Homography {+ let [a, b, c, d, e, f] = a.m;+ Homography([a, c, e, b, d, f, 0.0, 0.0, 1.0])+}++/// Sets where the source lands. An affine map is stored exactly in `transform` (no+/// `perspective`); a projective one in `perspective`, with `transform` its affine approximation at+/// the source origin (for code that only needs scale and position).+pub(crate) fn set_placement(sm: &mut SmartObject, h: Homography) {+ let m = h.0;+ let n = if m[8].abs() > 1e-12 { m.map(|v| v / m[8]) } else { m };+ if n[6].abs() < 1e-12 && n[7].abs() < 1e-12 {+ sm.transform = snap_affine(Affine { m: [n[0], n[3], n[1], n[4], n[2], n[5]] });+ sm.perspective = None;+ return;+ }+ let h = Homography(n);+ let (o, x, y) = (h.apply(0.0, 0.0), h.apply(1.0, 0.0), h.apply(0.0, 1.0));+ sm.transform = Affine { m: [x.0 - o.0, x.1 - o.1, y.0 - o.0, y.1 - o.1, o.0, o.1] };+ sm.perspective = Some(n);+}++/// Composes `a` (document → document) onto the smart object's placement.+pub(crate) fn transform_placement(sm: &mut SmartObject, a: &Affine) {+ match sm.perspective {+ None => sm.transform = snap_affine(a.mul(&sm.transform)),+ Some(_) => set_placement(sm, affine_homography(a).mul(&placement(sm))),+ }+}+/// Moves a smart object by whole pixels without re-rendering.pub(crate) fn shift_smart(sm: &mut SmartObject, dx: i32, dy: i32) {- sm.transform = Affine::translate(dx as f64, dy as f64).mul(&sm.transform);+ transform_placement(sm, &Affine::translate(dx as f64, dy as f64));if let Some(c) = &mut sm.cache {*c = crate::layer_multi_cmds::shift_surface(c, dx, dy);}diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rsindex d28a5c2d2..983ad6b81 100644--- a/crates/engine/src/smart_cmds/tests.rs+++ b/crates/engine/src/smart_cmds/tests.rs@@ -275,8 +275,9 @@ fn transforms_re_render_from_source_losslessly() {// Whole-pixel moves (Move tool) shift without re-rendering.smart.execute("layer.translate", json!({"dx": 3, "dy": -2})).unwrap();assert_eq!(active_smart(&smart).transform, Affine::translate(-3.0, 3.0));- // Perspective is refused (for now) rather than silently rasterizing.- assert!(smart.execute("edit.transform", json!({"layer": sid, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).is_err());+ // Perspective keeps the full projective placement (and stays a smart object).+ smart.execute("edit.transform", json!({"layer": sid, "quad": [[0, 0], [10, 0], [12, 10], [-2, 10]]})).unwrap();+ assert!(active_smart(&smart).perspective.is_some());}#[test]@@ -528,3 +529,63 @@ fn smart_filter_blur_repeats_the_canvas_edge_like_a_layer_filter() {assert!(max_diff(&a, &b) < 2.0 / 255.0, "smart re-render matches the layer filter ({depth}-bit)");}}++/// A distorted smart object keeps its fourth corner: through Edit Contents → Save (which+/// re-renders from the source) the placement and the rendered corners don't move.+#[test]+fn distort_survives_edit_contents() {+ let mut s = session(8);+ paint(&mut s);+ let id = convert(&mut s);+ let r = active_smart(&s).cache.unwrap().content_bounds();+ let (x0, y0, x1, y1) = (r.x0, r.y0, r.x1, r.y1);+ // Distort: only the bottom-right corner moves (in by 12, up by 8): not a parallelogram.+ let quad = json!([[x0, y0], [x1, y0], [x1 - 12, y1 - 8], [x0, y1]]);+ s.execute("edit.transform", json!({"layer": id, "rect": [x0, y0, x1, y1], "quad": quad})).unwrap();+ let placed = active_smart(&s);+ assert!(placed.perspective.is_some(), "Distort keeps a projective placement");+ let before = flat(&s);+ s.execute("layer.smartObjects.editContents", json!({})).unwrap();+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();+ s.set_active(0);+ assert_eq!(active_smart(&s).perspective, placed.perspective, "the placement survives the save");+ assert!(mean_diff(&before, &flat(&s)) < 0.01, "the re-render matches the distorted look");+ // The bottom-right of the original frame is now empty: the corner really moved in.+ let sm = active_smart(&s);+ let c = sm.cache.as_ref().unwrap();+ assert_eq!(c.rgba(x1 - 2, y1 - 2)[3], 0.0, "no pixels where the corner used to be");+}++/// Warp handles on a distorted smart object sit on its four distorted corners (the warp is mapped+/// through the full projective placement, not its affine approximation), and warping it keeps the+/// Distort placement.+#[test]+fn warp_on_a_distorted_smart_object_follows_the_corners() {+ let mut s = session(8);+ paint(&mut s);+ let id = convert(&mut s);+ let r = active_smart(&s).cache.unwrap().content_bounds();+ let (x0, y0, x1, y1) = (f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1));+ let quad = [[x0, y0], [x1, y0], [x1 - 12.0, y1 - 8.0], [x0, y1]];+ s.execute("edit.transform", json!({"layer": id, "rect": [x0, y0, x1, y1], "quad": quad})).unwrap();+ let mut sm = active_smart(&s);+ let h = placement(&sm);+ let inv = h.inverse().unwrap();+ let src: Vec<(f64, f64)> = quad.iter().map(|p| inv.apply(p[0], p[1])).collect();+ let b = src.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p.0), b[1].min(p.1), b[2].max(p.0), b[3].max(p.1)]);+ sm.warp = Some(photocraft_geom::warp::Warp::custom(photocraft_geom::warp::BezierMesh::identity(b, 1, 1), b));+ let layer = Layer::new("w", LayerContent::Smart(sm));+ let doc_warp = crate::warp_cmds::smart_warp_doc_space(&layer).unwrap();+ let pts = doc_warp.mesh.unwrap().points;+ for (q, i) in quad.iter().zip([0usize, 3, 15, 12]) {+ let p = pts[i];+ assert!((p[0] - q[0]).abs() < 1e-6 && (p[1] - q[1]).abs() < 1e-6, "corner {i}: {p:?} vs {q:?}");+ }+ // Warping the distorted smart object works and keeps its projective placement.+ let before = active_smart(&s).perspective;+ assert!(before.is_some());+ s.execute("edit.transform.warp", json!({"style": "arc", "bend": 30})).unwrap();+ let after = active_smart(&s);+ assert!(after.warp.is_some());+ assert_eq!(after.perspective, before);+}diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rsindex b73b68b96..60e9fd440 100644--- a/crates/engine/src/transform_cmds.rs+++ b/crates/engine/src/transform_cmds.rs@@ -193,11 +193,12 @@ pub(crate) fn transform_layer(doc_sel: Option<&Surface>, l: &mut Layer, h: &Homo}LayerContent::Smart(sm) => {// Smart objects keep the transform and re-render from their source afterwards- // (`refresh_text`), so repeated transforms don't degrade the pixels.- let Some(a) = affine else {- return Err(EngineError::Other("Distort and Perspective on smart objects aren't supported yet".into()));- };- sm.transform = crate::smart_cmds::snap_affine(a.mul(&sm.transform));+ // (`refresh_text`), so repeated transforms don't degrade the pixels. Distort and+ // Perspective keep the full projective map, so the fourth corner survives re-renders.+ match affine {+ Some(a) => crate::smart_cmds::transform_placement(sm, &a),+ None => crate::smart_cmds::set_placement(sm, h.mul(&crate::smart_cmds::placement(sm))),+ }// Fallback appearance for sources that can't be re-rendered.if let Some(c) = &mut sm.cache {let src = c.content_bounds();diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rsindex 2b1da8517..f2a1f5212 100644--- a/crates/engine/src/warp_cmds.rs+++ b/crates/engine/src/warp_cmds.rs@@ -8,10 +8,9 @@//! The split commands edit a mesh: either one passed in (`"warp"`, returned edited — what the//! Free Transform warp UI uses) or the active smart object's stored warp (a history step).-use photocraft_algo::transform::Interp;+use photocraft_algo::transform::{Homography, Interp};use photocraft_algo::warp::{warp_mesh_gray, warp_mesh_surface};use photocraft_doc::{Document, Layer, LayerContent, LayerId, Rect};-use photocraft_geom::Affine;use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};use photocraft_raster::Surface;use serde_json::{Value, json};@@ -39,9 +38,10 @@ fn rect_f(r: Rect) -> [f64; 4] {[f64::from(r.x0), f64::from(r.y0), f64::from(r.x1), f64::from(r.y1)]}-fn affine_apply(t: &Affine, p: [f64; 2]) -> [f64; 2] {- let [a, b, c, d, e, f] = t.m;- [a * p[0] + c * p[1] + e, b * p[0] + d * p[1] + f]+/// `p` through a projective map: a smart object's placement (affine, or Distort / Perspective).+fn hom_apply(h: &Homography, p: [f64; 2]) -> [f64; 2] {+ let (x, y) = h.apply(p[0], p[1]);+ [x, y]}/// The box a warp of `layer` starts from (Free Transform's frame).@@ -51,8 +51,8 @@ pub fn warp_bounds(doc: &Document, layer: &Layer) -> Rect {if let LayerContent::Smart(sm) = &layer.content&& let Some(w) = &sm.warp{- let t = sm.transform;- let c = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| affine_apply(&t, p));+ let t = crate::smart_cmds::placement(sm);+ let c = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| hom_apply(&t, p));let b = c.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);return Rect::new(b[0].round() as i32, b[1].round() as i32, b[2].round() as i32, b[3].round() as i32);}@@ -63,9 +63,9 @@ pub fn warp_bounds(doc: &Document, layer: &Layer) -> Rect {pub fn smart_warp_doc_space(layer: &Layer) -> Option<Warp> {let LayerContent::Smart(sm) = &layer.content else { return None };let w = sm.warp.as_ref()?;- let t = sm.transform;- let mesh = w.to_mesh(1, 1).map_points(|p| affine_apply(&t, p));- let corners = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| affine_apply(&t, p));+ let t = crate::smart_cmds::placement(sm);+ let mesh = w.to_mesh(1, 1).map_points(|p| hom_apply(&t, p));+ let corners = [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| hom_apply(&t, p));let b = corners.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);Some(Warp::custom(mesh, b))}@@ -129,15 +129,14 @@ fn warp_layer(doc_sel: Option<&Surface>, l: &mut Layer, w: &Warp, rect: Rect, inLayerContent::Text(_) => return Err(EngineError::Other("Warp needs rasterized type (or use Type › Warp Text)".into())),LayerContent::Shape(_) => return Err(EngineError::Other("Warp needs a rasterized shape (Layer › Rasterize › Shape)".into())),LayerContent::Smart(sm) => {- // Store in source space: undo the placement transform around the warp.- let t = sm.transform;- let inv = t.inverse().ok_or_else(|| EngineError::Other("the smart object's transform is degenerate".into()))?;+ // Store in source space: undo the placement (affine, or Distort / Perspective) around the warp.+ let inv = crate::smart_cmds::placement(sm).inverse().ok_or_else(|| EngineError::Other("the smart object's transform is degenerate".into()))?;let corners =- [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| affine_apply(&inv, p));+ [[w.bounds[0], w.bounds[1]], [w.bounds[2], w.bounds[1]], [w.bounds[2], w.bounds[3]], [w.bounds[0], w.bounds[3]]].map(|p| hom_apply(&inv, p));let sb = corners.iter().fold([f64::MAX, f64::MAX, f64::MIN, f64::MIN], |b, p| [b[0].min(p[0]), b[1].min(p[1]), b[2].max(p[0]), b[3].max(p[1])]);let src_warp = match w.style {WarpStyle::None => None,- WarpStyle::Custom => Some(Warp::custom(w.to_mesh(1, 1).map_points(|p| affine_apply(&inv, p)), sb)),+ WarpStyle::Custom => Some(Warp::custom(w.to_mesh(1, 1).map_points(|p| hom_apply(&inv, p)), sb)),_ => Some(Warp { bounds: sb, mesh: None, ..w.clone() }),};sm.warp = src_warp.filter(|w| !w.is_identity());@@ -293,12 +292,12 @@ fn split(s: &mut Session, p: &Value, cmd: &str, how: Split) -> Result<Value> {};let w = sm.warp.clone().unwrap_or_else(|| {let b = layer.surface().map_or(Rect::EMPTY, Surface::content_bounds);- let inv = sm.transform.inverse().unwrap_or(Affine::IDENTITY);- let c = [affine_apply(&inv, [f64::from(b.x0), f64::from(b.y0)]), affine_apply(&inv, [f64::from(b.x1), f64::from(b.y1)])];+ let inv = crate::smart_cmds::placement(sm).inverse().unwrap_or(Homography::IDENTITY);+ let c = [hom_apply(&inv, [f64::from(b.x0), f64::from(b.y0)]), hom_apply(&inv, [f64::from(b.x1), f64::from(b.y1)])];Warp::none([c[0][0].min(c[1][0]), c[0][1].min(c[1][1]), c[0][0].max(c[1][0]), c[0][1].max(c[1][1])])});- let t = sm.transform;- let at_src = at.and_then(|a| t.inverse().map(|inv| affine_apply(&inv, a)));+ let t = crate::smart_cmds::placement(sm);+ let at_src = at.and_then(|a| t.inverse().map(|inv| hom_apply(&inv, a)));let out = split_warp(&w, at_src, how).ok_or_else(|| bad(cmd, "nothing to split or remove there"))?;let label = if matches!(how, Split::Remove) { "Remove Warp Split" } else { "Split Warp" };s.edit(label, |doc, _| {diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rsindex 13dace95b..9bfeaa88a 100644--- a/crates/format/src/convert.rs+++ b/crates/format/src/convert.rs@@ -164,6 +164,7 @@ fn layer_m(l: &Layer, sink: &mut dyn Sink) -> LayerM {}),warp: s.warp.clone(),stack_mode: s.stack_mode,+ perspective: s.perspective,},};LayerM {@@ -422,7 +423,7 @@ impl Loader<'_> {cache: self.opt_surface(cache)?,psd_raw: self.opt_blob(psd_raw)?,}),- ContentM::Smart { source, transform, smart_filters, cache, psd_raw, filters_enabled, filter_mask, warp, stack_mode } => {+ ContentM::Smart { source, transform, smart_filters, cache, psd_raw, filters_enabled, filter_mask, warp, stack_mode, perspective } => {LayerContent::Smart(SmartObject {source: match source {SmartSourceM::Embedded { file_name, blob } => SmartSource::Embedded { file_name: file_name.clone(), bytes: self.fetch.blob(blob)? },@@ -445,6 +446,7 @@ impl Loader<'_> {},warp: warp.clone().filter(|w| w.mesh.as_ref().is_none_or(|m| m.is_valid())),stack_mode: *stack_mode,+ perspective: perspective.filter(|p| p.iter().all(|v| v.is_finite())),})}};diff --git a/crates/format/src/manifest.rs b/crates/format/src/manifest.rsindex 4206f2fdc..fc8cda544 100644--- a/crates/format/src/manifest.rs+++ b/crates/format/src/manifest.rs@@ -292,6 +292,9 @@ pub enum ContentM {warp: Option<photocraft_geom::warp::Warp>,#[serde(default)]stack_mode: Option<photocraft_doc::StackMode>,+ /// Distort / Perspective placement (row-major 3×3); absent for affine placements.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ perspective: Option<[f64; 9]>,},}diff --git a/crates/format/tests/common/mod.rs b/crates/format/tests/common/mod.rsindex 77c2273c4..59bb8f4b2 100644--- a/crates/format/tests/common/mod.rs+++ b/crates/format/tests/common/mod.rs@@ -187,6 +187,8 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {}),warp: Some(photocraft_geom::warp::Warp::custom(photocraft_geom::warp::BezierMesh::identity([0.0, 0.0, 48.0, 24.0], 2, 1), [0.0, 0.0, 48.0, 24.0])),stack_mode: Some(photocraft_doc::StackMode::Median),+ // Distort / Perspective placement, so the round trip covers it.+ perspective: Some([1.0, 0.1, 2.0, 0.05, 1.0, 3.0, 0.001, 0.0005, 1.0]),}),);let linked = Layer::new(@@ -201,6 +203,7 @@ pub fn rich_doc(mode: ColorMode, depth: SampleType) -> Document {filter_mask: None,warp: None,stack_mode: None,+ perspective: None,}),);d.layers.extend([paint, group, fill, grad, text, shape, smart, linked]);diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rsindex ffd15211d..cff39bb76 100644--- a/crates/io/src/blocks.rs+++ b/crates/io/src/blocks.rs@@ -531,6 +531,31 @@ pub fn parse_smart(key: &[u8; 4], data: &[u8]) -> (String, Affine) {(id, affine)}+/// The projective placement of a `SoLd` / `SoLE` block whose corners aren't a parallelogram+/// (Distort, Perspective): source pixels → document pixels, row-major 3×3. Read from+/// `nonAffineTransform` (the placed corners), else `Trnf`. `None` for affine placements, which+/// [`parse_smart`]'s affine holds exactly.+pub fn parse_smart_perspective(key: &[u8; 4], data: &[u8]) -> Option<[f64; 9]> {+ if key != b"SoLd" && key != b"SoLE" {+ return None;+ }+ let d = data.get(8..).and_then(parse_prefix_versioned)?;+ let sz = get_desc(&d, "Sz ")?;+ let (w, h) = (num(sz.get("Wdth"))?, num(sz.get("Hght"))?);+ let quad = |key: &str| -> Option<[[f64; 2]; 4]> {+ let Some(Value::List(pts)) = d.get(key) else { return None };+ let p: Vec<f64> = pts.iter().filter_map(|v| num(Some(v))).collect();+ (p.len() == 8 && p.iter().all(|v| v.is_finite())).then(|| [[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]])+ };+ let q = quad("nonAffineTransform").or_else(|| quad("Trnf"))?;+ // A parallelogram (top-left + bottom-right = top-right + bottom-left) is affine.+ let tol = 1e-6 * (1.0 + q.iter().flatten().fold(0.0f64, |m, v| m.max(v.abs())));+ if (0..2).all(|i| (q[0][i] + q[2][i] - q[1][i] - q[3][i]).abs() <= tol) || w <= 0.0 || h <= 0.0 {+ return None;+ }+ photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, w, h], q).map(|m| m.0)+}+/// `masterFXSwitch` from an `lfx2` block (defaults to `true`).pub fn effects_enabled(lfx2: &[u8]) -> bool {lfx2.get(4..)diff --git a/crates/io/src/psd_export.rs b/crates/io/src/psd_export.rsindex 4d7da4aba..6074a5f9e 100644--- a/crates/io/src/psd_export.rs+++ b/crates/io/src/psd_export.rs@@ -554,7 +554,16 @@ impl Ex {let size = if size.0 > 0.0 && size.1 > 0.0 { size } else { size_from_layer(sm) };let mut warnings = Vec::new();let fx = (!stack.filters.is_empty()).then(|| filter_fx(&stack, &l.name, &mut warnings));- let spec = PlacedSpec { idnt: &src.uuid, placed: &placed, transform: sm.transform, size, dpi: src.dpi, warp: sm.warp.as_ref(), filter_fx: fx };+ let spec = PlacedSpec {+ idnt: &src.uuid,+ placed: &placed,+ transform: sm.transform,+ perspective: sm.perspective,+ size,+ dpi: src.dpi,+ warp: sm.warp.as_ref(),+ filter_fx: fx,+ };let sold = sold_bytes(same_source.map(|t| &t.descriptor), &spec, &mut warnings);let plld = plld_bytes(&spec, &mut warnings);warnings.dedup();@@ -566,7 +575,12 @@ impl Ex {let bounds = sm.cache.as_ref().map_or(self.canvas, |c| c.content_bounds().union(&self.canvas));let item = match (sm.stack_mode, self.source_composite(&src.uuid)) {(None, Some((img, img_bounds))) => {- let unfiltered = photocraft_algo::warp::place_source(&img, img_bounds, &sm.transform, sm.warp.as_ref());+ let unfiltered = match &sm.perspective {+ Some(p) => {+ photocraft_algo::warp::place_source_projective(&img, img_bounds, &photocraft_algo::transform::Homography(*p), sm.warp.as_ref())+ }+ None => photocraft_algo::warp::place_source(&img, img_bounds, &sm.transform, sm.warp.as_ref()),+ };crate::smart_map::feid_item(&placed, &unfiltered, sm.filter_mask.as_ref(), bounds, self.fmt)}_ => None,diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rsindex fc5290a39..45ec96251 100644--- a/crates/io/src/psd_import.rs+++ b/crates/io/src/psd_import.rs@@ -299,6 +299,8 @@ impl Ctx<'_> {filter_mask,warp: rec.block(k).and_then(|b| blocks::parse_placed_warp(k, &b.data)),stack_mode: None,+ // Distort / Perspective: the fourth corner (the affine `transform` drops it).+ perspective: rec.block(k).and_then(|b| blocks::parse_smart_perspective(k, &b.data)),})} else if let Some(f) = soft_shape_fill(rec, vector_key.is_some(), fill_key) {// A shape whose vector mask has a density or feather is a fill layer seen through adiff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rsindex b88aa9404..b4ea8b72d 100644--- a/crates/io/src/smart_map.rs+++ b/crates/io/src/smart_map.rs@@ -487,6 +487,8 @@ pub struct PlacedSpec<'a> {pub placed: &'a str,/// Source pixels → document pixels.pub transform: Affine,+ /// Distort / Perspective: the full projective map (row-major 3×3), overriding `transform`.+ pub perspective: Option<[f64; 9]>,/// Source size in pixels.pub size: (f64, f64),/// Source resolution.@@ -496,17 +498,32 @@ pub struct PlacedSpec<'a> {pub filter_fx: Option<Descriptor>,}+/// Where the source corners land (top-left, top-right, bottom-right, bottom-left), as x, y pairs.+fn quad_points(s: &PlacedSpec<'_>) -> [f64; 8] {+ let (w, h) = s.size;+ let [a, b, c, d, e, f] = s.transform.m;+ let map = |x: f64, y: f64| match &s.perspective {+ Some(p) => photocraft_algo::transform::Homography(*p).apply(x, y),+ None => (a * x + c * y + e, b * x + d * y + f),+ };+ let mut out = [0.0; 8];+ for (i, (x, y)) in [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].into_iter().enumerate() {+ (out[2 * i], out[2 * i + 1]) = map(x, y);+ }+ out+}+/// The transform quad: the source corners (top-left, top-right, bottom-right, bottom-left).-fn quad(t: &Affine, (w, h): (f64, f64)) -> Value {- let pts = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)];- Value::List(- pts.iter()- .flat_map(|&(x, y)| {- let [a, b, c, d, e, f] = t.m;- [Value::Double(a * x + c * y + e), Value::Double(b * x + d * y + f)]- })- .collect(),- )+fn quad(s: &PlacedSpec<'_>) -> Value {+ Value::List(quad_points(s).into_iter().map(Value::Double).collect())+}++/// Has the placement moved from the quad a template descriptor stores (`Trnf`)?+fn quad_moved(template: &Descriptor, s: &PlacedSpec<'_>) -> bool {+ let Some(Value::List(pts)) = template.get("Trnf") else { return true };+ let old: Vec<f64> = pts.iter().filter_map(|v| crate::blocks::num(Some(v))).collect();+ let new = quad_points(s);+ old.len() != 8 || old.iter().zip(new).any(|(a, b)| (a - b).abs() > 1e-6 * (1.0 + a.abs()))}fn enumv(t: &str, v: &str) -> Value {@@ -573,10 +590,9 @@ pub fn sold_bytes(template: Option<&Descriptor>, s: &PlacedSpec<'_>, warnings: &let d = match template {Some(t) => {let mut d = t.clone();- let moved = parse_transform(t).is_none_or(|old| old != s.transform);- if moved {- set(&mut d, "Trnf", quad(&s.transform, s.size));- set(&mut d, "nonAffineTransform", quad(&s.transform, s.size));+ if quad_moved(t, s) {+ set(&mut d, "Trnf", quad(s));+ set(&mut d, "nonAffineTransform", quad(s));}set(&mut d, "warp", warp);match &s.filter_fx {@@ -597,8 +613,8 @@ pub fn sold_bytes(template: Option<&Descriptor>, s: &PlacedSpec<'_>, warnings: &.with("frameCount", Value::Integer(1)).with("Annt", Value::Integer(16)).with("Type", Value::Integer(2))- .with("Trnf", quad(&s.transform, s.size))- .with("nonAffineTransform", quad(&s.transform, s.size))+ .with("Trnf", quad(s))+ .with("nonAffineTransform", quad(s)).with("warp", warp).with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(s.size.0)).with("Hght", Value::Double(s.size.1)))).with("Rslt", unit(b"#Rsl", s.dpi));@@ -627,7 +643,7 @@ pub fn plld_bytes(s: &PlacedSpec<'_>, warnings: &mut Vec<String>) -> Vec<u8> {for v in [1i32, 1, 16, 2] {out.extend_from_slice(&v.to_be_bytes());}- if let Value::List(q) = quad(&s.transform, s.size) {+ if let Value::List(q) = quad(s) {for v in q {if let Value::Double(x) = v {out.extend_from_slice(&x.to_be_bytes());@@ -640,15 +656,6 @@ pub fn plld_bytes(s: &PlacedSpec<'_>, warnings: &mut Vec<String>) -> Vec<u8> {pad4(out)}-/// The transform a `soLD` descriptor stores (as [`crate::blocks::parse_smart`] reads it).-fn parse_transform(d: &Descriptor) -> Option<Affine> {- let Some(Value::List(pts)) = d.get("Trnf") else { return None };- let sz = get_desc(d, "Sz ")?;- let p: Vec<f64> = pts.iter().filter_map(|v| num(Some(v))).collect();- let (w, h) = (num(sz.get("Wdth"))?, num(sz.get("Hght"))?);- (p.len() == 8 && w > 0.0 && h > 0.0).then(|| Affine { m: [(p[2] - p[0]) / w, (p[3] - p[1]) / w, (p[6] - p[0]) / h, (p[7] - p[1]) / h, p[0], p[1]] })-}-/// The source size a `soLD` descriptor stores (`Sz `).pub fn stored_size(d: &Descriptor) -> Option<(f64, f64)> {let sz = get_desc(d, "Sz ")?;@@ -865,6 +872,7 @@ mod tests {idnt: "id-1",placed: "pl-2",transform: t,+ perspective: None,size: (64.0, 32.0),dpi: 72.0,warp: None,@@ -893,6 +901,54 @@ mod tests {assert_eq!(d.get("Trnf"), tmpl.get("Trnf"));}+ /// A Distort / Perspective placement goes out as its four corners (`Trnf`, `nonAffineTransform`)+ /// and comes back as the same projective map; an affine one reads back as no perspective.+ #[test]+ fn perspective_placement_round_trips_through_sold() {+ let h = photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 64.0, 32.0], [[10.0, 5.0], [80.0, 8.0], [70.0, 50.0], [12.0, 40.0]]).unwrap();+ let mut w = Vec::new();+ let mut spec = PlacedSpec {+ idnt: "id",+ placed: "pl",+ transform: Affine::IDENTITY,+ perspective: Some(h.0),+ size: (64.0, 32.0),+ dpi: 72.0,+ warp: None,+ filter_fx: None,+ };+ let sold = sold_bytes(None, &spec, &mut w);+ let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("a projective placement");+ let n = |m: [f64; 9]| m.map(|v| v / m[8]);+ for (a, b) in n(back).iter().zip(n(h.0)) {+ assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{back:?} vs {:?}", h.0);+ }+ // Affine placements carry no perspective.+ spec.perspective = None;+ spec.transform = Affine { m: [2.0, 0.0, 0.0, 2.0, 5.0, 7.0] };+ let sold = sold_bytes(None, &spec, &mut w);+ assert_eq!(crate::blocks::parse_smart_perspective(b"SoLd", &sold), None);+ assert_eq!(crate::blocks::parse_smart_perspective(b"PlLd", &sold), None);+ }++ /// `quad_moved` compares the corners a template stores with the placement's: unchanged keeps+ /// the template's quad, a moved corner (affine or projective) or a missing quad rewrites it.+ #[test]+ fn quad_moved_detects_corner_changes() {+ let t = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.0, 4.0] };+ let mut w = Vec::new();+ let mut spec = PlacedSpec { idnt: "id", placed: "pl", transform: t, perspective: None, size: (20.0, 10.0), dpi: 72.0, warp: None, filter_fx: None };+ let template = parse_sold(&sold_bytes(None, &spec, &mut w)).expect("parses").descriptor;+ assert!(!quad_moved(&template, &spec), "same placement");+ spec.transform = Affine { m: [1.0, 0.0, 0.0, 1.0, 3.5, 4.0] };+ assert!(quad_moved(&template, &spec), "moved half a pixel");+ spec.transform = t;+ spec.perspective =+ photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, 20.0, 10.0], [[3.0, 4.0], [23.0, 4.0], [20.0, 12.0], [3.0, 14.0]]).map(|h| h.0);+ assert!(quad_moved(&template, &spec), "one corner moved (Distort)");+ assert!(quad_moved(&Descriptor::new("null"), &spec), "no stored quad");+ }+/// Corrupted placed-layer data and filter descriptors never panic: they parse to something/// (unknown filters stay verbatim) or to nothing.#[test]@@ -910,6 +966,7 @@ mod tests {idnt: "id",placed: "pl",transform: Affine::IDENTITY,+ perspective: None,size: (8.0, 8.0),dpi: 72.0,warp: None,@@ -953,7 +1010,16 @@ mod tests {c.mesh = Some(custom);for (w, back) in [(Some(arc.clone()), Some(arc)), (Some(c.clone()), Some(c)), (Some(multi), None), (None, None)] {let mut warnings = Vec::new();- let spec = PlacedSpec { idnt: "i", placed: "p", transform: Affine::IDENTITY, size: (60.0, 30.0), dpi: 72.0, warp: w.as_ref(), filter_fx: None };+ let spec = PlacedSpec {+ idnt: "i",+ placed: "p",+ transform: Affine::IDENTITY,+ perspective: None,+ size: (60.0, 30.0),+ dpi: 72.0,+ warp: w.as_ref(),+ filter_fx: None,+ };let sold = sold_bytes(None, &spec, &mut warnings);assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), back);assert_eq!(warnings.len(), usize::from(w.is_some() && back.is_none()));diff --git a/crates/io/tests/roundtrip.rs b/crates/io/tests/roundtrip.rsindex 81e00e4f2..2bd9bb67e 100644--- a/crates/io/tests/roundtrip.rs+++ b/crates/io/tests/roundtrip.rs@@ -124,6 +124,7 @@ fn text_shape_smart_raw_blocks_survive() {filter_mask: None,warp: None,stack_mode: None,+ perspective: None,}),);smart.psd_blocks = vec![(*b"PlLd", Arc::new(vec![0; 4])), (*b"vmsk", Arc::new(vec![5; 8])), (*b"luni", Arc::new(vec![0; 8]))];