From 810fd3f47f93eaffb2bbf38be5461e59c1f6a20c Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Fri, 13 Nov 2026 20:56:28 -0700 Subject: [PATCH] feat(engine): width profiles and gradients through the merge, and erasing inside symbols (M7) --- crates/doc/src/width.rs | 202 ++++++++++++++++++++++++++++++ crates/engine/src/cmds_draw.rs | 2 +- crates/engine/src/cmds_erase.rs | 40 +++++- crates/engine/src/erase_tests.rs | 127 +++++++++++++++++++ crates/engine/src/merge.rs | 36 ++++-- crates/engine/src/rawsub_tests.rs | 4 +- crates/geom/src/planar.rs | 91 +++++++++++--- crates/geom/src/planar_tests.rs | 28 +++++ 8 files changed, 496 insertions(+), 34 deletions(-) diff --git a/crates/doc/src/width.rs b/crates/doc/src/width.rs index 4e433794..bacb457c 100644 --- a/crates/doc/src/width.rs +++ b/crates/doc/src/width.rs @@ -269,6 +269,155 @@ impl ProfilePreset { } } +impl WidthProfile { + /// This profile carried onto a piece of its stroke (ADR 0093): the piece runs along the + /// stretches `spans` of `path` (the stroke's path, in path positions: `k + t` is parameter + /// `t` of the segment command `k` draws, as `anicraft_geom::planar::Piece::spans` gives + /// them; a stretch with `to < from` runs backwards). The piece's width at each place is the + /// stroke's width there: every width point inside a stretch moves to the same place on the + /// piece (positions are rescaled by arc length), and where the piece starts, ends or jumps + /// mid-profile, a point there holds the width it had. Running backwards swaps left and + /// right. `None` when the piece has one width. + pub fn along(&self, path: &Path, spans: &[[f64; 2]]) -> Option { + let m = Measure::new(path); + let pts = self.points(); + let (first, last) = (pts.first().map_or(0.0, |p| p.t), pts.last().map_or(1.0, |p| p.t)); + let inside = |f: f32| f > first + MERGE && f < last - MERGE; + // Each stretch: its subpath, and where it starts and ends along it (arc length). + let parts: Vec<(usize, f64, f64)> = spans.iter().take(4096).filter_map(|sp| Some((m.locate(sp[0])?, m.locate(sp[1])?))).filter(|(a, b)| a.0 == b.0).map(|(a, b)| (a.0, a.1, b.1)).collect(); + let total: f64 = parts.iter().map(|(_, a, b)| (b - a).abs()).sum(); + if !total.is_finite() || total <= 1e-9 { + return Some(self.clone()); + } + let mut out: Vec = Vec::new(); + let mut cum = 0.0f64; + let side = |f: f32, fwd: bool| { + let (l, r) = self.at(f); + if fwd { (l, r) } else { (r, l) } + }; + for (i, &(sub, a, b)) in parts.iter().enumerate() { + let len = m.sub_len.get(sub).copied().unwrap_or(0.0); + if !len.is_finite() || len <= 1e-12 { + continue; + } + let (fa, fb) = ((a / len) as f32, (b / len) as f32); + let fwd = b >= a; + let q = |s: f64| ((cum + (s - a).abs()) / total) as f32; + // Joined to the stretch before it without a jump: its points carry on. + let joined_before = i > 0 && parts.get(i - 1).is_some_and(|&(ps, _, pb)| ps == sub && (pb - a).abs() < 1e-6 * len.max(1.0)); + let joined_after = parts.get(i + 1).is_some_and(|&(ns, na, _)| ns == sub && (na - b).abs() < 1e-6 * len.max(1.0)); + let mark = |s: f64, f: f32, out: &mut Vec| { + let (l, r) = side(f, fwd); + out.push(WidthPoint::new(q(s), l, r)); + }; + // A width point of the stroke's own already sits there. + let has_point = |f: f32| pts.iter().any(|p| (p.t - f).abs() < 1e-6); + if !joined_before && (i > 0 || inside(fa)) && !has_point(fa) { + mark(a, fa, &mut out); + } + let (lo, hi) = (fa.min(fb) - 1e-6, fa.max(fb) + 1e-6); + let within: Vec<&WidthPoint> = pts.iter().filter(|p| p.t >= lo && p.t <= hi).collect(); + let ordered: Box> = if fwd { Box::new(within.iter()) } else { Box::new(within.iter().rev()) }; + for p in ordered { + let (l, r) = if fwd { (p.left, p.right) } else { (p.right, p.left) }; + out.push(WidthPoint::new(q(f64::from(p.t) * len), l, r)); + } + if !joined_after && (i + 1 < parts.len() || inside(fb)) && !has_point(fb) { + mark(b, fb, &mut out); + } + cum += (b - a).abs(); + } + if out.len() > MAX_WIDTH_POINTS { + // Evenly spaced, the ends kept. + let n = out.len(); + let k = MAX_WIDTH_POINTS; + out = (0..k).filter_map(|i| out.get(i * (n - 1) / (k - 1)).copied()).collect(); + } + if out.is_empty() { + // No point falls on the piece: it lies where the width holds, one width all along. + let f = parts.first().and_then(|&(sub, a, _)| m.sub_len.get(sub).filter(|l| **l > 1e-12).map(|l| (a / l) as f32)).unwrap_or(0.0); + let fwd = parts.first().is_none_or(|&(_, a, b)| b >= a); + let (l, r) = side(f, fwd); + out.push(WidthPoint::new(0.0, l, r)); + } + WidthProfile::new(out) + } +} + +/// Arc lengths along a path's subpaths, by path position. +struct Measure { + /// Each drawn command: its index, subpath, arc length where it starts, and its curve. + segs: Vec<(usize, usize, f64, [Vec2; 4])>, + sub_len: Vec, +} + +impl Measure { + fn new(path: &Path) -> Measure { + use anicraft_geom::PathCmd; + let mut segs = Vec::new(); + let mut sub_len: Vec = Vec::new(); + let (mut start, mut cur, mut acc) = (Vec2::ZERO, Vec2::ZERO, 0.0f64); + let line = |a: Vec2, b: Vec2| [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b]; + for (k, c) in path.cmds.iter().enumerate().take(1 << 20) { + let curve = match *c { + PathCmd::MoveTo(p) => { + if !sub_len.is_empty() || !segs.is_empty() { + sub_len.push(acc); + } + (start, cur, acc) = (p, p, 0.0); + continue; + } + PathCmd::LineTo(p) => line(cur, p), + PathCmd::QuadTo(q, p) => [cur, cur.lerp(q, 2.0 / 3.0), p.lerp(q, 2.0 / 3.0), p], + PathCmd::CubicTo(a, b, p) => [cur, a, b, p], + PathCmd::Close => line(cur, start), + }; + segs.push((k, sub_len.len(), acc, curve)); + acc += cubic_length(&curve, 1.0); + cur = curve[3]; + } + sub_len.push(acc); + Measure { segs, sub_len } + } + + /// The subpath and arc length from its start at path position `u`. + fn locate(&self, u: f64) -> Option<(usize, f64)> { + if !u.is_finite() { + return None; + } + let k = u.floor(); + let t = u - k; + // Position `k + 1` is the end of command `k`. + let (k, t) = if t == 0.0 && k >= 1.0 && !self.segs.iter().any(|s| s.0 as f64 == k) { (k - 1.0, 1.0) } else { (k, t) }; + let i = self.segs.partition_point(|s| (s.0 as f64) < k); + match self.segs.get(i) { + Some(&(cmd, sub, at, c)) if cmd as f64 == k => Some((sub, at + cubic_length(&c, t))), + // The end of the last command (or of one before a MoveTo). + _ => { + let &(_, sub, at, c) = self.segs.get(i.checked_sub(1)?)?; + (t == 0.0).then(|| (sub, at + cubic_length(&c, 1.0))) + } + } + } +} + +/// Arc length of a cubic from 0 to `t` (composite five-point Gauss–Legendre on 16 pieces). +fn cubic_length(c: &[Vec2; 4], t: f64) -> f64 { + const G: [(f64, f64); 5] = [(0.046_910_077_030_668, 0.118_463_442_528_094_5), (0.230_765_344_947_158_45, 0.239_314_335_249_683_2), (0.5, 0.284_444_444_444_444_4), (0.769_234_655_052_841_6, 0.239_314_335_249_683_2), (0.953_089_922_969_332, 0.118_463_442_528_094_5)]; + let t = t.clamp(0.0, 1.0); + let p = c.map(|v| (f64::from(v.x), f64::from(v.y))); + let speed = |s: f64| { + let u = 1.0 - s; + let (d0, d1, d2) = (3.0 * u * u, 6.0 * u * s, 3.0 * s * s); + let dx = d0 * (p[1].0 - p[0].0) + d1 * (p[2].0 - p[1].0) + d2 * (p[3].0 - p[2].0); + let dy = d0 * (p[1].1 - p[0].1) + d1 * (p[2].1 - p[1].1) + d2 * (p[3].1 - p[2].1); + (dx * dx + dy * dy).sqrt() + }; + const N: usize = 16; + let h = t / N as f64; + (0..N).map(|i| G.iter().map(|&(x, w)| w * speed((i as f64 + x) * h)).sum::() * h).sum() +} + /// The unit normal on the left of direction `d` on a y-down screen (`-d.perp()`). pub fn left_normal(d: Vec2) -> Vec2 { Vec2::new(d.y, -d.x) @@ -403,4 +552,57 @@ mod tests { assert_eq!(sq[0].length(), 40.0); assert!(nearest_on_stroke(&[], Vec2::ZERO).is_none()); } + + fn near(a: (f32, f32), b: (f32, f32), tol: f32) -> bool { + (a.0 - b.0).abs() <= tol && (a.1 - b.1).abs() <= tol + } + + #[test] + fn a_piece_of_a_stroke_keeps_the_widths_it_had_there() { + // An asymmetric swell along a 100-long line (command 1 draws it). + let line = Path::line(Vec2::ZERO, Vec2::new(100.0, 0.0)); + let p = WidthProfile::new(vec![WidthPoint::new(0.0, 0.5, 1.0), WidthPoint::new(0.4, 3.0, 2.0), WidthPoint::new(1.0, 1.0, 0.25)]).unwrap(); + // Uncut: the same profile. + let whole = p.along(&line, &[[1.0, 2.0]]).unwrap(); + for (a, b) in whole.points().iter().zip(p.points()) { + assert!((a.t - b.t).abs() < 1e-5 && a.left == b.left && a.right == b.right, "{whole:?}"); + } + // The stretch from 20 to 70: its point at 0.4 moves to (40 − 20) / 50 = 0.4 of the piece, + // and every place on the piece has the width it had on the stroke. + let piece = p.along(&line, &[[1.2, 1.7]]).unwrap(); + for k in 0..=20 { + let u = k as f32 / 20.0; + let src = 0.2 + 0.5 * u; + assert!(near(piece.at(u), p.at(src), 0.12), "at {u}: {:?} vs {:?}", piece.at(u), p.at(src)); + } + assert!(piece.points().iter().any(|w| (w.t - 0.4).abs() < 1e-4 && w.left == 3.0), "{piece:?}"); + // Backwards: the far end comes first, and left and right swap. + let back = p.along(&line, &[[1.7, 1.2]]).unwrap(); + for k in 0..=20 { + let u = k as f32 / 20.0; + let (l, r) = p.at(0.7 - 0.5 * u); + assert!(near(back.at(u), (r, l), 0.12), "back at {u}: {:?} vs {:?}", back.at(u), (r, l)); + } + // A piece where the width holds (past the last point) has none of its own. + let flat = WidthProfile::new(vec![WidthPoint::new(0.0, 0.0, 0.0), WidthPoint::new(0.5, 2.0, 2.0)]).unwrap(); + assert!(flat.along(&line, &[[1.6, 2.0]]).is_some_and(|q| q.at(0.0) == (2.0, 2.0) && q.at(1.0) == (2.0, 2.0))); + let one = WidthProfile::new(vec![WidthPoint::new(0.0, 0.0, 0.0), WidthPoint::new(0.5, 1.0, 1.0)]).unwrap(); + assert!(one.along(&line, &[[1.6, 2.0]]).is_none(), "nominal all along: uniform"); + } + + #[test] + fn pieces_across_segments_and_hostile_spans() { + // Two segments of 50 and 50: the stretch 25..75 crosses from command 1 into command 2. + let mut path = Path::new(); + path.move_to(Vec2::ZERO); + path.line_to(Vec2::new(50.0, 0.0)); + path.line_to(Vec2::new(50.0, 50.0)); + let p = WidthProfile::new(vec![WidthPoint::new(0.0, 1.0, 1.0), WidthPoint::new(1.0, 3.0, 3.0)]).unwrap(); + let piece = p.along(&path, &[[1.5, 2.0], [2.0, 2.5]]).unwrap(); + assert!(near(piece.at(0.0), p.at(0.25), 1e-3) && near(piece.at(1.0), p.at(0.75), 1e-3), "{piece:?}"); + // Positions past the path, not numbers, or nothing: never a panic. + let _ = p.along(&path, &[[f64::NAN, 9.0], [-4.0, 1e300]]); + assert!(p.along(&path, &[]).is_some()); + assert!(p.along(&Path::new(), &[[1.0, 2.0]]).is_some()); + } } diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index f7164d0e..7141f042 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -111,7 +111,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, // A gradient or bitmap from the fill swatch is in stage space: with Lock Fill it stays where // it is on the stage, else it is fitted to the new shape (ADR 0074). let fill = fill.map(|f| if s.style.lock_fill || matches!(f, Paint::Solid(_)) { f.transformed(&Affine::translate(-origin.x, -origin.y)) } else { f.fitted(&local.bounds()) }); - let merge = !object && crate::merge::can_merge(stroke.as_ref()); + let merge = !object; let id = ElementId(s.doc.alloc_id()); let el = Element { id, diff --git a/crates/engine/src/cmds_erase.rs b/crates/engine/src/cmds_erase.rs index be5be5d4..f45bf51d 100644 --- a/crates/engine/src/cmds_erase.rs +++ b/crates/engine/src/cmds_erase.rs @@ -85,11 +85,22 @@ fn erase(s: &mut Session, p: &Value) -> Result { /// Erases `eraser` (keyframe space) from the active layer's raw shapes, as `mode` says. pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: Vec2) -> Result { - let nothing = |why: &str| Ok(json!({"erased": false, "mode": mode.key(), "elements": [], "reason": why})); // Nothing may change when nothing is erased (no keyframe made, no undo step). let before = s.doc.clone(); let els = s.editable_keyframe()?.elements.clone(); let area = eraser.bounds().inflate(2.0 * SNAP); + // What the eraser passes over and keeps (ADR 0093): symbols, and drawing objects, groups and + // text. Each opens for editing in place, where its raw shapes erase. + let kept = kept_under(s, &els, eraser); + let nothing = |why: &str| { + let why = match kept { + (0, 0) => why.to_string(), + (_, 0) => "the eraser keeps symbols on the stage; double-click one with the Selection tool (or select it and use Edit Symbols) to erase inside it".to_string(), + (0, _) => "the eraser keeps drawing objects; double-click one with the Selection tool to erase inside it".to_string(), + _ => "the eraser keeps symbols and drawing objects; double-click one with the Selection tool to erase inside it".to_string(), + }; + Ok(json!({"erased": false, "mode": mode.key(), "elements": [], "reason": why, "kept": {"symbols": kept.0, "objects": kept.1}})) + }; let touching: Vec = (0..els.len()).filter(|&i| els.get(i).and_then(|e| mergeable(e).map(|sh| !reach(sh, &e.transform).intersect(&area).is_empty())).unwrap_or(false)).collect(); let el = |i: &usize| els.get(*i).map(|e| e.as_ref()); let is_fill = |i: &usize| el(i).and_then(mergeable).is_some_and(|sh| sh.fill.is_some()); @@ -142,7 +153,32 @@ pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: // What stays selected: the rest of the selection, and what is left of selected shapes. s.selection.retain(|l, id| l != here || !gone.contains(&id)); s.selection.extend_on(here, picked); - Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0)})) + Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0), "kept": {"symbols": kept.0, "objects": kept.1}})) +} + +/// How many symbol instances, and how many other elements that are not raw shapes (drawing +/// objects, groups, text), the eraser's outline reaches on the keyframe: what it keeps. +fn kept_under(s: &Session, els: &[std::sync::Arc], eraser: &Path) -> (usize, usize) { + let area = eraser.bounds(); + let (mut symbols, mut objects) = (0, 0); + for e in els.iter().take(100_000) { + if mergeable(e).is_some() || matches!(e.kind, ElementKind::Camera) { + continue; + } + let b = match &e.kind { + ElementKind::Shape(sh) => reach(sh, &e.transform), + _ => s.element_bounds(e.id), + }; + if b.intersect(&area).is_empty() { + continue; + } + if matches!(e.kind, ElementKind::Symbol { .. }) { + symbols += 1; + } else { + objects += 1; + } + } + (symbols, objects) } /// Total fill area and stroke length of raw shapes, in keyframe space. Fill areas are exact diff --git a/crates/engine/src/erase_tests.rs b/crates/engine/src/erase_tests.rs index be5f6c42..8bf2200c 100644 --- a/crates/engine/src/erase_tests.rs +++ b/crates/engine/src/erase_tests.rs @@ -228,3 +228,130 @@ fn bad_params_are_errors_and_plug_ins_may_erase() { assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); } } + +// ----- ADR 0093: gradients and width profiles through the merge, erasing inside symbols -------- + +#[test] +fn an_erased_gradient_keeps_its_gradient_in_both_pieces_where_it_was() { + let mut s = blank(false); + let stops = vec![anicraft_doc::GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, anicraft_doc::GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }]; + let paint = Paint::linear(Vec2::new(100.0, 100.0), Vec2::new(300.0, 100.0), stops); + s.style.fill_paint = Some(paint.clone()); + s.style.lock_fill = true; + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "stroke": null})); + run(&mut s, "edit.deselect", json!({})); + let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20})); + assert_eq!(r["erased"], true); + let pieces = shapes(&s); + assert_eq!(pieces.len(), 2, "cut in two"); + for (sh, m) in &pieces { + let f = sh.fill.as_ref().map(|f| f.transformed(m)).expect("filled"); + assert!(crate::merge::same_paint(&f, &paint), "the gradient stays in the same place on the stage: {f:?}"); + } + assert!(near(measure(&s).0, 18_000.0, 40.0)); + // The renderer agrees: left red, right blue, the band empty. + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let (l, r) = (img.pixel(110, 150).unwrap(), img.pixel(290, 150).unwrap()); + assert!(l[0] > 0.85 && l[2] < 0.15 && r[2] > 0.85 && r[0] < 0.15, "{l:?} {r:?}"); +} + +/// The raw strokes on the active layer with their profiles, as (start x, end x, profile). +fn profiled(s: &Session) -> Vec<(f32, f32, Option)> { + shapes(s) + .into_iter() + .filter_map(|(sh, m)| { + let st = sh.stroke.as_ref()?; + let ends: Vec = sh.path.anchors().iter().map(|p| m.apply(p.1)).collect(); + Some((ends.first()?.x, ends.last()?.x, st.profile.clone())) + }) + .collect() +} + +#[test] +fn a_variable_width_stroke_split_by_the_eraser_keeps_its_profile_per_piece() { + let mut s = blank(false); + s.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth); + let source = anicraft_doc::ProfilePreset::TaperBoth.profile().unwrap(); + run(&mut s, "draw.line", json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke": BLACK, "stroke_width": 12})); + run(&mut s, "edit.deselect", json!({})); + assert_eq!(profiled(&s).len(), 1, "a variable-width line is raw (ADR 0093)"); + let r = run(&mut s, "draw.erase", json!({"points": stroke(150.0, 60.0, 150.0, 140.0), "size": 20})); + assert_eq!(r["erased"], true); + let pieces = profiled(&s); + assert_eq!(pieces.len(), 2, "{pieces:?}"); + for (x0, x1, prof) in &pieces { + let prof = prof.as_ref().expect("each piece keeps a profile"); + // Every place on the piece has the width it had on the line. + for k in 0..=10 { + let u = k as f32 / 10.0; + let x = x0 + (x1 - x0) * u; + let want = source.at((x - 100.0) / 200.0); + let got = prof.at(u); + assert!((got.0 - want.0).abs() < 0.06 && (got.1 - want.1).abs() < 0.06, "at x {x}: {got:?} vs {want:?} ({x0}..{x1})"); + } + } + // The left piece starts at a point and ends wide; erasing nothing changes nothing. + let doc = s.doc.clone(); + let r = run(&mut s, "draw.erase", json!({"points": stroke(150.0, 300.0, 150.0, 340.0), "size": 20})); + assert_eq!(r["erased"], false); + assert_eq!(s.doc, doc); + // A line across a variable-width line cuts it too, the profile following each piece. + let mut t = blank(false); + t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth); + run(&mut t, "draw.line", json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke": BLACK, "stroke_width": 12})); + t.style.set_profile(anicraft_doc::ProfilePreset::Uniform); + run(&mut t, "draw.line", json!({"x0": 200, "y0": 0, "x1": 200, "y1": 200, "stroke": RED, "stroke_width": 2})); + let cut: Vec<_> = profiled(&t).into_iter().filter(|p| p.2.is_some()).collect(); + assert_eq!(cut.len(), 2, "{cut:?}"); + // Merging the pieces again (a drop) keeps them as they are. + let before = profiled(&t); + let ids: Vec = t.visible_elements().iter().map(|e| e.id.0).collect(); + t.select_only(ids.iter().map(|i| anicraft_doc::ElementId(*i))); + run(&mut t, "draw.drop", json!({})); + let after = profiled(&t); + assert_eq!(after.len(), before.len()); + for (a, b) in after.iter().filter(|p| p.2.is_some()).zip(before.iter().filter(|p| p.2.is_some())) { + let (pa, pb) = (a.2.as_ref().unwrap(), b.2.as_ref().unwrap()); + for k in 0..=10 { + let u = k as f32 / 10.0; + assert!((pa.at(u).0 - pb.at(u).0).abs() < 1e-3, "remerged profile drifted"); + } + } + // And the file keeps them. + let json = crate::format::to_json(&s.doc).unwrap(); + assert_eq!(crate::format::from_json(&json).unwrap(), s.doc); +} + +#[test] +fn the_eraser_works_inside_an_open_symbol_and_says_how_on_the_stage() { + let mut s = blank(false); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": BLUE, "stroke": null})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Card"})); + let inst = s.selection.id_list().first().copied().expect("the instance is selected"); + run(&mut s, "edit.deselect", json!({})); + // On the stage, the symbol is kept, and the reason says how to erase inside it. + let (doc, steps) = (s.doc.clone(), s.history_len()); + let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20})); + assert_eq!(r["erased"], false); + assert_eq!(r["kept"]["symbols"], 1); + assert!(r["reason"].as_str().unwrap().contains("double-click"), "{r}"); + assert_eq!((s.doc.clone(), s.history_len()), (doc, steps), "no change, no undo step"); + // Opened in place, its raw shapes erase, in the symbol's own space. + run(&mut s, "symbol.edit", json!({"id": inst})); + let to_symbol = s.editing.last().map(|l| l.transform).and_then(|m| m.inverse()).unwrap(); + let pts: Vec<[f32; 2]> = stroke(200.0, 60.0, 200.0, 240.0).into_iter().map(|[x, y]| to_symbol.apply(Vec2::new(x, y))).map(|p| [p.x, p.y]).collect(); + let r = run(&mut s, "draw.erase", json!({"points": pts, "size": 20})); + assert_eq!(r["erased"], true, "{r}"); + run(&mut s, "symbol.exit", json!({"all": true})); + // The instance on the stage shows the cut (the renderer, the oracle). + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + let bg = s.doc.stage.background; + let (gap, kept) = (img.pixel(200, 150).unwrap(), img.pixel(150, 150).unwrap()); + assert!((gap[2] - bg.b).abs() < 0.02 && (gap[0] - bg.r).abs() < 0.02, "{gap:?}"); + assert!(kept[2] > 0.9, "{kept:?}"); + // One undo step puts the symbol back whole. + run(&mut s, "edit.undo", json!({})); + let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap(); + assert!(img.pixel(200, 150).unwrap()[2] > 0.9); +} diff --git a/crates/engine/src/merge.rs b/crates/engine/src/merge.rs index 114ca901..f55b2ad8 100644 --- a/crates/engine/src/merge.rs +++ b/crates/engine/src/merge.rs @@ -19,22 +19,16 @@ pub fn specs() -> Vec { } /// A raw shape the merge can take: any fill (solid, gradient or bitmap: the paint is carried -/// into each piece, ADR 0042) or none, and a stroke of one width or none. A width profile runs -/// along the whole stroke, so cutting it would need its length carried through the merge; those -/// strokes stay whole, as objects, for now. +/// into each piece, ADR 0042) or none, and any stroke or none. A stroke's width profile is +/// carried into each piece of it (ADR 0093): the merge says which stretch of the stroke each +/// piece runs along, and the piece keeps the widths it had there. pub(crate) fn mergeable(e: &Element) -> Option<&Shape> { match &e.kind { - ElementKind::Shape(s) if s.merge && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s), + ElementKind::Shape(s) if s.merge => Some(s), _ => None, } } -/// Whether a new shape with this style can join the drawing (strokes with a width profile are -/// drawn as objects for now). -pub(crate) fn can_merge(stroke: Option<&Stroke>) -> bool { - stroke.is_none_or(|st| st.profile.is_none()) -} - pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect { let pad = s.stroke.as_ref().map_or(0.0, Stroke::reach) * m.mean_scale(); s.path.bounds().transformed(m).inflate(pad + 2.0 * SNAP) @@ -140,6 +134,9 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt // Style tables: equal entries are one style to the merge. let mut fills: Vec<(Paint, ColorEffect)> = Vec::new(); let mut strokes: Vec<(Stroke, ColorEffect)> = Vec::new(); + // A stroke with a width profile is a style of its own (its pieces never chain into another + // stroke's), with the path its profile runs along (an index into `paths`). + let mut profiled: Vec<(u32, usize)> = Vec::new(); let mut paths: Vec = Vec::with_capacity(parts.len()); let mut styles: Vec<(Option, Option, anicraft_geom::FillRule)> = Vec::with_capacity(parts.len()); let mut marked: Vec = Vec::with_capacity(parts.len()); @@ -151,7 +148,17 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt // Gradients and bitmaps are placed in keyframe space, so every piece shows its // part of the paint where it was. let fill = sh.fill.as_ref().map(|f| fill_index(&mut fills, (f.transformed(&e.transform), e.color))); - let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (st.scaled(e.transform.mean_scale()), e.color))); + let stroke = sh.stroke.clone().map(|st| { + let st = (st.scaled(e.transform.mean_scale()), e.color); + if st.0.profile.is_some() { + strokes.push(st); + let i = (strokes.len() - 1) as u32; + profiled.push((i, paths.len() - 1)); + i + } else { + index_of(&mut strokes, st) + } + }); styles.push((fill, stroke, sh.fill_rule)); marked.push(*mark); } @@ -178,7 +185,12 @@ fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Opt (Some(f.clone()), None, *c) } else { let Some((st, c)) = strokes.get(piece.style as usize) else { continue }; - (None, Some(st.clone()), *c) + let mut st = st.clone(); + // Each piece of a variable-width stroke keeps the widths it had (ADR 0093). + if let (Some(profile), Some(path)) = (&st.profile, profiled.iter().find(|(i, _)| *i == piece.style).and_then(|(_, p)| paths.get(*p))) { + st.profile = profile.along(path, &piece.spans); + } + (None, Some(st), *c) }; // Local origin at the centre of the piece, as the drawing tools place shapes. let c = piece.path.bounds().center(); diff --git a/crates/engine/src/rawsub_tests.rs b/crates/engine/src/rawsub_tests.rs index 6c8c003b..7442dca4 100644 --- a/crates/engine/src/rawsub_tests.rs +++ b/crates/engine/src/rawsub_tests.rs @@ -322,11 +322,11 @@ fn gradient_fills_take_part_in_the_merge() { run(&mut s, "draw.rect", json!({"x": 50, "y": 25, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null})); let g = fills(&s).into_iter().find(|e| fill_color(e).is_none()).unwrap(); assert!((area(&g) - (20_000.0 - 2_500.0)).abs() < 1.0); - // A width profile still makes an object. + // A width profile is raw too (ADR 0093: the merge carries it into each piece). let mut t = raw_session(); t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth); run(&mut t, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0})); - assert!(raw(&t).is_empty()); + assert_eq!(raw(&t).len(), 1); let _ = Affine::IDENTITY; } diff --git a/crates/geom/src/planar.rs b/crates/geom/src/planar.rs index b52c3e6e..f8ec0da3 100644 --- a/crates/geom/src/planar.rs +++ b/crates/geom/src/planar.rs @@ -55,6 +55,19 @@ pub struct Piece { pub item: usize, /// Inside the cutter ([`merge_cut`]); always false from [`merge`]. pub inside: bool, + /// For a stroke piece: the stretches of its items' paths it runs along, in order, each as + /// `[from, to]` in path positions (see [`Piece::position`]); `to < from` where it runs + /// backwards. What a width profile needs to follow its stroke into each piece (ADR 0093). + /// Empty for fills. + pub spans: Vec<[f64; 2]>, +} + +impl Piece { + /// A place on an item's path as a path position: `k + t` is parameter `t` along the segment + /// that command `k` draws (a `Close` draws the closing line). + pub fn position(cmd: usize, t: f64) -> f64 { + cmd as f64 + t.clamp(0.0, 1.0) + } } #[derive(Clone, Debug, Default, PartialEq)] @@ -296,6 +309,15 @@ struct Seg { line: bool, item: usize, stroke: bool, + /// Its ends as path positions on its item ([`Piece::position`]). + pos: [f64; 2], +} + +impl Seg { + /// Path position of parameter `t`. + fn at(&self, t: f64) -> f64 { + self.pos[0] + (self.pos[1] - self.pos[0]) * t + } } /// Every segment of every item. A filled subpath left open gets its closing edge (unstroked). @@ -306,31 +328,32 @@ fn collect(items: &[Item]) -> Option> { continue; } let stroke = it.stroke.is_some(); - let mut push = |c: Cubic, line: bool, stroke: bool| { + let mut push = |c: Cubic, line: bool, stroke: bool, k: usize| { if !c.iter().all(|p| p.finite()) || hull_len(&c) <= 1e-9 { return; } + let k = k as f64; // A segment that comes back to where it began (a loop) is two, so no edge is a loop. if c[0].dist(c[3]) < TOL && hull_len(&c) > 2.0 * TOL { let (a, b) = split(&c, 0.5); - segs.push(Seg { c: a, line, item, stroke }); - segs.push(Seg { c: b, line, item, stroke }); + segs.push(Seg { c: a, line, item, stroke, pos: [k, k + 0.5] }); + segs.push(Seg { c: b, line, item, stroke, pos: [k + 0.5, k + 1.0] }); } else { - segs.push(Seg { c, line, item, stroke }); + segs.push(Seg { c, line, item, stroke, pos: [k, k + 1.0] }); } }; let (mut start, mut last) = (P::default(), P::default()); let (mut open, mut drawn) = (false, false); - let close = |push: &mut dyn FnMut(Cubic, bool, bool), last: P, start: P, stroked: bool| { + let close = |push: &mut dyn FnMut(Cubic, bool, bool, usize), last: P, start: P, stroked: bool, k: usize| { if last.dist(start) > 0.0 { - push(line_cubic(last, start), true, stroked); + push(line_cubic(last, start), true, stroked, k); } }; - for cmd in &it.path.cmds { + for (k, cmd) in it.path.cmds.iter().enumerate() { let to = match *cmd { PathCmd::MoveTo(p) => { if open && drawn && it.fill.is_some() { - close(&mut push, last, start, false); + close(&mut push, last, start, false, k); } start = P::of(p); last = start; @@ -339,7 +362,7 @@ fn collect(items: &[Item]) -> Option> { } PathCmd::Close => { if open { - close(&mut push, last, start, stroke); + close(&mut push, last, start, stroke, k); } last = start; (open, drawn) = (false, false); @@ -352,12 +375,12 @@ fn collect(items: &[Item]) -> Option> { } PathCmd::CubicTo(a, b, p) => ([last, P::of(a), P::of(b), P::of(p)], false), }; - push(to.0, to.1, stroke); + push(to.0, to.1, stroke, k); last = to.0[3]; (open, drawn) = (true, true); } if open && drawn && it.fill.is_some() { - close(&mut push, last, start, false); + close(&mut push, last, start, false, it.path.cmds.len()); } if segs.len() > MAX_SEGMENTS { return None; @@ -820,7 +843,7 @@ impl Map { None => { let (style, item, inside) = top.get(&g).copied().unwrap_or((0, 0, false)); piece_of.insert(g, out.fills.len()); - out.fills.push(Piece { style, path, item, inside }); + out.fills.push(Piece { style, path, item, inside, spans: Vec::new() }); } } } @@ -877,17 +900,24 @@ impl Map { let item = halves.iter().filter_map(|&h| stroke_of[h / 2]).max().unwrap_or(0); // A run along the cutter's edge counts as inside it. let inside = halves.iter().any(|&h| cut_edge[h / 2]) || halves.get(halves.len() / 2).is_some_and(|&h| cutter.covers(eval(&self.curve(h), 0.5), FillRule::EvenOdd)); - out.strokes.push(Piece { style: st, path: self.emit(&halves, closed, segs), item, inside }); + let (path, spans) = self.emit_spans(&halves, closed, segs); + out.strokes.push(Piece { style: st, path, item, inside, spans }); } } /// A subpath along `halves`: pieces of one segment joined back, straight runs made one line. fn emit(&self, halves: &[Half], closed: bool, segs: &[Seg]) -> Path { + self.emit_spans(halves, closed, segs).0 + } + + /// [`Map::emit`], with the stretches of the items' paths the subpath runs along. + fn emit_spans(&self, halves: &[Half], closed: bool, segs: &[Seg]) -> (Path, Vec<[f64; 2]>) { let mut runs: Vec = Vec::new(); for &h in halves { let e = &self.edges[h / 2]; let (t0, t1) = if h.is_multiple_of(2) { (e.t[0], e.t[1]) } else { (e.t[1], e.t[0]) }; - let run = Run { c: self.curve(h), line: e.line, src: e.src, t: [t0, t1] }; + let spans = segs.get(e.src).map(|s| vec![[s.at(t0), s.at(t1)]]).unwrap_or_default(); + let run = Run { c: self.curve(h), line: e.line, src: e.src, t: [t0, t1], spans }; match runs.last_mut().and_then(|last| last.join(&run, segs)) { Some(j) => { if let Some(last) = runs.last_mut() { @@ -918,10 +948,35 @@ impl Map { if closed && !runs.is_empty() { path.close(); } - path + let mut spans: Vec<[f64; 2]> = Vec::new(); + for sp in runs.into_iter().flat_map(|r| r.spans) { + push_span(&mut spans, sp); + } + (path, spans) } } +/// Adds `sp` to `spans`, extending the last one when `sp` carries straight on from it. +fn push_span(spans: &mut Vec<[f64; 2]>, sp: [f64; 2]) { + if let Some(last) = spans.last_mut() + && (last[1] - sp[0]).abs() < 1e-9 + && (last[1] >= last[0]) == (sp[1] >= sp[0]) + { + last[1] = sp[1]; + return; + } + spans.push(sp); +} + +/// Two runs' spans, one after the other. +fn joined(a: &[[f64; 2]], b: &[[f64; 2]]) -> Vec<[f64; 2]> { + let mut out = a.to_vec(); + for &sp in b { + push_span(&mut out, sp); + } + out +} + struct Faces { face_of_half: Vec>, /// A point inside each face. @@ -934,6 +989,8 @@ struct Run { line: bool, src: usize, t: [f64; 2], + /// The stretches of item paths it covers ([`Piece::spans`]). + spans: Vec<[f64; 2]>, } impl Run { @@ -943,14 +1000,14 @@ impl Run { if self.src == o.src && self.t[1] == o.t[0] && forward(self) == forward(o) && self.src != usize::MAX { let s = segs.get(self.src)?; let c = pinned(&sub(&s.c, self.t[0], o.t[1]), self.line, self.c[0], o.c[3]); - return Some(Run { c, line: self.line, src: self.src, t: [self.t[0], o.t[1]] }); + return Some(Run { c, line: self.line, src: self.src, t: [self.t[0], o.t[1]], spans: joined(&self.spans, &o.spans) }); } if self.line && o.line { let (a, b, c) = (self.c[0], self.c[3], o.c[3]); let d = c.sub(a); let l = d.len(); if l > 1e-9 && (d.cross(b.sub(a)) / l).abs() < 0.01 && d.dot(b.sub(a)) > 0.0 && d.dot(c.sub(b)) > 0.0 { - return Some(Run { c: line_cubic(a, c), line: true, src: usize::MAX, t: [0.0, 0.0] }); + return Some(Run { c: line_cubic(a, c), line: true, src: usize::MAX, t: [0.0, 0.0], spans: joined(&self.spans, &o.spans) }); } } None diff --git a/crates/geom/src/planar_tests.rs b/crates/geom/src/planar_tests.rs index a951c2ba..c4aeaf19 100644 --- a/crates/geom/src/planar_tests.rs +++ b/crates/geom/src/planar_tests.rs @@ -370,3 +370,31 @@ fn intersect_clips_to_the_region() { let want = std::f32::consts::PI * 100.0 / 4.0; assert!((area(&quarter) - want).abs() < want * 0.002, "{} vs {want}", area(&quarter)); } + +#[test] +fn stroke_pieces_say_which_stretch_of_their_path_they_run_along() { + // A line from x 0 to 100, crossed by another at x 30 (crossings start new pieces): its two + // pieces run along positions 1.0..1.3 and 1.3..2.0 (command 1 draws it). + let a = Path::line(Vec2::new(0.0, 0.0), Vec2::new(100.0, 0.0)); + let b = Path::line(Vec2::new(30.0, -50.0), Vec2::new(30.0, 50.0)); + let m = run(&[stroked(&a, None, 1), stroked(&b, None, 2)]); + let mut spans: Vec<[f64; 2]> = m.strokes.iter().filter(|p| p.item == 0).flat_map(|p| p.spans.clone()).collect(); + spans.sort_by(|x, y| x[0].min(x[1]).total_cmp(&y[0].min(y[1]))); + assert_eq!(spans.len(), 2, "{m:?}"); + let lo = |s: [f64; 2]| s[0].min(s[1]); + let hi = |s: [f64; 2]| s[0].max(s[1]); + assert!((lo(spans[0]) - 1.0).abs() < 1e-6 && (hi(spans[0]) - 1.3).abs() < 1e-3, "{spans:?}"); + assert!((lo(spans[1]) - 1.3).abs() < 1e-3 && (hi(spans[1]) - 2.0).abs() < 1e-6, "{spans:?}"); + // A polyline uncut keeps one span over all its segments, and fills carry none. + let mut z = Path::new(); + z.move_to(Vec2::new(0.0, 0.0)); + z.line_to(Vec2::new(50.0, 0.0)); + z.cubic_to(Vec2::new(70.0, 0.0), Vec2::new(90.0, 5.0), Vec2::new(100.0, 20.0)); + let r = rect(200.0, 0.0, 10.0, 10.0); + let m = run(&[stroked(&z, None, 1), fill(&r, 3)]); + assert_eq!(m.strokes.len(), 1); + let sp = &m.strokes[0].spans; + assert_eq!(sp.len(), 1, "{sp:?}"); + assert!((lo(sp[0]) - 1.0).abs() < 1e-9 && (hi(sp[0]) - 3.0).abs() < 1e-9, "{sp:?}"); + assert!(m.fills.iter().all(|f| f.spans.is_empty())); +}