This commit is contained in:
bflatastic committed 2026-11-19 01:09:05 +07:00
commit 333a70effe
4 files changed
+269 -5

No files matched your search

+172 -1
View File
@@ -1382,7 +1382,134 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p
} else {
object.appearance.contents_index
};
Some(Appearance { items, effects: st.effects.clone(), contents_index })
let appearance = Appearance { items, effects: st.effects.clone(), contents_index };
// Zig Zag's ridges are placed by VectorCraft's own rule: on objects other than type it is kept
// only where they draw the outline the drawn look has.
if !slot && st.effects.iter().any(|e| e.id == "distort.zigZag") && !draws_look_outline(object, &appearance, look) {
return None;
}
Some(appearance)
}
/// How far, in points, an outline drawn with a reshaping effect may lie from its drawn look's
/// ([`draws_look_outline`]): the look's coordinates are written to a few decimals.
const OUTLINE_TOLERANCE: f64 = 0.25;
/// How far, in points, a flattened outline in [`draws_look_outline`] may lie from its curves.
const OUTLINE_FLATNESS: f64 = OUTLINE_TOLERANCE / 10.0;
/// How far apart, in points, [`draws_look_outline`] checks points along each flattened segment.
const OUTLINE_SPACING: f64 = OUTLINE_TOLERANCE / 2.0;
/// How close, in points, each checked point must lie to the other flattened outline: every point
/// between two checked ones is within half the spacing of one, and both outlines are within the
/// flatness of their curves, so the curves are then within [`OUTLINE_TOLERANCE`] of each other.
const OUTLINE_POINT_LIMIT: f64 = OUTLINE_TOLERANCE - 2.0 * OUTLINE_FLATNESS - OUTLINE_SPACING / 2.0;
/// Most point-to-segment distances worked out for one object, over all its look's outlines.
const MAX_OUTLINE_PAIRS: usize = 4_000_000;
/// Does path or compound path `object` with `appearance`'s effects draw every outline of its drawn look
/// `look`, as `look` draws its own (each within [`OUTLINE_TOLERANCE`] of the other)? `false` for
/// anything else: a look holding other than paths, outlines too detailed to compare.
fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bool {
fn leaves(n: &Node, out: &mut Vec<vectorcraft_geom::PathData>, depth: usize) -> bool {
match &n.kind {
NodeKind::Path { path, .. } => {
out.push(path.clone());
true
}
NodeKind::Compound { children, .. } => {
out.push(vectorcraft_geom::PathData::new(
children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect(),
));
true
}
NodeKind::Group { clip: false, .. } if depth < MAX_DEPTH => n.children().into_iter().flatten().all(|c| leaves(c, out, depth + 1)),
_ => false,
}
}
/// The segments of `paths` flattened, at most `max` of them.
fn segments(paths: &[vectorcraft_geom::PathData], max: usize) -> Option<Vec<kurbo::Line>> {
let mut out = vec![];
let (mut start, mut last) = (None, None);
let mut over = false;
for p in paths {
vectorcraft_geom::flatten(p.to_bezpath(), OUTLINE_FLATNESS, |el| {
let mut add = |a: kurbo::Point, b: kurbo::Point| {
if out.len() < max {
out.push(kurbo::Line::new(a, b));
} else {
over = true;
}
};
match el {
kurbo::PathEl::MoveTo(q) => (start, last) = (Some(q), Some(q)),
kurbo::PathEl::LineTo(q) => {
if let Some(l) = last {
add(l, q);
}
last = Some(q);
}
kurbo::PathEl::ClosePath => {
if let (Some(l), Some(s)) = (last, start) {
add(l, s);
}
last = start;
}
_ => {}
}
});
}
(!over && !out.is_empty()).then_some(out)
}
/// Does every point of segments `a` lie close enough to segments `b` ([`OUTLINE_POINT_LIMIT`])?
/// Each segment is checked at both ends (the last point of an open outline starts no segment)
/// and at points at most [`OUTLINE_SPACING`] apart between them (two outlines can share their
/// vertices and join them differently). Each point's distance to each segment of `b` (a
/// projection onto it) is taken from `budget`: `false` once that runs out.
fn near(a: &[kurbo::Line], b: &[kurbo::Line], budget: &mut usize) -> bool {
use kurbo::{ParamCurve, ParamCurveArclen, ParamCurveNearest};
let close = |p: kurbo::Point| b.iter().any(|t| t.nearest(p, 1e-6).distance_sq <= OUTLINE_POINT_LIMIT * OUTLINE_POINT_LIMIT);
for s in a {
let steps = (s.arclen(1e-6) / OUTLINE_SPACING).ceil();
let steps = if steps.is_finite() && steps >= 1.0 { steps as usize } else { 1 };
let Some(left) = budget.checked_sub(steps.saturating_add(1).saturating_mul(b.len())) else { return false };
*budget = left;
if !(0..=steps).all(|k| close(s.eval(k as f64 / steps as f64))) {
return false;
}
}
true
}
/// The box round segments `lines` (`None` without any).
fn bounds(lines: &[kurbo::Line]) -> Option<kurbo::Rect> {
let first = lines.first()?.p0;
Some(lines.iter().fold(kurbo::Rect::from_points(first, first), |r, l| r.union_pt(l.p0).union_pt(l.p1)))
}
let (mut ours, mut theirs) = (vec![], vec![]);
if !matches!(object.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) || !leaves(object, &mut ours, 0) || !leaves(look, &mut theirs, 0) {
return false;
}
// The object's outline reshaped as it is drawn: its effects from its own bounds.
for path in &mut ours {
let bounds = kurbo::Shape::bounding_box(&path.to_bezpath());
*path = vectorcraft_effects::apply_geometry(&appearance.effects, path, bounds);
}
let max = MAX_OUTLINE_PAIRS.isqrt();
let Some(ours) = segments(&ours, max) else { return false };
let Some(ours_box) = bounds(&ours) else { return false };
// Two outlines each within the tolerance of the other have boxes as close: the boxes are
// compared first, then the points, from one budget for the object.
let boxed = |t: &[kurbo::Line]| {
let Some(r) = bounds(t) else { return false };
[r.x0 - ours_box.x0, r.y0 - ours_box.y0, r.x1 - ours_box.x1, r.y1 - ours_box.y1].iter().all(|d| d.abs() <= OUTLINE_TOLERANCE)
};
let mut budget = MAX_OUTLINE_PAIRS;
// Each of the look's outlines (a fill and a stroke draw the same one) is the object's.
theirs
.iter()
.all(|t| segments(std::slice::from_ref(t), max).is_some_and(|t| boxed(&t) && near(&t, &ours, &mut budget) && near(&ours, &t, &mut budget)))
}
/// A graphic style's appearance from art style `st`, on no object: `None` when the style isn't one
@@ -1673,6 +1800,50 @@ mod tests {
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, Paint::None, 0.0)))
}
/// The outline check works from one budget for the object: a look of the outline drawn twice
/// (a fill and a stroke) matches, one drawn thousands of times gives up and keeps the drawn
/// look instead of comparing every copy.
#[test]
fn the_outline_check_has_one_budget_for_the_object() {
let zig = vectorcraft_doc::Effect {
id: "distort.zigZag".into(),
params: serde_json::json!({"size": 3.0, "relative": false, "ridges": 4, "points": "corner"}),
visible: true,
};
let path = shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 60.0));
let appearance = Appearance { effects: vec![zig.clone()], ..Appearance::basic(Paint::None, Paint::None, 0.0) };
let object = Node::path(NodeId(1), path.clone(), appearance.clone());
let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &path, Rect::new(0.0, 0.0, 100.0, 60.0));
let look = |copies: u64| {
let drawn = (0..copies).map(|i| Arc::new(Node::path(NodeId(10 + i), outline.clone(), Appearance::default()))).collect();
Node::group(NodeId(2), drawn)
};
assert!(draws_look_outline(&object, &appearance, &look(2)));
let started = std::time::Instant::now();
assert!(!draws_look_outline(&object, &appearance, &look(5_000)));
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
}
/// The outline check holds for every point of the outlines, not only the points it checks: a
/// 0.25 pt line whose look has only short pieces over its ends, 0.24 pt away, leaves the
/// line's middle about 0.27 pt from the look, so the drawn look stays. The line drawn 0.1 pt
/// away matches.
#[test]
fn the_outline_check_holds_between_the_points_it_checks() {
use kurbo::Point;
use vectorcraft_geom::{PathData, SubPath};
let appearance = Appearance::basic(Paint::None, Paint::None, 0.0);
let line = PathData::new(vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(0.25, 0.0)], false)]);
let object = Node::path(NodeId(1), line, appearance.clone());
let look = |pieces: &[[Point; 2]]| {
let drawn = PathData::new(pieces.iter().map(|p| SubPath::polyline(p, false)).collect());
Node::group(NodeId(2), vec![Arc::new(Node::path(NodeId(3), drawn, Appearance::default()))])
};
let ends = [[Point::new(0.0, 0.24), Point::new(0.01, 0.24)], [Point::new(0.24, 0.24), Point::new(0.25, 0.24)]];
assert!(!draws_look_outline(&object, &appearance, &look(&ends)));
assert!(draws_look_outline(&object, &appearance, &look(&[[Point::new(0.0, 0.1), Point::new(0.25, 0.1)]])));
}
/// An image draws no stroke, so an image with a brush in its art style keeps its drawn look.
#[test]
fn an_image_with_a_brush_keeps_its_drawn_look() {
+5 -3
View File
@@ -1744,8 +1744,9 @@ impl Builder<'_> {
/// Is `e`, on the whole object, an effect any object is read with? Of the Distort & Transform
/// effects: Transform without copies (Random is never read), Twist, a Tweak that moves nothing,
/// Pucker & Bloat at 0, and Free Distort when its corners make a parallelogram (an affine map).
/// Zig Zag is left to type. Which objects Transform, Twist and Free Distort are read on is
/// Pucker & Bloat at 0, Free Distort when its corners make a parallelogram (an affine map), and Zig
/// Zag (on objects other than type only where it draws its drawn look's outline: `read::ops`'
/// `styled`). Which objects Transform, Twist and Free Distort are read on is
/// `read::ops`' `moves_with`.
fn any_object_takes(e: &Effect) -> bool {
match e.id.as_str() {
@@ -1762,7 +1763,8 @@ fn any_object_takes(e: &Effect) -> bool {
| "path.outlineObject"
| "path.outlineStroke"
| "distort.twist"
| "distort.tweak" => true,
| "distort.tweak"
| "distort.zigZag" => true,
// Copies are drawn as one path, its fills under all its strokes, where the file paints each
// copy's fill and stroke in turn.
"distort.transform" => e.params["copies"].as_i64() == Some(0),
+2 -1
View File
@@ -1023,7 +1023,8 @@ fn any_object_takes_the_distort_effects_that_draw_as_its_drawn_look() {
assert!(simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.0], [0.0, -1.0], [1.0, -1.0]])));
assert!(!simple("Adobe Free Distort", &corners(src, [[0.2, 0.0], [1.2, 0.1], [0.0, -1.0], [1.0, -1.0]])));
assert!(!simple("Adobe Punk and Bloat", "-35 /Real (d_factor) ,\n"));
assert!(!simple("Adobe Zigzag", ""));
// Zig Zag: objects other than type check it against their drawn look (`read::ops`).
assert!(simple("Adobe Zigzag", ""));
assert!(!simple("Adobe Transform", &format!("1 /Int (numCopies) ,\n{SWITCHES}")));
// With another effect, only type takes it.
let chain = [basic("Adobe Twirl", "45 /Real (angle) ,\n"), basic("Adobe Offset Path", "4 /Real (ofst) ,\n0 /Int (jntp) ,\n4 /Real (mlim) ,\n")];
+90
View File
@@ -7369,6 +7369,96 @@ fn an_object_with_a_distort_effect_drawn_another_way_keeps_its_drawn_look() {
}
}
#[test]
fn a_path_with_zig_zag_comes_in_as_itself_where_its_look_has_that_outline() {
// GUARDS: Zig Zag on a path came in as its drawn look even where the live effect draws the same outline.
let keys = "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n2 /Real (ridges) ,\n0 /Real (roundness) ,\n";
let zig = vectorcraft_doc::Effect {
id: "distort.zigZag".into(),
params: serde_json::json!({"size": 3.0, "relative": false, "ridges": 2, "points": "corner"}),
visible: true,
};
// The square as the document has it (y up in the file, down in the document).
let plain = read_ok(&layer(&format!("{RED}{}f\n", rect_path(20.0, 20.0, 60.0, 50.0))));
let square = art(&plain.doc)[0].path_data().unwrap().clone();
let to_file = |p: Point| {
let start = square.subpaths[0].anchors[0].p;
Point::new(p.x - start.x + 20.0, start.y - p.y + 20.0)
};
let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &square, square.bounds().unwrap());
// The look: the outline the effect draws, as straight segments.
let ops = |shift: f64| -> String {
let mut out = String::new();
for sp in &outline.subpaths {
for (i, a) in sp.anchors.iter().enumerate() {
let p = to_file(a.p);
out.push_str(&format!("{:.4} {:.4} {}\n", p.x + shift, p.y, if i == 0 { "m" } else { "L" }));
}
}
out
};
let hidden_rect = rect_path(20.0, 20.0, 60.0, 50.0).replace('\n', "\n%_");
let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}f\nU\n%_{hidden_rect}f\n1 (Bent) XW\n");
let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(0.0)))));
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
let a = art(&r.doc);
assert_eq!(a.len(), 1, "{a:#?}");
assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {a:#?}");
let e = &a[0].appearance.effects;
assert_eq!(e.len(), 1, "{e:?}");
assert_eq!(
(e[0].id.as_str(), &e[0].params),
("distort.zigZag", &serde_json::json!({"size": 3.0, "relative": false, "ridges": 2, "points": "corner"}))
);
// A look whose ridges lie elsewhere (here 1 pt to the right) keeps the drawn look.
let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(1.0)))));
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
assert!(matches!(art(&r.doc)[0].kind, NodeKind::Group { .. }));
// An open path (filled without closing it, `F`): its look's outline matches, and a look whose
// last point lies 3 pt away from where the effect ends it keeps the drawn look.
let open_path = "20 20 m\n60 20 L\n60 50 L\n";
let plain = read_ok(&layer(&format!("{RED}{open_path}F\n")));
let open = art(&plain.doc)[0].path_data().unwrap().clone();
assert!(!open.subpaths[0].closed);
let start = open.subpaths[0].anchors[0].p;
let outline = vectorcraft_effects::apply_geometry(std::slice::from_ref(&zig), &open, open.bounds().unwrap());
let ops = |last_shift: f64| -> String {
let mut out = String::new();
for sp in &outline.subpaths {
for (i, a) in sp.anchors.iter().enumerate() {
let shift = if i + 1 == sp.anchors.len() { last_shift } else { 0.0 };
let p = Point::new(a.p.x - start.x + 20.0 + shift, start.y - a.p.y + 20.0);
out.push_str(&format!("{:.4} {:.4} {}\n", p.x, p.y, if i == 0 { "m" } else { "L" }));
}
}
out
};
let hidden_open = open_path.replace('\n', "\n%_");
let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}F\nU\n%_{hidden_open}F\n1 (Bent) XW\n");
let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(0.0)))));
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", keys, BLUE_FILL), layer(&object(&ops(3.0)))));
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
// A Zig Zag of no size on an open path through the corners of its look's square, joined
// across it: the vertices match, the segments between them don't, so the drawn look stays.
let flat = "0 /Real (amount) ,\n1 /Real (absoluteness) ,\n0 /Real (ridges) ,\n0 /Real (roundness) ,\n";
let bowtie = "%_20 20 m\n%_60 50 L\n%_60 20 L\n%_20 50 L\n%_F\n";
let crossed = format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{}f\nU\n{bowtie}1 (Bent) XW\n", rect_path(20.0, 20.0, 60.0, 50.0));
let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", flat, BLUE_FILL), layer(&crossed)));
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
// A look worked out by hand rather than by the effect: Zig Zag of 3 pt with one ridge per
// segment and corner points, on a line from (20, 20) to (60, 20), puts the line's ends 3 pt up
// the page and its middle 3 pt down. The same look mirrored keeps the drawn look.
let one = "3 /Real (amount) ,\n1 /Real (absoluteness) ,\n1 /Real (ridges) ,\n0 /Real (roundness) ,\n";
let line = "20 20 m\n60 20 L\n".replace('\n', "\n%_");
let object = |look: &str| format!("0 Ae\nu\n0 0 0 0 0 0 1 Xa\n{look}F\nU\n%_{line}F\n1 (Bent) XW\n");
let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", one, BLUE_FILL), layer(&object("20 23 m\n40 17 L\n60 23 L\n"))));
assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
assert!(matches!(art(&r.doc)[0].kind, NodeKind::Path { .. }), "{:#?}", art(&r.doc));
let r = read_ok(&format!("{}{}", distort_styles("Adobe Zigzag", one, BLUE_FILL), layer(&object("20 17 m\n40 23 L\n60 17 L\n"))));
assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings);
}
/// The gradient `G`, white to black, defined for a document.
const GRADIENT_G: &str = "%AI5_BeginGradient: (G)\n(G) 0 2 Bd\n[\n%_1 0 50 0 Bs\n%_0 0 50 100 Bs\nBD\n%AI5_EndGradient\n";