Skip to content

armgit / klad

Public Imported from GitHub
0

A drawing app built for agent/human collaboration

Rust

Eraser, smudge and blender strokes attach to the marks under them

Indicode BVb639e81331f8
diff --git a/crates/app/src/editor.rs b/crates/app/src/editor.rs
index 5f6aaf7..8de8048 100644
--- a/crates/app/src/editor.rs
+++ b/crates/app/src/editor.rs
@@ -2863,9 +2863,13 @@ impl Editor {
let brush = live.stroke.brush.clone();
let erasing = live.brush.blend == klad_brush::brush::StrokeBlend::Erase;
let blend = stroke_blend(&live.brush, live.stroke.lock).unwrap_or(live.brush.blend);
+ let attaching = Instant::now();
+ live.stroke.on = self.attaching(&live.stroke, &live.brush.def);
+ let attach = ms(attaching);
let mut touched = self.scene.commit_stroke(live.stroke, &mut self.buffer, blend)?;
if let Some((_, mut copy, _)) = live.twin {
copy.id = self.scene.next_mark_id();
+ copy.on = self.attaching(&copy, &live.brush.def);
touched.extend(self.scene.commit_stroke(copy, &mut self.mirror_buffer, blend)?);
}
let commit = ms(start);
@@ -2878,7 +2882,7 @@ impl Editor {
}
let count = self.scene.active_marks().len();
let text = format!(
- "{brush}: {samples} samples, {dabs} live dabs, {alone} B packed alone\nlayer file {bytes} B for {count} strokes and fills ({:.0} B each)\npen up {ended:.1} ms{}, commit {commit:.1} ms, save {:.1} ms",
+ "{brush}: {samples} samples, {dabs} live dabs, {alone} B packed alone\nlayer file {bytes} B for {count} strokes and fills ({:.0} B each)\npen up {ended:.1} ms{}, attach {attach:.1} ms, commit {commit:.1} ms, save {:.1} ms",
bytes as f64 / count.max(1) as f64,
if repainted { " (tapered repaint)" } else { "" },
ms(saving)
@@ -2887,6 +2891,14 @@ impl Editor {
Ok(())
}
+ fn attaching(&self, stroke: &Stroke, def: &BrushDef) -> Vec<u32> {
+ let marks = self.scene.active_marks();
+ klad_core::attach::targets(marks, marks.len(), stroke, |id| match id == stroke.brush {
+ true => Some(def),
+ false => self.brushes.def(id).or_else(|| self.embedded.get(id)),
+ })
+ }
+
fn set_colour(&mut self, rgba: [f32; 4]) {
self.color = rgba;
self.hsva = Hsva::from_rgba(rgba, self.hsva.h);
diff --git a/crates/app/src/editor/ui_tests.rs b/crates/app/src/editor/ui_tests.rs
index 7ce4df6..f6f3e17 100644
--- a/crates/app/src/editor/ui_tests.rs
+++ b/crates/app/src/editor/ui_tests.rs
@@ -1935,6 +1935,40 @@ fn recolouring_several_strokes_keeps_each_ones_shade() {
let _ = std::fs::remove_dir_all(&path);
}
+fn pen_line(h: &mut Harness<'static, Editor>, a: egui::Pos2, b: egui::Pos2) {
+ h.hover_at(a);
+ h.run_steps(1);
+ h.drag_at(a);
+ h.run_steps(1);
+ (1..=8).for_each(|i| {
+ h.hover_at(a + (b - a) * (i as f32 / 8.0));
+ h.run_steps(1);
+ });
+ h.drop_at(b);
+ h.run_steps(3);
+}
+
+#[test]
+fn an_eraser_drawn_in_the_editor_attaches_to_the_strokes_it_crossed() {
+ let path = sample("attach");
+ let mut h = harness(editor(&path), vec2(1440.0, 900.0));
+ activate(&mut h, "notes");
+ let c = h.state().canvas_rect.center();
+ pen_line(&mut h, c + vec2(-80.0, 0.0), c + vec2(80.0, 0.0));
+ pen_line(&mut h, c + vec2(-80.0, 120.0), c + vec2(80.0, 120.0));
+ h.key_press(Key::E);
+ h.run_steps(2);
+ pen_line(&mut h, c + vec2(0.0, -30.0), c + vec2(0.0, 30.0));
+ let marks = h.state().scene.active_marks().to_vec();
+ assert_eq!(marks.len(), 3);
+ assert_eq!(
+ marks[2].as_stroke().unwrap().on,
+ vec![marks[0].id()],
+ "the eraser holds the line it crossed, not the one below"
+ );
+ let _ = std::fs::remove_dir_all(&path);
+}
+
#[test]
fn a_checkout_under_the_open_editor_shows_the_drawing_it_brings() {
let path = sample("checkout");
diff --git a/crates/brush/src/replay.rs b/crates/brush/src/replay.rs
index 25a6341..070a871 100644
--- a/crates/brush/src/replay.rs
+++ b/crates/brush/src/replay.rs
@@ -4,7 +4,6 @@ use crate::fill::{fill_tiles, paint_fill_where};
use crate::tiles::{Raster, StrokeBuffer, TILE, TILE_PX, Tile};
use anyhow::Result;
use half::f16;
-use klad_core::brushes::Curve;
use klad_core::stroke::{Mark, Sample, Stroke, fingerprint};
use rayon::prelude::*;
use std::collections::{BTreeMap, BTreeSet};
@@ -54,12 +53,9 @@ fn painted(
}
fn reach(stroke: &Stroke, brushes: &BrushSet) -> Option<f32> {
- let def = brushes.def(&stroke.brush)?;
- let most = |c: Option<Curve>| c.map_or(1.0, |c| c.min.abs().max(c.max.abs()));
- let size = &def.dynamics.size;
- let radius =
- 0.5 * stroke.size * most(size.pressure) * most(size.tilt) * most(size.speed) * (1.0 + def.jitter.size.abs());
- Some((radius.max(0.6) * (1.0 + 2.0 * def.jitter.scatter.abs()) + 2.0) * 1.25)
+ brushes
+ .def(&stroke.brush)
+ .map(|def| klad_core::attach::reach(stroke, def))
}
fn guess(raster: &Raster, brushes: &BrushSet, mark: &Mark) -> Vec<usize> {
diff --git a/crates/brush/tests/edit_time.rs b/crates/brush/tests/edit_time.rs
index 4a33434..423e0c5 100644
--- a/crates/brush/tests/edit_time.rs
+++ b/crates/brush/tests/edit_time.rs
@@ -19,7 +19,11 @@ fn edit_time() {
let (w, h) = (bundle.doc.canvas.width, bundle.doc.canvas.height);
let start = Instant::now();
let (mut replay, mut raster, _) = CelReplay::replay(w, h, marks.clone(), &brushes).unwrap();
- println!("replay in order: {:.0} ms for {} marks", start.elapsed().as_secs_f64() * 1000.0, marks.len());
+ println!(
+ "replay in order: {:.0} ms for {} marks",
+ start.elapsed().as_secs_f64() * 1000.0,
+ marks.len()
+ );
let mut current = marks;
let times: Vec<(f64, usize, bool)> = [6.0f32, -6.0, 6.0, -6.0, 6.0]
.iter()
@@ -46,3 +50,39 @@ fn edit_time() {
times[0].2
);
}
+
+#[test]
+#[ignore]
+fn attach_time() {
+ let Ok(path) = std::env::var("KLAD_EDIT_BUNDLE") else {
+ eprintln!("set KLAD_EDIT_BUNDLE and KLAD_EDIT_LAYER");
+ return;
+ };
+ let layer = std::env::var("KLAD_EDIT_LAYER").unwrap();
+ let bundle = Bundle::open(&path).unwrap();
+ let brushes = BrushSet::for_bundle(&bundle).unwrap();
+ let owner = bundle.doc.layer(&layer).unwrap();
+ let cel = owner.content_at(0).unwrap().id.clone();
+ let marks = bundle.read_marks(&layer, &cel).unwrap();
+ let probes: Vec<(usize, klad_core::stroke::Stroke)> = marks
+ .iter()
+ .enumerate()
+ .filter_map(|(i, m)| m.as_stroke().map(|s| (i, s)))
+ .filter(|(_, s)| brushes.def(&s.brush).and_then(klad_core::attach::modifier).is_some())
+ .map(|(i, s)| (i, s.clone()))
+ .collect();
+ probes.iter().for_each(|(at, stroke)| {
+ let start = Instant::now();
+ let found = (0..5)
+ .map(|_| klad_core::attach::targets(&marks, *at, stroke, |id| brushes.def(id)).len())
+ .fold(0, |_, n| n);
+ println!(
+ "attach {} ({}, size {:.0}) over {} earlier marks: {:.2} ms, {found} targets",
+ klad_core::markedit::address(&cel, stroke.id),
+ stroke.brush,
+ stroke.size,
+ at,
+ start.elapsed().as_secs_f64() * 1000.0 / 5.0
+ );
+ });
+}
diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs
index 0b9d62b..403d5e5 100644
--- a/crates/cli/src/main.rs
+++ b/crates/cli/src/main.rs
@@ -3845,8 +3845,36 @@ fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> R
let strokes: Vec<_> = strokes_of(&marks).collect();
let fills: Vec<_> = fills_of(&marks).collect();
if as_json {
- let list: Vec<serde_json::Value> = strokes.iter().map(|s| stroke_json(&cel.id, s, true)).collect();
- let fills: Vec<serde_json::Value> = fills.iter().map(|f| fill_json(&cel.id, f)).collect();
+ let attached = klad_core::attach::attached(&marks);
+ let links = |value: &mut serde_json::Value, id: u32, on: Vec<u32>| {
+ let addresses = |ids: &[u32]| {
+ ids.iter()
+ .map(|i| klad_core::markedit::address(&cel.id, *i))
+ .collect::<Vec<_>>()
+ };
+ if !on.is_empty() {
+ value["on"] = serde_json::json!(addresses(&on));
+ }
+ if let Some(by) = attached.get(&id) {
+ value["attached"] = serde_json::json!(addresses(by));
+ }
+ };
+ let list: Vec<serde_json::Value> = strokes
+ .iter()
+ .map(|s| {
+ let mut value = stroke_json(&cel.id, s, true);
+ links(&mut value, s.id, klad_core::attach::live_on(&marks, s));
+ value
+ })
+ .collect();
+ let fills: Vec<serde_json::Value> = fills
+ .iter()
+ .map(|f| {
+ let mut value = fill_json(&cel.id, f);
+ links(&mut value, f.id, Vec::new());
+ value
+ })
+ .collect();
println!(
"{}",
serde_json::json!({ "cel": cel.id, "strokes": list, "fills": fills, "order": marks.iter().map(|m| m.id()).collect::<Vec<_>>(), "parts": cel.parts })
@@ -3862,8 +3890,26 @@ fn strokes(path: &Path, layer: &str, frame: u32, after: u32, as_json: bool) -> R
if !strokes.is_empty() {
println!("id author brush size samples ms Hz pressure tilt bounds");
}
+ let attached = klad_core::attach::attached(&marks);
+ let names = |ids: &[u32]| {
+ ids.iter()
+ .map(|i| klad_core::doc::mark_name(*i))
+ .collect::<Vec<_>>()
+ .join(" ")
+ };
strokes.iter().for_each(|s| {
- let part = cel.part_of(s.id).map_or(String::new(), |p| format!(" part {p}"));
+ let on = klad_core::attach::live_on(&marks, s);
+ let part = [
+ cel.part_of(s.id).map_or(String::new(), |p| format!(" part {p}")),
+ match on.is_empty() {
+ true => String::new(),
+ false => format!(" on {}", names(&on)),
+ },
+ attached
+ .get(&s.id)
+ .map_or(String::new(), |by| format!(" attached {}", names(by))),
+ ]
+ .concat();
let ms: u32 = s.samples.iter().map(|v| v.dt_ms as u32).sum();
let hz = s.samples.len().saturating_sub(1) as f64 / (ms.max(1) as f64 / 1000.0);
let (lo, hi) = s.samples.iter().fold((f32::MAX, 0.0f32), |(lo, hi), v| {
diff --git a/crates/cli/tests/binary.rs b/crates/cli/tests/binary.rs
index 66c2438..8cba3cd 100644
--- a/crates/cli/tests/binary.rs
+++ b/crates/cli/tests/binary.rs
@@ -457,3 +457,37 @@ fn recolour_moves_strokes_together_and_keeps_their_shades() {
assert_eq!(log.matches("cli").count(), 3, "one history step: {log}");
std::fs::remove_dir_all(&dir).unwrap();
}
+
+#[test]
+fn an_eraser_stroke_attaches_to_the_lines_it_crosses_and_says_so() {
+ let dir = std::env::temp_dir().join(format!("draw-binary-attach-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ let bundle = dir.join("a.klad");
+ let path = bundle.to_str().unwrap();
+ let draw = |args: &[&str]| {
+ let out = Command::new(env!("CARGO_BIN_EXE_klad")).args(args).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ String::from_utf8_lossy(&out.stdout).to_string()
+ };
+ draw(&["new", path, "--width", "200", "--height", "100"]);
+ draw(&["stroke", path, "l1", "--path", "M10 20 L190 20"]);
+ draw(&["stroke", path, "l1", "--path", "M10 80 L190 80"]);
+ draw(&[
+ "stroke",
+ path,
+ "l1",
+ "--brush",
+ "eraser",
+ "--size",
+ "12",
+ "--path",
+ "M100 5 L100 35",
+ ]);
+ let listed: serde_json::Value = serde_json::from_str(&draw(&["strokes", path, "l1", "--json"])).unwrap();
+ let strokes = listed["strokes"].as_array().unwrap();
+ assert_eq!(strokes[2]["on"], serde_json::json!(["c2:s1"]));
+ assert_eq!(strokes[0]["attached"], serde_json::json!(["c2:s3"]));
+ assert!(strokes[1].get("attached").is_none());
+ assert!(draw(&["strokes", path, "l1"]).contains("on s1"));
+ std::fs::remove_dir_all(&dir).unwrap();
+}
diff --git a/crates/core/src/attach.rs b/crates/core/src/attach.rs
new file mode 100644
index 0000000..2f6a9a3
--- /dev/null
+++ b/crates/core/src/attach.rs
@@ -0,0 +1,365 @@
+use crate::brushes::{BrushBlend, BrushDef, Curve, PaintDef};
+use crate::fill::Fill;
+use crate::stroke::{Mark, Sample, Stroke};
+use std::collections::{BTreeMap, BTreeSet};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Modifier {
+ Erase,
+ Smudge,
+ Blend,
+}
+
+pub fn modifier(def: &BrushDef) -> Option<Modifier> {
+ match (def.blend, def.paint) {
+ (BrushBlend::Erase, _) => Some(Modifier::Erase),
+ (_, Some(PaintDef::Smudge { .. })) => Some(Modifier::Smudge),
+ (_, Some(PaintDef::Blend { .. })) => Some(Modifier::Blend),
+ _ => None,
+ }
+}
+
+pub fn reach(stroke: &Stroke, def: &BrushDef) -> f32 {
+ let most = |c: Option<Curve>| c.map_or(1.0, |c| c.min.abs().max(c.max.abs()));
+ let size = &def.dynamics.size;
+ let radius =
+ 0.5 * stroke.size * most(size.pressure) * most(size.tilt) * most(size.speed) * (1.0 + def.jitter.size.abs());
+ (radius.max(0.6) * (1.0 + 2.0 * def.jitter.scatter.abs()) + 2.0) * 1.25
+}
+
+type P = (f32, f32);
+
+struct Shape {
+ segments: Vec<[P; 2]>,
+ radius: f32,
+ bounds: [f32; 4],
+}
+
+impl Shape {
+ fn of(stroke: &Stroke, radius: f32) -> Option<Self> {
+ let points: Vec<P> = stroke.samples.iter().map(Sample::pos).collect();
+ let first = *points.first()?;
+ let segments = match points.len() {
+ 1 => vec![[first, first]],
+ _ => points.windows(2).map(|w| [w[0], w[1]]).collect(),
+ };
+ let bounds = points.iter().fold([first.0, first.1, first.0, first.1], |b, p| {
+ [b[0].min(p.0), b[1].min(p.1), b[2].max(p.0), b[3].max(p.1)]
+ });
+ Some(Self {
+ segments,
+ radius,
+ bounds,
+ })
+ }
+
+ fn padded(&self, pad: f32) -> [f32; 4] {
+ let [x0, y0, x1, y1] = self.bounds;
+ [x0 - pad, y0 - pad, x1 + pad, y1 + pad]
+ }
+}
+
+fn overlap(a: [f32; 4], b: [f32; 4]) -> bool {
+ a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3]
+}
+
+fn to_segment(p: P, [a, b]: [P; 2]) -> f32 {
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let len2 = dx * dx + dy * dy;
+ let t = match len2 > 0.0 {
+ true => (((p.0 - a.0) * dx + (p.1 - a.1) * dy) / len2).clamp(0.0, 1.0),
+ false => 0.0,
+ };
+ let (x, y) = (a.0 + t * dx - p.0, a.1 + t * dy - p.1);
+ (x * x + y * y).sqrt()
+}
+
+fn cross(o: P, a: P, b: P) -> f32 {
+ (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0)
+}
+
+fn between(s: [P; 2], t: [P; 2]) -> f32 {
+ let crossed = cross(s[0], s[1], t[0]) * cross(s[0], s[1], t[1]) < 0.0
+ && cross(t[0], t[1], s[0]) * cross(t[0], t[1], s[1]) < 0.0;
+ match crossed {
+ true => 0.0,
+ false => to_segment(s[0], t)
+ .min(to_segment(s[1], t))
+ .min(to_segment(t[0], s))
+ .min(to_segment(t[1], s)),
+ }
+}
+
+struct Grid {
+ cell: f32,
+ cells: BTreeMap<(i32, i32), Vec<usize>>,
+ shape: Shape,
+}
+
+impl Grid {
+ fn new(shape: Shape) -> Self {
+ let cell = shape.radius.max(8.0);
+ let mut cells: BTreeMap<(i32, i32), Vec<usize>> = BTreeMap::new();
+ shape.segments.iter().enumerate().for_each(|(i, [a, b])| {
+ let [x0, y0, x1, y1] = [a.0.min(b.0), a.1.min(b.1), a.0.max(b.0), a.1.max(b.1)];
+ let (cx0, cy0, cx1, cy1) = (
+ (x0 / cell).floor() as i32,
+ (y0 / cell).floor() as i32,
+ (x1 / cell).floor() as i32,
+ (y1 / cell).floor() as i32,
+ );
+ (cy0..=cy1).for_each(|cy| (cx0..=cx1).for_each(|cx| cells.entry((cx, cy)).or_default().push(i)));
+ });
+ Self { cell, cells, shape }
+ }
+
+ fn near(&self, segment: [P; 2], pad: f32) -> bool {
+ let limit = self.shape.radius + pad;
+ let [a, b] = segment;
+ let reach = |v: f32, lo: bool| match lo {
+ true => ((v - limit) / self.cell).floor() as i32,
+ false => ((v + limit) / self.cell).floor() as i32,
+ };
+ let (cx0, cy0, cx1, cy1) = (
+ reach(a.0.min(b.0), true),
+ reach(a.1.min(b.1), true),
+ reach(a.0.max(b.0), false),
+ reach(a.1.max(b.1), false),
+ );
+ (cy0..=cy1).any(|cy| {
+ (cx0..=cx1).any(|cx| {
+ self.cells
+ .get(&(cx, cy))
+ .is_some_and(|found| found.iter().any(|&i| between(segment, self.shape.segments[i]) <= limit))
+ })
+ })
+ }
+
+ fn touches_stroke(&self, stroke: &Stroke, radius: f32) -> bool {
+ Shape::of(stroke, radius).is_some_and(|other| {
+ overlap(self.shape.padded(self.shape.radius), other.padded(radius))
+ && other.segments.iter().any(|s| self.near(*s, radius))
+ })
+ }
+
+ fn touches_fill(&self, fill: &Fill) -> bool {
+ let c = &fill.coverage;
+ let Some(box_) = c.bounds() else {
+ return false;
+ };
+ let [x0, y0, x1, y1] = self.shape.padded(self.shape.radius + 1.0);
+ if !overlap(box_, [x0, y0, x1, y1]) {
+ return false;
+ }
+ let (fx0, fy0) = (x0.max(box_[0]).floor() as u32, y0.max(box_[1]).floor() as u32);
+ let (fx1, fy1) = (x1.min(box_[2]).ceil() as u32, y1.min(box_[3]).ceil() as u32);
+ (fy0..fy1).any(|y| {
+ (fx0..fx1).any(|x| {
+ c.at(x, y) > 0 && {
+ let p = (x as f32 + 0.5, y as f32 + 0.5);
+ self.near([p, p], 0.75)
+ }
+ })
+ })
+ }
+}
+
+fn radius_of<'a>(stroke: &Stroke, def_of: &impl Fn(&str) -> Option<&'a BrushDef>) -> f32 {
+ def_of(&stroke.brush).map_or(stroke.size * 0.5 + 2.0, |def| reach(stroke, def))
+}
+
+fn plain_near<'a>(earlier: &[Mark], grid: &Grid, def_of: &impl Fn(&str) -> Option<&'a BrushDef>) -> Vec<u32> {
+ earlier
+ .iter()
+ .filter(|m| match m {
+ Mark::Fill(f) => grid.touches_fill(f),
+ Mark::Stroke(s) => {
+ def_of(&s.brush).and_then(modifier).is_none() && grid.touches_stroke(s, radius_of(s, def_of))
+ }
+ })
+ .map(Mark::id)
+ .collect()
+}
+
+pub fn targets<'a>(
+ marks: &[Mark],
+ before: usize,
+ stroke: &Stroke,
+ def_of: impl Fn(&str) -> Option<&'a BrushDef>,
+) -> Vec<u32> {
+ let Some(def) = def_of(&stroke.brush).filter(|d| modifier(d).is_some()) else {
+ return Vec::new();
+ };
+ let Some(shape) = Shape::of(stroke, reach(stroke, def)) else {
+ return Vec::new();
+ };
+ let grid = Grid::new(shape);
+ let earlier = &marks[..before.min(marks.len())];
+ let mut found: BTreeSet<u32> = plain_near(earlier, &grid, &def_of).into_iter().collect();
+ earlier.iter().enumerate().for_each(|(at, m)| {
+ let Some(s) = m.as_stroke() else {
+ return;
+ };
+ let reads = def_of(&s.brush)
+ .and_then(modifier)
+ .is_some_and(|k| k != Modifier::Erase);
+ if !reads || !grid.touches_stroke(s, radius_of(s, &def_of)) {
+ return;
+ }
+ match s.on.is_empty() {
+ false => found.extend(s.on.iter().copied()),
+ true => {
+ let Some(own) = def_of(&s.brush).and_then(|d| Shape::of(s, reach(s, d))) else {
+ return;
+ };
+ found.extend(plain_near(&earlier[..at], &Grid::new(own), &def_of));
+ }
+ }
+ });
+ let live: BTreeSet<u32> = earlier.iter().map(Mark::id).collect();
+ found.intersection(&live).copied().collect()
+}
+
+pub fn live_on(marks: &[Mark], stroke: &Stroke) -> Vec<u32> {
+ match stroke.on.is_empty() {
+ true => Vec::new(),
+ false => {
+ let live: BTreeSet<u32> = marks.iter().map(Mark::id).collect();
+ stroke.on.iter().copied().filter(|id| live.contains(id)).collect()
+ }
+ }
+}
+
+pub fn attached(marks: &[Mark]) -> BTreeMap<u32, Vec<u32>> {
+ let live: BTreeSet<u32> = marks.iter().map(Mark::id).collect();
+ let mut map: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
+ crate::stroke::strokes_of(marks).for_each(|s| {
+ s.on.iter()
+ .filter(|id| live.contains(id))
+ .for_each(|id| map.entry(*id).or_default().push(s.id))
+ });
+ map
+}
+
+pub fn attach<'a>(marks: &mut [Mark], at: usize, def_of: impl Fn(&str) -> Option<&'a BrushDef>) {
+ let on = match marks.get(at).and_then(Mark::as_stroke) {
+ Some(stroke) if stroke.on.is_empty() => targets(marks, at, stroke, &def_of),
+ _ => return,
+ };
+ if let Some(Mark::Stroke(stroke)) = marks.get_mut(at) {
+ stroke.on = on;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::brushes::library;
+ use crate::fill::{Coverage, FillSource};
+
+ fn defs() -> BTreeMap<String, BrushDef> {
+ ["ink", "eraser", "smudge", "blender", "wet", "airbrush"]
+ .iter()
+ .map(|id| (id.to_string(), library(id).unwrap()))
+ .collect()
+ }
+
+ fn line(id: u32, brush: &str, size: f32, from: P, to: P) -> Mark {
+ Stroke::new(id, brush, [0.1, 0.1, 0.1, 1.0], size, id)
+ .with_points(&[(from.0, from.1, 1.0), (to.0, to.1, 1.0)], 4.0)
+ .into()
+ }
+
+ fn found(marks: &[Mark], stroke: &Mark) -> Vec<u32> {
+ let defs = defs();
+ targets(marks, marks.len(), stroke.as_stroke().unwrap(), |id| defs.get(id))
+ }
+
+ #[test]
+ fn an_eraser_attaches_to_the_marks_under_it_and_never_to_later_ones() {
+ let marks = vec![
+ line(1, "ink", 6.0, (10.0, 50.0), (200.0, 50.0)),
+ line(2, "ink", 6.0, (10.0, 90.0), (200.0, 90.0)),
+ line(3, "ink", 6.0, (10.0, 300.0), (200.0, 300.0)),
+ ];
+ let eraser = line(4, "eraser", 12.0, (100.0, 30.0), (100.0, 110.0));
+ assert_eq!(
+ found(&marks, &eraser),
+ vec![1, 2],
+ "the two lines it crosses, not the far one"
+ );
+ let defs = defs();
+ assert_eq!(
+ targets(&marks, 1, eraser.as_stroke().unwrap(), |id| defs.get(id)),
+ vec![1],
+ "only marks before it in the order"
+ );
+ let far = line(5, "eraser", 12.0, (400.0, 400.0), (420.0, 420.0));
+ assert!(found(&marks, &far).is_empty(), "over nothing it attaches to nothing");
+ let paint = line(6, "ink", 12.0, (100.0, 30.0), (100.0, 110.0));
+ assert!(found(&marks, &paint).is_empty(), "paint strokes never attach");
+ }
+
+ #[test]
+ fn a_line_end_inside_the_eraser_counts_even_between_samples() {
+ let long = line(1, "ink", 4.0, (0.0, 0.0), (1000.0, 0.0));
+ let eraser = line(2, "eraser", 10.0, (500.0, -20.0), (500.0, 20.0));
+ assert_eq!(found(&[long], &eraser), vec![1]);
+ let near = line(3, "ink", 4.0, (0.0, 12.0), (1000.0, 12.0));
+ let dot = line(4, "eraser", 10.0, (500.0, 0.0), (500.0, 0.0));
+ assert_eq!(
+ found(&[near], &dot),
+ vec![3],
+ "generous: the brushes' reach, not their size"
+ );
+ }
+
+ #[test]
+ fn fills_count_by_their_pixels() {
+ let mut mask = vec![0u8; 200 * 200];
+ (50..60).for_each(|y| (50..150).for_each(|x| mask[y * 200 + x] = 255));
+ let fill: Mark = Fill::new(
+ 1,
+ [1.0, 0.0, 0.0, 1.0],
+ FillSource::Polygon(vec![[50.0, 50.0], [150.0, 50.0], [150.0, 60.0]]),
+ Coverage::from_mask(200, 200, &mask),
+ )
+ .into();
+ let over = line(2, "eraser", 8.0, (100.0, 40.0), (100.0, 70.0));
+ assert_eq!(found(std::slice::from_ref(&fill), &over), vec![1]);
+ let beside = line(3, "eraser", 8.0, (100.0, 80.0), (100.0, 120.0));
+ assert!(found(&[fill], &beside).is_empty());
+ }
+
+ #[test]
+ fn reaching_a_smear_takes_the_marks_the_smudge_moved() {
+ let leaf = line(1, "ink", 6.0, (0.0, 0.0), (40.0, 0.0));
+ let mut smudge = line(2, "smudge", 20.0, (40.0, 0.0), (120.0, 0.0));
+ if let Mark::Stroke(s) = &mut smudge {
+ s.on = vec![1];
+ }
+ let trim = line(3, "eraser", 10.0, (110.0, -20.0), (110.0, 20.0));
+ assert_eq!(
+ found(&[leaf.clone(), smudge], &trim),
+ vec![1],
+ "the smear is the leaf's paint, so trimming it attaches to the leaf"
+ );
+ let loose = line(2, "smudge", 20.0, (30.0, 0.0), (120.0, 0.0));
+ assert_eq!(
+ found(&[leaf, loose], &trim),
+ vec![1],
+ "an unattached smudge counts by what was under it"
+ );
+ }
+
+ #[test]
+ fn attach_fills_in_a_stroke_already_in_the_list() {
+ let defs = defs();
+ let mut marks = vec![
+ line(1, "ink", 6.0, (10.0, 50.0), (200.0, 50.0)),
+ line(2, "blender", 30.0, (60.0, 40.0), (80.0, 60.0)),
+ ];
+ attach(&mut marks, 1, |id| defs.get(id));
+ assert_eq!(marks[1].as_stroke().unwrap().on, vec![1]);
+ }
+}
diff --git a/crates/core/src/bundle.rs b/crates/core/src/bundle.rs
index cafe79b..e9e24b0 100644
--- a/crates/core/src/bundle.rs
+++ b/crates/core/src/bundle.rs
@@ -1,3 +1,4 @@
+use crate::attach;
use crate::brushes::{self, BrushDef};
use crate::doc::{Document, Layer, Loc};
use crate::here;
@@ -503,10 +504,35 @@ impl Bundle {
*made = markedit::paste(marks, copies, transform.as_ref(), cut.as_deref(), doc.mark_ids(cel))?;
Ok(())
}
+ MarkChange::Add(_) => {
+ let from = marks.len();
+ markedit::apply(marks, change, cel, doc.mark_ids(cel))?;
+ self.attach_added(marks, from)
+ }
_ => markedit::apply(marks, change, cel, doc.mark_ids(cel)),
}
}
+ pub fn brush_defs<'a>(&self, ids: impl IntoIterator<Item = &'a str>) -> Result<BTreeMap<String, BrushDef>> {
+ ids.into_iter()
+ .collect::<BTreeSet<&str>>()
+ .into_iter()
+ .filter_map(|id| self.brush(id).map(|def| def.map(|d| (id.to_string(), d))).transpose())
+ .collect()
+ }
+
+ fn attach_added(&self, marks: &mut [Mark], from: usize) -> Result<()> {
+ let added = self.brush_defs(strokes_of(&marks[from..]).map(|s| s.brush.as_str()))?;
+ let attaching = strokes_of(&marks[from..])
+ .any(|s| s.on.is_empty() && added.get(&s.brush).and_then(attach::modifier).is_some());
+ if !attaching {
+ return Ok(());
+ }
+ let defs = self.brush_defs(strokes_of(marks).map(|s| s.brush.as_str()))?;
+ (from..marks.len()).for_each(|at| attach::attach(marks, at, |id| defs.get(id)));
+ Ok(())
+ }
+
fn marks_after(
&self,
doc: &Document,
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index 1bac434..4b59039 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod attach;
pub mod brushes;
pub mod bundle;
pub mod color;
diff --git a/crates/core/src/stroke.rs b/crates/core/src/stroke.rs
index 3796352..e79a0c0 100644
--- a/crates/core/src/stroke.rs
+++ b/crates/core/src/stroke.rs
@@ -520,8 +520,10 @@ mod tests {
#[test]
fn attachments_round_trip_change_the_fingerprint_and_version_1_files_still_read() {
- let line = Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1).with_points(&[(1.0, 1.0, 1.0), (9.0, 2.0, 0.5)], 0.0);
- let free = Stroke::new(2, "eraser", [0.0, 0.0, 0.0, 1.0], 12.0, 2).with_points(&[(4.0, 0.0, 1.0), (4.0, 6.0, 1.0)], 0.0);
+ let line =
+ Stroke::new(1, "ink", [0.0, 0.0, 0.0, 1.0], 4.0, 1).with_points(&[(1.0, 1.0, 1.0), (9.0, 2.0, 0.5)], 0.0);
+ let free = Stroke::new(2, "eraser", [0.0, 0.0, 0.0, 1.0], 12.0, 2)
+ .with_points(&[(4.0, 0.0, 1.0), (4.0, 6.0, 1.0)], 0.0);
let attached = Stroke {
on: vec![1, 7 | (5 << 22), 3],
..free.clone()