Merge pull request #8392 from dotCooCoo/feat/distort-images

Free Transform: Perspective Distort and Free Distort put an image's corners on the handles
This commit is contained in:
BFlat
2026-11-20 02:02:42 +07:00
committed by GitHub
84 changed files with 2666 additions and 110 deletions
+21
View File
@@ -1002,6 +1002,27 @@ fn dcs_transparency_counts_a_transparent_dcs_image_over_another() {
assert!(marked(b), "the opaque image it overlaps");
}
/// Replace measures a DCS file's clipping group by its bounds, not by its plates' image, so a
/// distorted plate image does not stop an image replacing the group.
#[test]
fn replace_is_not_refused_for_a_dcs_group_whose_image_is_distorted() {
let dir = temp_dir("replace-distorted");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
let group = r["ids"][0].clone();
let image = image_of(&s, &group).id;
let b = s.doc().unwrap().doc.node(image).unwrap().geometric_bounds().unwrap();
let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1);
let corners = json!([[x0 + 4.0, y0], [x1 - 4.0, y0], [x1, y1], [x0, y1]]);
s.execute("object.distort", &json!({ "ids": [image.0], "corners": corners })).unwrap();
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
let png = crate::tests_links::png(2, 2, [0, 0, 255]);
let out = s.execute("file.place", &json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
assert!(out.is_ok(), "{out:?}");
}
#[test]
fn dcs_transparency_counts_characters_with_a_transparent_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
+75
View File
@@ -588,6 +588,81 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's");
}
/// Update Links gives a distorted image its file's new pixels between the same corners: its
/// Placement Options' fill and clip do not move or clip it. Its transform takes the new pixel size,
/// and Link Info measures its scale at its middle.
#[test]
fn update_links_keeps_a_distorted_images_corners() {
let dir = Folder::new("distorted-update");
let photo = dir.file("photo.png");
write(&photo, &png(20, 10, RED));
let mut s = session();
let id = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
let before = corners(&s);
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
// The far corner of the pixels as the transform alone places them.
let far = |s: &Session| {
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
};
let far_before = far(&s);
// Link Info measures the scale where the effective resolution is measured: at the middle.
let scale_matches_ppi = |s: &mut Session| {
let info = s.execute("links.info", &json!({"id": id.0})).unwrap();
for i in 0..2 {
let (scale, ppi, eff) = (info["scale"][i].as_f64().unwrap(), info["ppi"][i].as_f64().unwrap(), info["effectivePpi"][i].as_f64().unwrap());
assert!((scale - ppi / eff * 100.0).abs() < 1e-6, "{info}");
}
};
scale_matches_ppi(&mut s);
// A copy in a symbol, distorted the same way, shows the same file.
let copy = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [copy.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
let in_symbol = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
if let NodeKind::Image(im) = &n.kind {
out.push((n.is_distorted_image(), (im.width, im.height)));
}
});
out
};
let symbol_corners = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| out.extend(n.image_corners()));
out
};
assert_eq!(in_symbol(&s), [(true, (20, 10))]);
let symbol_before = symbol_corners(&s);
assert_eq!(symbol_before.len(), 1);
write(&photo, &png(60, 20, BLUE));
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"].as_array().unwrap().len(), 2, "{u}");
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
assert!(n.is_distorted_image());
assert_eq!(corners(&s), before);
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
assert_eq!((im.width, im.height), (60, 20));
// The transform takes the new pixel size, so a placement by the transform keeps the old size.
assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
let d = &s.doc().unwrap().doc;
assert!(!matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })), "not clipped");
let mut clipped = false;
d.symbols[0].art.walk(&mut |n| clipped |= matches!(n.kind, NodeKind::Group { clip: true, .. }));
assert!(!clipped, "the symbol's image is not clipped");
assert_eq!(in_symbol(&s), [(true, (60, 20))]);
assert_eq!(symbol_corners(&s), symbol_before, "the symbol's image keeps its corners");
scale_matches_ppi(&mut s);
}
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
/// masks too: those showing the same content as an image in the layers, and those no object in the
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,
+20
View File
@@ -1422,6 +1422,26 @@ fn theme_picker_marquee_takes_the_area_and_picks_add_up() {
assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]);
}
/// A distorted image is read where its pixels are drawn, between its corners.
#[test]
fn theme_picker_reads_a_distorted_image_where_it_is_drawn() {
let mut s = session();
let (id, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]);
let (x, y0, y1) = (b.x1 + 20.0, b.y0, b.y1);
run(&mut s, "select.set", json!({"ids": [id.0]}));
run(&mut s, "object.distort", json!({"corners": [[x + 40.0, y0], [x + 60.0, y0], [x + 100.0, y1], [x, y1]]}));
// The lower left of the trapezoid, outside the rectangle the image was placed in: red.
assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [x + 2.0, y1 - 4.0, x + 20.0, y1 - 1.0]}]})), ["rgb 255 0 0"]);
// Where the image was: nothing.
assert!(pick_theme(&mut s, json!({"picks": [{"rect": [b.x0 + 1.0, b.y0 + 1.0, b.x1 - 1.0, b.y1 - 1.0]}]})).is_empty());
// A marquee reaching past the horizon its sides meet at (a quarter of its height above its
// top) still reads every pixel it covers.
let h = y1 - y0;
let mut both = pick_theme(&mut s, json!({"picks": [{"rect": [x - 10.0, y0 - h, x + 110.0, y1 + 1.0]}]}));
both.sort();
assert_eq!(both, ["rgb 0 0 255", "rgb 255 0 0"]);
}
/// Pixels less than half opaque are left out, and so is an image whose pixels can't be read.
#[test]
fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() {
+400
View File
@@ -754,6 +754,406 @@ fn distort_perspective_midpoint_is_projective() {
assert!((c.y - 100.0 / 6.0).abs() < 1e-3, "{c:?}");
}
/// A 2 × 2 px image placed at (0, 0)–(100, 100), selected.
fn placed_image(s: &mut Session) -> NodeId {
s.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![]));
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "pic".into(),
width: 2,
height: 2,
xf: vectorcraft_geom::Affine::scale(50.0),
link: None,
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), 0, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?;
sel.set([id]);
Ok(id)
})
.unwrap()
}
fn corners(s: &Session, id: NodeId) -> [Point; 4] {
s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap()
}
fn assert_corners(got: [Point; 4], want: [(f64, f64); 4]) {
for (g, (x, y)) in got.iter().zip(want) {
assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?} against {want:?}");
}
}
/// Perspective Distort and Free Distort put an image's corners exactly on the handles, in one
/// undo step; the image is bounded and clicked by its corners, and a move takes them along.
#[test]
fn distort_puts_an_images_corners_on_the_handles() {
for want in [[(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)], [(10.0, 5.0), (90.0, 0.0), (120.0, 110.0), (0.0, 100.0)]] {
let mut s = session();
let img = placed_image(&mut s);
let undo = undo_len(&s);
let corners_json: Vec<[f64; 2]> = want.iter().map(|(x, y)| [*x, *y]).collect();
s.execute("object.distort", &json!({ "corners": corners_json })).unwrap();
assert_eq!(undo_len(&s), undo + 1);
assert_corners(corners(&s, img), want);
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
let b = bounds(&s, img);
let xs = want.map(|c| c.0);
let ys = want.map(|c| c.1);
let near = |a: f64, b: f64| (a - b).abs() < 1e-9;
assert!(near(b.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(b.x1, xs.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
assert!(near(b.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(b.y1, ys.iter().copied().fold(f64::MIN, f64::max)), "{b:?}");
s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap();
assert_corners(corners(&s, img), want.map(|(x, y)| (x + 10.0, y + 20.0)));
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
}
// Clicks: inside the trapezoid hits the image; inside its old square but outside the
// trapezoid does not.
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let doc = &s.doc().unwrap().doc;
let opt = vectorcraft_doc::hit::HitOptions::default();
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(50.0, 50.0), opt).map(|h| h.leaf), Some(img));
assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(5.0, 10.0), opt).map(|h| h.leaf), None);
}
/// Distorted together with a path, the image's corners and the path's anchors follow one warp.
#[test]
fn distort_moves_an_image_and_a_path_as_one() {
let mut s = session();
let img = placed_image(&mut s);
let path = rect(&mut s, 100.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [200, 100], [50, 100]]})).unwrap();
let d = &s.doc().unwrap().doc;
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
let q = corners(&s, img);
// The image's right edge and the path's left edge were one line, and stay one where the warp
// moves it.
assert!(q[2].distance(Point::new(100.0, 100.0)) > 1.0, "{q:?}");
for p in [q[1], q[2]] {
assert!(anchors.iter().any(|a| a.distance(p) < 1e-9), "{p:?} not in {anchors:?}");
}
}
/// Corners that would fold an image over are refused: nothing changes and no undo step is kept.
/// A distorted image keeps its distortion where commands that cannot keep it are asked to work.
#[test]
fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() {
let mut s = session();
let img = placed_image(&mut s);
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [0, 100], [100, 100]]})).unwrap_err().to_string();
assert!(e.contains("convex"), "{e}");
assert_eq!(undo_len(&s), undo);
assert_eq!(s.doc().unwrap().doc, before);
// Three corners on one line give no perspective map at all.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [100, 50], [0, 100]]})).unwrap_err().to_string();
assert!(e.contains("convex"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
// A convex shape too small for a perspective map: the corners could not reach the handles.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1e-7, 0], [8e-8, 1e-7], [0, 1e-7]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
// The same shape far from the origin: its distance from it does not hide the missed corner.
let x = 1_000_000.0;
let e = s.execute("object.distort", &json!({"corners": [[x, 0], [x + 1e-7, 0], [x + 8e-8, 1e-7], [x, 1e-7]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
// A long, thin shape with one side all but gone.
let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1_000_000, 0], [1_000_000, 1e-19], [0, 1]]})).unwrap_err().to_string();
assert!(e.contains("too close together"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
// A small shape near the edge of the canvas is still distorted.
let o = vectorcraft_doc::MAX_COORD - 2.0;
let far = [[o, o], [o + 1.0, o], [o + 0.2130712, o + 1.0], [o, o + 1.0]];
s.execute("object.distort", &json!({ "from": [0, 0, 100, 100], "corners": far })).unwrap();
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(undo_len(&s), undo);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
for (cmd, params) in [
("object.cropImage", json!({})),
("imageTrace.make", json!({})),
("links.relink", json!({"path": "/nowhere/pic.png"})),
// Refused before the folder is searched, so a file missing there does not hide it.
("links.relink", json!({"folder": "/nowhere"})),
("links.embed", json!({"ids": [img.0]})),
("links.unembed", json!({})),
// Refused before any file is written.
("links.unembed", json!({"folder": "/nowhere"})),
("object.createObjectMosaic", json!({})),
("object.mesh.create", json!({})),
(
"file.place",
json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}),
),
] {
let e = s.execute(cmd, &params).unwrap_err().to_string();
// Every command gives the one shared refusal, which the complete-message catalogs translate.
assert!(e.contains("is an image changed by Perspective Distort or Free Distort, which this command does not work on"), "{cmd}: {e}");
}
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
assert_eq!(undo_len(&s), undo + 1);
// Type replaces a distorted image by its bounds, which the corners give: not refused.
let text = json!({"replace": true, "name": "note.txt", "dataBase64": vectorcraft_format::base64_encode(b"Hello")});
let out = s.execute("file.place", &text).unwrap();
let id = NodeId(out["ids"][0].as_u64().unwrap());
assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Text(_)));
}
/// Create Gradient Mesh on a path and a distorted image converts the path and names the image it
/// left as it is, with the shared refusal.
#[test]
fn mesh_create_reports_the_distorted_image_it_skips() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let path = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap();
let out = s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap();
assert_eq!(out["ids"].as_array().map(Vec::len), Some(1), "{out}");
let skipped = out["skipped"].as_array().expect("the skipped image");
assert_eq!(skipped.len(), 1, "{out}");
assert_eq!(skipped[0]["id"], json!(img.0));
assert!(skipped[0]["reason"].as_str().unwrap().contains("Perspective Distort or Free Distort"), "{out}");
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
// Without a distorted image, no `skipped`.
let other = rect(&mut s, 400.0, 0.0, 100.0, 100.0);
let out = s.execute("object.mesh.create", &json!({"ids": [other.0], "rows": 1, "cols": 1})).unwrap();
assert!(out.get("skipped").is_none(), "{out}");
}
/// A blend takes the warp's affine approximation whole, so an image inside it does not stop a
/// distort whose corners an image could not follow.
#[test]
fn distort_of_a_blend_holding_an_image_is_not_refused() {
let mut s = session();
let img = placed_image(&mut s);
let r = rect(&mut s, 200.0, 0.0, 100.0, 100.0);
let out = s.execute("object.blend.make", &json!({"ids": [img.0, r.0]})).unwrap();
let blend = NodeId(out["id"].as_u64().unwrap());
let undo = undo_len(&s);
s.execute("object.distort", &json!({"ids": [blend.0], "corners": [[0, 0], [300, 0], [100, 50], [0, 100]]})).unwrap();
assert_eq!(undo_len(&s), undo + 1);
assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
}
/// The Control bar's Mask clips a distorted image to the shape between its corners.
#[test]
fn mask_on_a_distorted_image_follows_its_corners() {
let mut s = session();
let img = placed_image(&mut s);
let want = [(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let out = s.execute("object.maskImage", &json!({})).unwrap();
let path = NodeId(out["path"].as_u64().unwrap());
let d = &s.doc().unwrap().doc;
let anchors: Vec<Point> = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect();
assert_eq!(anchors.len(), 4, "{anchors:?}");
for (x, y) in want {
assert!(anchors.iter().any(|a| a.distance(Point::new(x, y)) < 1e-9), "{x},{y} not in {anchors:?}");
}
assert!(d.node(img).unwrap().is_distorted_image());
}
/// A Transform effect moves a distorted image's corners with it: expanded, the image stands
/// where the effect drew it.
#[test]
fn a_transform_effect_moves_a_distorted_images_corners() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let mut found = vec![];
for layer in &s.doc().unwrap().doc.layers {
layer.walk(&mut |n| {
if let Some(q) = n.image_corners() {
found.push(q);
}
});
}
let want = [(240.0, 0.0), (260.0, 0.0), (300.0, 100.0), (200.0, 100.0)];
assert!(found.iter().any(|q| q.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-6)), "{found:?}");
}
/// A Transform effect after a Warp effect moves a distorted image's warped pixels once: the art
/// stands where the Warp alone draws it, moved by the Transform.
#[test]
fn a_transform_after_a_warp_moves_a_distorted_image_once() {
let expanded_bounds = |transform: bool| {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "warp.bulge", "params": {"bend": 50}})).unwrap();
if transform {
s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap();
}
s.execute("select.set", &json!({"ids": [img.0]})).unwrap();
s.execute("effect.expandAppearance", &json!({})).unwrap();
let mut images = None;
for layer in &s.doc().unwrap().doc.layers {
layer.walk(&mut |n| {
if let vectorcraft_doc::NodeKind::Image(im) = &n.kind {
let r = im.xf.transform_rect_bbox(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)));
images = Some(images.map_or(r, |b: vectorcraft_geom::Rect| b.union(r)));
}
});
}
images.expect("the warped pieces")
};
let (alone, moved) = (expanded_bounds(false), expanded_bounds(true));
assert!((moved.x0 - alone.x0 - 200.0).abs() < 1e-6 && (moved.x1 - alone.x1 - 200.0).abs() < 1e-6, "{alone:?} {moved:?}");
assert!((moved.y0 - alone.y0).abs() < 1e-6 && (moved.y1 - alone.y1).abs() < 1e-6, "{alone:?} {moved:?}");
}
/// A raster effect's baked pixels already show the distortion: the image that replaces a
/// distorted one is placed by its own transform.
#[test]
fn baked_raster_effect_pixels_replace_a_distortion() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let v = s.doc().unwrap().doc.node(img).unwrap().clone();
let baked = Node::new(NodeId(99), v.kind.clone());
let out = crate::cmd::rasterfx::replace_with_image(v, baked);
assert!(!out.is_distorted_image());
assert!(out.extras().image_quad.is_none());
}
/// A distorted image is saved with its corners and reads back the same.
#[test]
fn a_distorted_image_saves_and_reads_back() {
let mut s = session();
let img = placed_image(&mut s);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let doc = &s.doc().unwrap().doc;
let bytes = vectorcraft_format::save(doc, false);
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(img).unwrap().image_corners(), doc.node(img).unwrap().image_corners());
assert!(back.node(img).unwrap().is_distorted_image());
assert!(String::from_utf8_lossy(&bytes).contains("image_quad"));
// An image without a distortion is saved without the field, and opens as it was.
let mut plain = session();
let img = placed_image(&mut plain);
let doc = &plain.doc().unwrap().doc;
let bytes = vectorcraft_format::save(doc, false);
assert!(!String::from_utf8_lossy(&bytes).contains("image_quad"));
let back = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(back.node(img), doc.node(img));
// Corners in a file that fold the image over leave it placed by its transform.
let mut bad = (**doc).clone();
bad.node_mut(img).unwrap().extras_mut().image_quad =
Some(Box::new([(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)].map(|(x, y)| Point::new(x, y))));
let back = vectorcraft_format::load(&vectorcraft_format::save(&bad, false)).unwrap();
assert!(!back.node(img).unwrap().is_distorted_image());
assert_corners(back.node(img).unwrap().image_corners().unwrap(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
}
/// A distort whose corners cross the warp's horizon at the image is refused with that reason, and
/// a distort that leaves a distorted image where it is records nothing.
#[test]
fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing() {
let mut s = session();
let img = placed_image(&mut s);
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
// The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at
// y = 15, inside the image.
let e = s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string();
assert!(e.contains("horizon"), "{e}");
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s));
let b = bounds(&s, img);
let at = [[b.x0, b.y0], [b.x1, b.y0], [b.x1, b.y1], [b.x0, b.y1]];
s.execute("object.distort", &json!({ "from": [b.x0, b.y0, b.x1, b.y1], "corners": at })).unwrap();
assert_eq!(s.doc().unwrap().doc, before);
assert_eq!(undo_len(&s), undo);
}
/// Image info gives a distorted image's resolution at its middle, not the resolution it had
/// before the distort.
#[test]
fn image_info_measures_a_distorted_image_at_its_middle() {
let mut s = session();
placed_image(&mut s);
// 2 pixels across 100 pt: 1.44 ppi.
let ppi = |s: &mut Session| {
let out = s.execute("image.info", &json!({})).unwrap();
[out["ppi"][0].as_f64().unwrap(), out["ppi"][1].as_f64().unwrap()]
};
assert!((ppi(&mut s)[0] - 1.44).abs() < 1e-9);
// The top squeezed to half the width: the middle of the pixels spans less than 100 pt across,
// so the resolution across there is higher.
s.execute("object.distort", &json!({ "corners": [[25, 0], [75, 0], [100, 100], [0, 100]] })).unwrap();
let [x, _] = ppi(&mut s);
assert!(x > 1.44 * 1.1, "{x}");
}
/// Rasterize draws a distorted image's pixels between its corners, and the image it makes is a
/// plain one.
#[test]
fn rasterize_draws_a_distorted_image_between_its_corners() {
let mut s = session();
let img = placed_image(&mut s);
let mut png = std::io::Cursor::new(vec![]);
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap();
s.edit("Pixels", |d, _| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png.into_inner()));
Ok(())
})
.unwrap();
s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap();
s.execute("select.set", &json!({ "ids": [img.0] })).unwrap();
let out = s.execute("object.rasterize", &json!({ "ppi": 72, "background": "transparent", "addAround": 0 })).unwrap();
let d = &s.doc().unwrap().doc;
let id = NodeId(out["id"].as_u64().unwrap());
let n = d.node(id).unwrap();
assert!(!n.is_distorted_image());
let vectorcraft_doc::NodeKind::Image(im) = &n.kind else { panic!("an image") };
// The raster covers the corners' bounds.
let b = n.geometric_bounds().unwrap();
assert!([b.x0, b.y0, b.x1 - 100.0, b.y1 - 100.0].iter().all(|v| v.abs() <= 1.0), "{b:?}");
let px = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap();
let (w, h) = px.dimensions();
let rgba = px.to_rgba8();
let alpha = |x: f64, y: f64| {
let p = im.xf.inverse() * Point::new(x, y);
assert!(p.x >= 0.0 && p.y >= 0.0 && p.x < f64::from(w) && p.y < f64::from(h), "({x}, {y}) is outside the raster: {p:?}");
let (i, j) = (p.x as u32, p.y as u32);
rgba[((j * w + i) * 4 + 3) as usize]
};
assert_eq!(alpha(50.0, 90.0), 255, "inside the corners");
assert_eq!(alpha(10.0, 10.0), 0, "inside the old rectangle, outside the corners");
}
/// A Free Transform drag in Free Distort mode on an image puts the dragged corner where the drag
/// ends, in one undo step, also when a position on the way would have folded the image.
#[test]
fn free_transform_distort_drag_on_an_image_is_one_undo_step() {
let mut s = session();
let img = placed_image(&mut s);
let undo = undo_len(&s);
let v = ViewInfo::default();
s.select_tool("freeTransform", v).unwrap();
s.set_tool_option("mode", &json!("distort"));
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
// Past the top left corner: the image would fold over.
s.pointer(&PointerEvent::new(PointerKind::Drag, -50.0, -50.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 120.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 120.0), v).unwrap();
assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (130.0, 120.0), (0.0, 100.0)]);
assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image());
assert_eq!(undo_len(&s), undo + 1);
}
#[test]
fn free_transform_distort_mode_via_pointer() {
let mut s = session();