Skip to content

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

PSD: read and write Photoshop's Cylinder warp on placed layers (#4112)

Claudea4531d3122d0
diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs
index 87fda102f..a54e07fee 100644
--- a/crates/io/src/blocks.rs
+++ b/crates/io/src/blocks.rs
@@ -526,7 +526,8 @@ pub(crate) fn with_pattern_placement(mut d: Descriptor, angle: f32, link: bool,
}
/// The warp of a placed layer (`SoLd`/`SoLE` `warp` descriptor): style, bend, distortions,
-/// axis, bounds and, for `warpCustom`, the 4 × 4 `customEnvelopeWarp` mesh. Read-only: the raw
+/// axis, bounds and, for `warpCustom`, the 4 × 4 `customEnvelopeWarp` mesh, for `warpCylinder`
+/// its seven `warpValues`. Read-only: the raw
/// block is what gets written back. `None` when absent or `warpNone` with no mesh. A `PlLd`
/// record keeps its warp elsewhere: see [`parse_plld_warp`].
pub fn parse_placed_warp(key: &[u8; 4], data: &[u8]) -> Option<photocraft_geom::warp::Warp> {
@@ -539,7 +540,8 @@ pub fn parse_placed_warp(key: &[u8; 4], data: &[u8]) -> Option<photocraft_geom::
/// A `warp` descriptor (the `SoLd` key, or the whole descriptor after a `PlLd` record's corners)
/// as a warp: `Some(None)` for no warp (`warpNone`, or a warp that moves nothing), `None` when it
-/// can't be read (an unknown style, missing bounds, a mesh that isn't 4 × 4).
+/// can't be read (an unknown style, missing bounds, a mesh that isn't 4 × 4, a cylinder that
+/// isn't a horizontal one without perspective, the only kind measured).
fn warp_of(w: &Descriptor) -> Option<Option<photocraft_geom::warp::Warp>> {
use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};
let style = enum_of(w, "warpStyle").and_then(|v| WarpStyle::parse(&String::from_utf8_lossy(v)))?;
@@ -553,6 +555,17 @@ fn warp_of(w: &Descriptor) -> Option<Option<photocraft_geom::warp::Warp>> {
warp.h_distort = num(w.get("warpPerspective")).unwrap_or(0.0);
warp.v_distort = num(w.get("warpPerspectiveOther")).unwrap_or(0.0);
warp.vertical = enum_of(w, "warpRotate") == Some(b"Vrtc");
+ if style == WarpStyle::Cylinder {
+ if warp.vertical || warp.h_distort != 0.0 || warp.v_distort != 0.0 {
+ return None;
+ }
+ let values: Vec<f64> = match w.get("warpValues")? {
+ Value::List(l) => l.iter().map(|v| num(Some(v))).collect::<Option<_>>()?,
+ Value::UnitFloats { values, .. } => values.clone(),
+ _ => return None,
+ };
+ return Some(Some(Warp::cylinder(&values, bounds)?));
+ }
if style == WarpStyle::Custom {
let env = get_desc(w, "customEnvelopeWarp")?;
let Some(Value::ObjectArray(arr)) = env.get("meshPoints") else { return None };
@@ -593,12 +606,17 @@ pub(crate) fn parse_prefix_versioned(data: &[u8]) -> Option<Descriptor> {
}
/// The source-space box Photoshop maps onto a placed layer's `Trnf` quad: the bounding box of a
-/// single-patch custom warp's 16 control points, which may spill past the source, else the source
-/// rect `0..w × 0..h`. Mapping the source rect instead counts the overhang twice and stretches the
-/// placement. A degenerate or non-finite box falls back to the source rect.
+/// single-patch custom warp's 16 control points or of a cylinder's mesh (#4112), which may spill
+/// past the source, else the source rect `0..w × 0..h`. Mapping the source rect instead counts the
+/// overhang twice and stretches the placement. A degenerate or non-finite box falls back to the
+/// source rect.
pub(crate) fn placed_frame(warp: Option<&photocraft_geom::warp::Warp>, w: f64, h: f64) -> [f64; 4] {
+ use photocraft_geom::warp::WarpStyle;
let rect = [0.0, 0.0, w, h];
- let Some(m) = warp.filter(|wp| wp.style == photocraft_geom::warp::WarpStyle::Custom).and_then(|wp| wp.mesh.as_ref()).filter(|m| m.points.len() == 16)
+ let Some(m) = warp
+ .and_then(|wp| wp.mesh.as_ref().map(|m| (wp.style, m)))
+ .filter(|(style, m)| (*style == WarpStyle::Custom && m.points.len() == 16) || *style == WarpStyle::Cylinder)
+ .map(|(_, m)| m)
else {
return rect;
};
@@ -608,6 +626,16 @@ pub(crate) fn placed_frame(warp: Option<&photocraft_geom::warp::Warp>, w: f64, h
if ok { b } else { rect }
}
+/// The source-space box a projective (Distort / Perspective) placement maps onto its corners: a
+/// cylinder's control-point box, as for an affine placement (#4112), else the source rect. A
+/// custom warp keeps the source rect here: there is no Photoshop reference for that combination.
+pub(crate) fn perspective_frame(warp: Option<&photocraft_geom::warp::Warp>, w: f64, h: f64) -> [f64; 4] {
+ match warp {
+ Some(wp) if wp.style == photocraft_geom::warp::WarpStyle::Cylinder => placed_frame(warp, w, h),
+ _ => [0.0, 0.0, w, h],
+ }
+}
+
/// Smart object identifier and transform from `SoLd`/`SoLE` (best effort). A `PlLd` block
/// stores no source size, so its transform needs the embedded file: see [`parse_plld`].
pub fn parse_smart(key: &[u8; 4], data: &[u8]) -> (String, Affine) {
@@ -647,15 +675,15 @@ pub fn corners_affine(p: &[f64; 8], frame: [f64; 4]) -> Option<Affine> {
/// for a source of `size` warped by `warp`: the inverse of [`crate::smart_map::plld_bytes`]'s
/// quad. As for `SoLd`'s `Trnf` (#3677), affine corners frame a single-patch custom warp's
/// control-point box (which may spill past the source), else the source rect; projective corners
-/// frame the source rect, as `parse_smart_perspective` reads them. `PlLd` stores no source size:
+/// frame [`perspective_frame`], as `parse_smart_perspective` reads them. `PlLd` stores no source size:
/// without the source file (`None`) the layer is taken as placed at 100 %, the edge lengths being
/// its size (a custom warp's box needs no size); position and rotation stay right, only Replace
/// Contents and re-renders depend on the scale. Import and export (which keeps an unedited record
/// verbatim) both place a `PlLd` layer with this.
pub fn plld_transform(p: &[f64; 8], size: Option<(f64, f64)>, warp: Option<&photocraft_geom::warp::Warp>) -> (Affine, Option<[f64; 9]>) {
let (w, h) = size.unwrap_or_else(|| ((p[2] - p[0]).hypot(p[3] - p[1]), (p[6] - p[0]).hypot(p[7] - p[1])));
- let perspective = corners_perspective([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], (w, h));
- let frame = if perspective.is_some() { [0.0, 0.0, w, h] } else { placed_frame(warp, w, h) };
+ let perspective = corners_perspective_in([[p[0], p[1]], [p[2], p[3]], [p[4], p[5]], [p[6], p[7]]], perspective_frame(warp, w, h));
+ let frame = if perspective.is_some() { perspective_frame(warp, w, h) } else { placed_frame(warp, w, h) };
(corners_affine(p, frame).unwrap_or(Affine::IDENTITY), perspective)
}
@@ -730,18 +758,26 @@ pub fn parse_smart_perspective(key: &[u8; 4], data: &[u8]) -> Option<[f64; 9]> {
(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"))?;
- corners_perspective(q, (w, h))
+ let warp = get_desc(&d, "warp").and_then(warp_of).flatten();
+ corners_perspective_in(q, perspective_frame(warp.as_ref(), w, h))
}
/// The projective placement of a `w` × `h` source onto corners `q` that aren't a parallelogram;
/// `None` for affine corners (see [`corners_affine`]) or an empty size.
pub fn corners_perspective(q: [[f64; 2]; 4], (w, h): (f64, f64)) -> Option<[f64; 9]> {
+ corners_perspective_in(q, [0.0, 0.0, w, h])
+}
+
+/// [`corners_perspective`] for the source-space box `frame` (left, top, right, bottom; see
+/// [`perspective_frame`]).
+pub(crate) fn corners_perspective_in(q: [[f64; 2]; 4], frame: [f64; 4]) -> Option<[f64; 9]> {
// 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 {
+ let ok = frame.iter().all(|v| v.is_finite()) && frame[2] > frame[0] && frame[3] > frame[1];
+ if (0..2).all(|i| (q[0][i] + q[2][i] - q[1][i] - q[3][i]).abs() <= tol) || !ok {
return None;
}
- photocraft_algo::transform::Homography::rect_to_quad([0.0, 0.0, w, h], q).map(|m| m.0)
+ photocraft_algo::transform::Homography::rect_to_quad(frame, q).map(|m| m.0)
}
/// `masterFXSwitch` from an `lfx2` block (defaults to `true`).
@@ -1239,6 +1275,121 @@ mod more_tests {
assert_eq!(placed_frame(None, 50.0, 25.0), [0.0, 0.0, 50.0, 25.0]);
}
+ /// A `SoLd` placed on `quad` (`Trnf` and `nonAffineTransform`) for a 1000 × 1000 source,
+ /// warped by `warp`.
+ fn sold_placed(quad: [f64; 8], warp: Descriptor) -> Vec<u8> {
+ let list = Value::List(quad.iter().map(|v| Value::Double(*v)).collect());
+ let d = Descriptor::new("null")
+ .with("Trnf", list.clone())
+ .with("nonAffineTransform", list)
+ .with("Sz ", Value::Descriptor(Descriptor::new("Pnt ").with("Wdth", Value::Double(1000.0)).with("Hght", Value::Double(1000.0))))
+ .with("warp", Value::Descriptor(warp));
+ let mut data = b"soLD".to_vec();
+ data.extend_from_slice(&4u32.to_be_bytes());
+ data.extend(VersionedDescriptor::new(d).to_bytes());
+ data
+ }
+
+ /// A `warpCylinder` descriptor as #4112 describes it: horizontal, no perspective, seven
+ /// `warpValues` in the space of `bounds`.
+ fn cylinder_desc(values: Value) -> Descriptor {
+ let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) };
+ let bounds = Descriptor::new("classFloatRect")
+ .with("Top ", Value::Double(0.0))
+ .with("Left", Value::Double(0.0))
+ .with("Btom", Value::Double(1000.0))
+ .with("Rght", Value::Double(1000.0));
+ Descriptor::new("warp")
+ .with("warpStyle", e("warpStyle", "warpCylinder"))
+ .with("warpValue", Value::Double(0.0))
+ .with("warpValues", values)
+ .with("warpPerspective", Value::Double(0.0))
+ .with("warpPerspectiveOther", Value::Double(0.0))
+ .with("warpRotate", e("Ornt", "Hrzn"))
+ .with("bounds", Value::Descriptor(bounds))
+ }
+
+ const CYL: [f64; 7] = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5];
+
+ fn doubles(v: &[f64]) -> Value {
+ Value::List(v.iter().map(|x| Value::Double(*x)).collect())
+ }
+
+ /// #4112: a `warpCylinder` placed layer comes in as the cylinder its seven values describe,
+ /// instead of no warp (which re-rendered the contents flat).
+ #[test]
+ fn placed_cylinder_warp_is_read() {
+ use photocraft_geom::warp::{Warp, WarpStyle};
+ let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0];
+ let want = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap();
+ let w = parse_placed_warp(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("a cylinder");
+ assert_eq!(w, want);
+ assert_eq!(w.style, WarpStyle::Cylinder);
+ // Values written as one unit-float list read the same.
+ let floats = Value::UnitFloats { unit: *b"#Pxl", values: CYL.to_vec() };
+ assert_eq!(parse_placed_warp(b"SoLE", &sold_placed(quad, cylinder_desc(floats))), Some(want));
+ }
+
+ /// Cylinders nobody has measured (vertical, with perspective) and broken values stay
+ /// unreadable, as every cylinder was before: the layer keeps the pixels Photoshop stored.
+ #[test]
+ fn placed_cylinder_warps_that_cant_be_read() {
+ let quad = [0.0, 0.0, 800.0, 0.0, 800.0, 800.0, 0.0, 800.0];
+ let read = |d: Descriptor| parse_placed_warp(b"SoLd", &sold_placed(quad, d));
+ let e = |t: &str, v: &str| Value::Enumerated { type_id: Id::new(t), value: Id::new(v) };
+ let with = |key: &str, v: Value| {
+ let mut d = cylinder_desc(doubles(&CYL));
+ d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|(_, old)| *old = v.clone());
+ d
+ };
+ assert!(read(with("warpRotate", e("Ornt", "Vrtc"))).is_none(), "vertical");
+ assert!(read(with("warpPerspective", Value::Double(20.0))).is_none(), "perspective");
+ assert!(read(with("warpPerspectiveOther", Value::Double(-5.0))).is_none(), "the other perspective");
+ assert!(read(cylinder_desc(doubles(&CYL[..6]))).is_none(), "six values");
+ assert!(read(cylinder_desc(Value::List(vec![Value::Text(UnicodeString::new_nul("x")); 7]))).is_none(), "not numbers");
+ assert!(read(cylinder_desc(Value::Double(1.0))).is_none(), "one number");
+ let mut flipped = CYL;
+ flipped.swap(0, 2);
+ assert!(read(cylinder_desc(doubles(&flipped))).is_none(), "silhouettes swapped");
+ let mut no_values = cylinder_desc(doubles(&CYL));
+ no_values.items.retain(|(k, _)| !k.is("warpValues"));
+ assert!(read(no_values).is_none(), "no warpValues");
+ }
+
+ /// Like a custom warp's (#3677), a cylinder's control-point box is what the placement quad
+ /// frames, for affine corners and for projective ones (`nonAffineTransform`).
+ #[test]
+ fn placed_cylinder_quad_frames_its_control_box() {
+ use photocraft_geom::warp::Warp;
+ let cb = Warp::cylinder(&CYL, [0.0, 0.0, 1000.0, 1000.0]).unwrap().mesh.unwrap().control_bounds();
+ // Affine: the box lands on the quad.
+ let quad = [10.0, 20.0, 410.0, 20.0, 410.0, 520.0, 10.0, 520.0];
+ let (_, a) = parse_smart(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL))));
+ let [m0, m1, m2, m3, m4, m5] = a.m;
+ let map = |x: f64, y: f64| (m0 * x + m2 * y + m4, m1 * x + m3 * y + m5);
+ for ((x, y), (qx, qy)) in
+ [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])))
+ {
+ let (px, py) = map(x, y);
+ assert!((px - qx).abs() < 1e-9 && (py - qy).abs() < 1e-9, "{x},{y} → {px},{py}, not {qx},{qy}");
+ }
+ assert!(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).is_none(), "affine");
+ // Projective: the same box lands on the four corners.
+ let quad = [10.0, 20.0, 410.0, 60.0, 400.0, 480.0, 30.0, 520.0];
+ let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, cylinder_desc(doubles(&CYL)))).expect("projective"));
+ for ((x, y), (qx, qy)) in
+ [(cb[0], cb[1]), (cb[2], cb[1]), (cb[2], cb[3]), (cb[0], cb[3])].into_iter().zip(quad.as_chunks::<2>().0.iter().map(|p| (p[0], p[1])))
+ {
+ let (px, py) = h.apply(x, y);
+ assert!((px - qx).abs() < 1e-6 && (py - qy).abs() < 1e-6, "{x},{y} → {px},{py}, not {qx},{qy}");
+ }
+ // Without a warp a projective quad still frames the source rect.
+ let none = Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpNone") });
+ let h = photocraft_algo::transform::Homography(parse_smart_perspective(b"SoLd", &sold_placed(quad, none)).expect("projective"));
+ let (px, py) = h.apply(1000.0, 1000.0);
+ assert!((px - 400.0).abs() < 1e-6 && (py - 480.0).abs() < 1e-6);
+ }
+
#[test]
fn effects_switch() {
let mut lfx = vec![0, 0, 0, 0];
diff --git a/crates/io/src/smart_map.rs b/crates/io/src/smart_map.rs
index 6eeda61a1..4f46a7bbd 100644
--- a/crates/io/src/smart_map.rs
+++ b/crates/io/src/smart_map.rs
@@ -692,7 +692,8 @@ pub struct PlacedSpec<'a> {
/// Where the frame corners land (top-left, top-right, bottom-right, bottom-left), as x, y pairs.
/// The frame is [`crate::blocks::placed_frame`] for an affine placement (the inverse of
-/// `parse_smart`), the source rect for a projective one (as `parse_smart_perspective` reads it).
+/// `parse_smart`), [`crate::blocks::perspective_frame`] for a projective one (as
+/// `parse_smart_perspective` reads it).
fn quad_points(s: &PlacedSpec<'_>) -> [f64; 8] {
let (w, h) = s.size;
let [a, b, c, d, e, f] = s.transform.m;
@@ -700,7 +701,7 @@ fn quad_points(s: &PlacedSpec<'_>) -> [f64; 8] {
Some(p) => photocraft_algo::transform::Homography(*p).apply(x, y),
None => (a * x + c * y + e, b * x + d * y + f),
};
- let [x0, y0, x1, y1] = if s.perspective.is_some() { [0.0, 0.0, w, h] } else { crate::blocks::placed_frame(s.warp, w, h) };
+ let [x0, y0, x1, y1] = if s.perspective.is_some() { crate::blocks::perspective_frame(s.warp, w, h) } else { crate::blocks::placed_frame(s.warp, w, h) };
let mut out = [0.0; 8];
for (i, (x, y)) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].into_iter().enumerate() {
(out[2 * i], out[2 * i + 1]) = map(x, y);
@@ -726,7 +727,7 @@ fn enumv(t: &str, v: &str) -> Value {
}
/// The `warp` descriptor (also the `PlLd` warp). Multi-patch meshes have no 1 × 1 envelope and
-/// are written as no warp, with a message.
+/// are written as no warp, with a message. A cylinder is written as its seven `warpValues`.
fn warp_desc(w: Option<&Warp>, size: (f64, f64), warnings: &mut Vec<String>) -> Value {
let none = Warp::none([0.0, 0.0, size.0, size.1]);
let mut w = w.unwrap_or(&none).clone();
@@ -745,9 +746,11 @@ fn warp_desc(w: Option<&Warp>, size: (f64, f64), warnings: &mut Vec<String>) ->
.with("Left", Value::Double(x0))
.with("Btom", Value::Double(y1))
.with("Rght", Value::Double(x1));
- let mut d = Descriptor::new("warp")
- .with("warpStyle", enumv("warpStyle", w.style.psd_name()))
- .with("warpValue", Value::Double(w.bend))
+ let mut d = Descriptor::new("warp").with("warpStyle", enumv("warpStyle", w.style.psd_name())).with("warpValue", Value::Double(w.bend));
+ if w.style == WarpStyle::Cylinder {
+ d = d.with("warpValues", Value::List(w.values.iter().copied().map(Value::Double).collect()));
+ }
+ let mut d = d
.with("warpPerspective", Value::Double(w.h_distort))
.with("warpPerspectiveOther", Value::Double(w.v_distort))
.with("warpRotate", enumv("Ornt", if w.vertical { "Vrtc" } else { "Hrzn" }))
@@ -1424,6 +1427,53 @@ mod tests {
assert!(!quad_moved(&p.descriptor, &spec));
}
+ /// #4112: a regenerated `SoLd` (after Replace Contents, a move…) writes a cylinder back as
+ /// `warpCylinder` and its seven values, not as no warp, and frames its control-point box with
+ /// the quad, affine or projective, so import places it where it was.
+ #[test]
+ fn cylinder_warp_round_trips_through_sold() {
+ let v = [100.0, 800.0, 900.0, 200.0, 0.3, 0.3, 0.5];
+ let warp = Warp::cylinder(&v, [0.0, 0.0, 1000.0, 1000.0]).unwrap();
+ let transform = Affine { m: [0.5, 0.0, 0.0, 0.5, 40.0, 30.0] };
+ let mut spec =
+ PlacedSpec { idnt: "i", placed: "p", transform, perspective: None, size: (1000.0, 1000.0), dpi: 72.0, warp: Some(&warp), filter_fx: None };
+ let mut warnings = Vec::new();
+ let sold = sold_bytes(None, &spec, &mut warnings);
+ assert!(warnings.is_empty(), "{warnings:?}");
+ let p = parse_sold(&sold).expect("parses");
+ let Some(Value::Descriptor(w)) = p.descriptor.get("warp") else { panic!("no warp") };
+ assert_eq!(crate::blocks::enum_of(w, "warpStyle"), Some(b"warpCylinder".as_slice()));
+ let Some(Value::List(values)) = w.get("warpValues") else { panic!("no warpValues") };
+ assert_eq!(values.iter().filter_map(|x| num(Some(x))).collect::<Vec<_>>(), v);
+ assert!(w.get("customEnvelopeWarp").is_none());
+ assert_eq!(crate::blocks::parse_placed_warp(b"SoLd", &sold), Some(warp.clone()));
+ for (a, b) in p.transform.m.iter().zip(transform.m) {
+ assert!((a - b).abs() < 1e-9, "{:?}", p.transform);
+ }
+ // The quad is the image of the control-point box, not of the source rect.
+ let cb = warp.mesh.as_ref().unwrap().control_bounds();
+ let Some(Value::List(q)) = p.descriptor.get("Trnf") else { panic!("no Trnf") };
+ let q: Vec<f64> = q.iter().filter_map(|x| num(Some(x))).collect();
+ let want = [cb[0], cb[1], cb[2], cb[1], cb[2], cb[3], cb[0], cb[3]].map(|c| 0.5 * c);
+ for (i, (a, b)) in q.iter().zip(want).enumerate() {
+ let shift = if i % 2 == 0 { 40.0 } else { 30.0 };
+ assert!((a - (b + shift)).abs() < 1e-9, "corner {i}: {q:?}");
+ }
+ assert!(!quad_moved(&p.descriptor, &spec));
+ // A projective placement comes back as the same map.
+ let h = photocraft_algo::transform::Homography::rect_to_quad(cb, [[10.0, 20.0], [410.0, 60.0], [400.0, 480.0], [30.0, 520.0]]).unwrap();
+ spec.perspective = Some(h.0);
+ let sold = sold_bytes(None, &spec, &mut warnings);
+ let back = crate::blocks::parse_smart_perspective(b"SoLd", &sold).expect("projective");
+ let n = |m: [f64; 9]| m.map(|x| x / 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);
+ }
+ let plld = plld_bytes(&spec, &mut warnings);
+ assert_eq!(crate::blocks::parse_plld_warp(&plld), crate::blocks::PlldWarp::Warp(warp));
+ assert!(warnings.is_empty(), "{warnings:?}");
+ }
+
#[test]
fn hex_and_uuid() {
assert_eq!(from_hex(&to_hex(&[0, 1, 0xab, 0xff])), Some(vec![0, 1, 0xab, 0xff]));
diff --git a/crates/io/tests/cylinder_warp.rs b/crates/io/tests/cylinder_warp.rs
new file mode 100644
index 000000000..be75e3150
--- /dev/null
+++ b/crates/io/tests/cylinder_warp.rs
@@ -0,0 +1,123 @@
+//! Smart objects warped with Photoshop's Cylinder (#4112) through PSD persistence and a re-render
+//! from their contents, as Replace Contents, Relink and Edit Contents do.
+
+use std::sync::Arc;
+
+use photocraft_color::{ColorMode, SampleType};
+use photocraft_doc::{Document, Layer, LayerContent, SmartObject, SmartSource};
+use photocraft_geom::warp::{Warp, WarpStyle};
+use photocraft_geom::{Affine, Rect, Size};
+use photocraft_io::{ExportOptions, export, import, smart_map};
+use photocraft_psd::PsdFile;
+use photocraft_raster::Surface;
+
+/// Silhouettes at x 10 and 90, edges at y 20 and 80, ellipses 0.3 deep, wrapped as little as
+/// Photoshop allows (a sixth of the contents on the back on each side).
+const VALUES: [f64; 7] = [10.0, 80.0, 90.0, 20.0, 0.3, 0.3, 0.0];
+
+/// A 100 × 100 source: a red band at the left and a blue band at the right (both on the back of
+/// the cylinder), green in between.
+fn contents() -> Surface {
+ let mut s = Surface::new(photocraft_color::PixelFormat::new(ColorMode::Rgb, SampleType::U8, true));
+ s.fill_rect(Rect::new(0, 0, 100, 100), &[0.0, 1.0, 0.0, 1.0]);
+ s.fill_rect(Rect::new(0, 0, 5, 100), &[1.0, 0.0, 0.0, 1.0]);
+ s.fill_rect(Rect::new(95, 0, 100, 100), &[0.0, 0.0, 1.0, 1.0]);
+ s
+}
+
+fn document(transform: Affine, perspective: Option<[f64; 9]>) -> (Document, Warp) {
+ let pixels = contents();
+ let mut source = Document::new("label", Size::new(100, 100), ColorMode::Rgb, SampleType::U8);
+ source.layers.push(Layer::new("art", LayerContent::Raster(pixels.clone())));
+ let bytes = photocraft_format::save_to_bytes(&source, &Default::default()).unwrap();
+ let warp = Warp::cylinder(&VALUES, [0.0, 0.0, 100.0, 100.0]).unwrap();
+ let mut sm = SmartObject::new(SmartSource::Embedded { file_name: "label.pcraft".into(), bytes: Arc::new(bytes) }, transform, None);
+ sm.warp = Some(warp.clone());
+ sm.perspective = perspective;
+ sm.cache = Some(render(&sm));
+ let mut doc = Document::new("jar", Size::new(160, 160), ColorMode::Rgb, SampleType::U8);
+ doc.layers.push(Layer::new("label", LayerContent::Smart(sm)));
+ (doc, warp)
+}
+
+/// The smart object drawn from its contents, as the engine re-renders it.
+fn render(sm: &SmartObject) -> Surface {
+ let src = contents();
+ match &sm.perspective {
+ Some(p) => {
+ photocraft_algo::warp::place_source_projective(&src, Rect::new(0, 0, 100, 100), &photocraft_algo::transform::Homography(*p), sm.warp.as_ref())
+ }
+ None => photocraft_algo::warp::place_source(&src, Rect::new(0, 0, 100, 100), &sm.transform, sm.warp.as_ref()),
+ }
+ .unwrap()
+}
+
+fn smart(doc: &Document) -> &SmartObject {
+ let LayerContent::Smart(sm) = &doc.layers[0].content else { panic!("not a smart object") };
+ sm
+}
+
+fn round_trip(doc: &Document) -> (PsdFile, Document) {
+ let out = export(doc, "psd", &ExportOptions::default()).unwrap();
+ assert!(!out.warnings.iter().any(|w| w.contains("warp") || w.contains("written as pixels")), "{:?}", out.warnings);
+ (PsdFile::from_bytes(&out.bytes).unwrap(), import("psd", &out.bytes).unwrap().document)
+}
+
+/// Opaque pixels of the render that are mostly `channel` (0 red, 1 green, 2 blue).
+fn count(s: &Surface, channel: usize) -> usize {
+ let r = s.content_bounds();
+ s.read_region(r).chunks_exact(4).filter(|p| p[3] > 0.5 && p[channel] > 0.5 && (0..3).all(|c| c == channel || p[c] < 0.5)).count()
+}
+
+/// Before #4112 a cylinder was read as no warp: re-rendering the contents drew them flat, the
+/// red and blue bands that wrap round the back included. Now the PSD keeps the cylinder and the
+/// re-render hides the back and centres the front between the silhouettes.
+#[test]
+fn a_cylinder_survives_psd_and_wraps_the_contents_again() {
+ let transform = Affine { m: [1.0, 0.0, 0.0, 1.0, 30.0, 20.0] };
+ let (doc, warp) = document(transform, None);
+ let (file, back) = round_trip(&doc);
+ let layer = file.layers().iter().find(|l| l.name() == "label").unwrap();
+ let sold = smart_map::parse_sold(&layer.block(b"SoLd").unwrap().data).unwrap();
+ let Some(photocraft_psd::descriptor::Value::Descriptor(w)) = sold.descriptor.get("warp") else { panic!("no warp") };
+ assert!(matches!(w.get("warpStyle"), Some(photocraft_psd::descriptor::Value::Enumerated { value, .. }) if value.as_bytes() == b"warpCylinder"));
+ let sm = smart(&back);
+ assert_eq!(sm.warp.as_ref().map(|w| w.style), Some(WarpStyle::Cylinder));
+ assert_eq!(sm.warp.as_ref(), Some(&warp));
+ for (a, b) in sm.transform.m.iter().zip(transform.m) {
+ assert!((a - b).abs() < 1e-9, "{:?}", sm.transform);
+ }
+ let out = render(sm);
+ assert_eq!((count(&out, 0), count(&out, 2)), (0, 0), "the bands on the back are hidden");
+ assert!(count(&out, 1) > 3000, "the front is drawn");
+ // Between the silhouettes (x 10 and 90, shifted by 30) and no further.
+ let b = out.content_bounds();
+ assert!(b.x0 >= 39 && b.x1 <= 121, "{b:?}");
+ // The middle of the contents is at the front, centred.
+ let mid = out.pixel(80, 60);
+ assert!(mid[1] > 0.9 && mid[3] > 0.9, "{mid:?}");
+ // Saved again unchanged, the block is written as it was read.
+ let (again, _) = round_trip(&back);
+ let layer2 = again.layers().iter().find(|l| l.name() == "label").unwrap();
+ assert_eq!(layer2.block(b"SoLd").unwrap().data, layer.block(b"SoLd").unwrap().data);
+}
+
+/// Mockups usually place the label in perspective (`nonAffineTransform`): that placement and
+/// the cylinder both come back.
+#[test]
+fn a_cylinder_in_perspective_survives_psd() {
+ let cb = Warp::cylinder(&VALUES, [0.0, 0.0, 100.0, 100.0]).unwrap().mesh.unwrap().control_bounds();
+ let h = photocraft_algo::transform::Homography::rect_to_quad(cb, [[20.0, 20.0], [140.0, 30.0], [135.0, 150.0], [25.0, 140.0]]).unwrap();
+ let (doc, warp) = document(Affine::IDENTITY, Some(h.0));
+ let (_, back) = round_trip(&doc);
+ let sm = smart(&back);
+ assert_eq!(sm.warp.as_ref(), Some(&warp));
+ let p = sm.perspective.expect("still projective");
+ let n = |m: [f64; 9]| m.map(|v| v / m[8]);
+ for (a, b) in n(p).iter().zip(n(h.0)) {
+ assert!((a - b).abs() < 1e-9 * (1.0 + b.abs()), "{p:?} vs {:?}", h.0);
+ }
+ let out = render(sm);
+ assert_eq!((count(&out, 0), count(&out, 2)), (0, 0));
+ assert!(count(&out, 1) > 3000);
+}