Merge pull request #559 from storytold/fix/backlog-stage-tools

fix(brush): a long Brush stroke never freezes the window; Free Transform on a skewed symbol tested (M8)
This commit is contained in:
Tanish Manku authored and GitHub committed 2026-11-23 18:19:15 -07:00
commit 59b195bce7
20 files changed
+1056 -52

No files matched your search

+19
View File
@@ -2,6 +2,25 @@
## Unreleased
* **A long Brush stroke no longer freezes the window** (M8, ADR 0129, #519, backlog P-003).
* A stroke drawn for a long time, over itself again and again, took longer to turn into a
shape the longer it was, and a part of it selected over the rest cost seconds on every
frame. The outline's tracing is now bounded however long the stroke is (a fast scribble of
60 000 samples: 1.5 s before, 0.4 s now, of which the trace is at most 0.3 s), and the
selection's stipple is cut row by row (seconds a frame before, a few milliseconds now).
* In the editor a long stroke's outline is traced off the window's thread: the stroke stays
on the stage as you drew it, you can go on painting at once, and it becomes a shape, in
one undo step, a moment later. Anything else you do waits for it first, so strokes and
edits always happen in the order you made them.
* `anicraft-cli bench --stroke <samples>` measures a long stroke (painting, picking, moving,
the merge on deselect), and `bench --stroke-file <file>` a document's own artwork.
* Not yet: the Subselection tool, the Paint Bucket and the shape tools' snapping are still
slow on a single shape of ten thousand points and more.
* **Free Transform on a skewed symbol** (M8, #117, backlog P-005): scaling from a corner,
turning from outside it and skewing from an edge are now covered end to end by a test on a
slanted instance (the fix itself came with ADR 0111). The guide says what a handle scales
from (#193). Rotation on Windows and FreeBSD (#479) could not be reproduced on Windows 10
and stays open.
* **Documents too large to draw, shape-tween outlines on a guide, and small fixes from outside**
(M8, backlog P-002, P-011 and P-012; ADR 0128).
* **Security: no nesting of symbols hangs AniCraft.** The allowance of work one frame has
+101
View File
@@ -0,0 +1,101 @@
//! `bench --stroke`: what one long, fast, pressured Brush stroke costs (issue #519). The stroke
//! is painted, picked, moved, floated and deselected (which merges it into the drawing, ADR
//! 0122), and each step is timed. `--stroke-file` times the same steps on the artwork of a
//! document instead, so a reported file can be measured as it is.
use crate::{Args, avg_ms, open_session, round};
use anicraft_engine::Session;
use serde_json::{Value, json};
use std::time::Instant;
/// Samples of the default scenario: about 50 seconds of drawing at a tablet's 120 reports a
/// second.
pub const DEFAULT_SAMPLES: u32 = 6000;
/// Most samples the scenario takes (the command's own limit is `geom::brush::MAX_SAMPLES`).
const MAX_SAMPLES: u32 = 100_000;
/// A fast scribble over a 1280 × 720 stage: loops that drift across it and cross themselves
/// again and again, with the pressure swelling and fading. The same for a given `n`.
pub fn scribble(n: u32) -> Vec<[f32; 3]> {
let n = n.clamp(2, MAX_SAMPLES);
(0..n)
.map(|i| {
// About 16 stage units between samples: a fast hand.
let t = i as f32 * 0.06;
let x = 640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos();
let y = 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin();
[x, y, 0.55 + 0.45 * (t * 0.37).sin()]
})
.collect()
}
fn ms(t: Instant) -> f64 {
round(t.elapsed().as_secs_f64() * 1000.0)
}
/// Curve and line segments of every shape on the playhead's frame.
fn segments(s: &Session) -> usize {
s.display_list().items.iter().map(|i| i.path.cmds.len()).sum()
}
pub fn bench_stroke(a: &Args) -> Result<String, String> {
let file = a.flag("stroke-file");
let samples = match a.flag("stroke") {
Some("yes" | "true") | None => DEFAULT_SAMPLES,
Some(v) => v.parse::<u32>().map_err(|_| "--stroke takes a number of samples (or yes)".to_string())?.clamp(2, MAX_SAMPLES),
};
let mut out = json!({"build": if cfg!(debug_assertions) { "debug (use --release for real numbers)" } else { "release" }});
let mut s = match file {
Some(p) => {
out["file"] = json!(p);
open_session(Some(p))?
}
None => {
let mut s = Session::default();
let _ = s.execute("draw.object_drawing", &json!({"on": false}));
let t = Instant::now();
let v = s.execute("draw.brush", &json!({"points": scribble(samples), "size": 10, "color": "#000000", "object": false})).map_err(|e| e.to_string())?;
out["samples"] = json!(samples);
out["draw_brush_ms"] = json!(ms(t));
out["pieces"] = json!(v["elements"].as_array().map_or(0, Vec::len));
out["merged"] = v["merged"].clone();
s
}
};
out["segments"] = json!(segments(&s));
out["elements"] = json!(s.visible_elements().len());
let doc = s.doc.clone();
let frame = s.frame;
out["evaluate_ms"] = json!(round(avg_ms(5, |_| {
let _ = anicraft_doc::evaluate(&doc, frame);
})));
let view = anicraft_render::View::stage(&doc, 1.0);
let dl = anicraft_doc::evaluate(&doc, frame);
out["render_ms"] = json!(round(avg_ms(3, |_| {
let _ = anicraft_render::render(&dl, &view);
})));
out["hit_test_us"] = json!(round(
avg_ms(200, |i| {
let _ = s.hit_test(anicraft_geom::Vec2::new((i * 37 % 1280) as f32, (i * 53 % 720) as f32), 2.0);
}) * 1000.0
));
// The reporter's steps: select it, move it, let go of the mouse (it floats), deselect (it
// merges into the drawing).
let mut step = |s: &mut Session, key: &str, id: &str, p: Value| -> Result<Value, String> {
let t = Instant::now();
let v = s.execute(id, &p).map_err(|e| format!("{id}: {e}"))?;
out[key] = json!(ms(t));
Ok(v)
};
step(&mut s, "select_all_ms", "edit.select_all", json!({}))?;
step(&mut s, "move_ms", "element.translate", json!({"dx": 24, "dy": 16}))?;
step(&mut s, "float_ms", "draw.float", json!({}))?;
step(&mut s, "deselect_merge_ms", "edit.deselect", json!({}))?;
let t = Instant::now();
let _ = s.undo();
out["undo_ms"] = json!(ms(t));
out["segments_after"] = json!(segments(&s));
serde_json::to_string_pretty(&out).map_err(|e| e.to_string())
}
+35
View File
@@ -2,6 +2,7 @@
//! server (`mcp`). Every operation goes through the engine's command registry.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod bench_stroke;
#[cfg(not(target_arch = "wasm32"))]
pub mod control;
pub mod mcp;
@@ -46,6 +47,10 @@ USAGE:
anicraft-cli bench [--layers N] [--shapes N] [--frames N] performance probe (use --release)
anicraft-cli bench --check yes the default scenario against the budgets in
docs/performance.md; fails when one is missed
anicraft-cli bench --stroke <samples> one long Brush stroke: painting it, picking it, moving
it and the merge when it is deselected (ADR 0129)
anicraft-cli bench --stroke-file <file.anicraft>
the same steps on a document's own artwork
anicraft-cli serve [file|--sample] [--automation-read-root <folder> --automation-write-root <folder>]
JSON-lines on stdin/stdout:
{\"id\":1,\"cmd\":\"draw.rect\",\"params\":{\"x\":10,\"y\":10,\"w\":50,\"h\":50}}
@@ -579,6 +584,9 @@ pub fn check_budgets(out: &Value) -> (Vec<Value>, Vec<String>) {
/// `cargo run --release -p anicraft-cli -- bench`. With `--check yes`, the default scenario
/// is compared with [`TIME_BUDGETS`] and a missed budget is an error.
pub fn bench(a: &Args) -> Result<String, String> {
if a.flag("stroke").is_some() || a.flag("stroke-file").is_some() {
return bench_stroke::bench_stroke(a);
}
let check = a.flag("check").is_some_and(|v| v == "yes" || v == "true");
if check {
if cfg!(debug_assertions) {
@@ -1021,6 +1029,33 @@ pub(crate) mod tests {
}
}
/// `bench --stroke` walks the reporter's steps of #519 (paint, pick, move, float, deselect,
/// undo) and `--stroke-file` the same on a document: the stroke becomes one merged shape,
/// the merge on deselect keeps it, and undo puts the drawing back as it was.
#[test]
fn stroke_bench_paints_moves_and_merges_a_long_stroke() {
let out: Value = serde_json::from_str(&run(&["bench".into(), "--stroke".into(), "400".into()]).unwrap()).unwrap();
assert_eq!(out["samples"], 400);
assert_eq!(out["merged"], true);
let segments = out["segments"].as_u64().unwrap();
assert!(segments > 50, "a scribble has an outline of many curves: {segments}");
assert_eq!(out["segments_after"].as_u64(), Some(segments), "undo takes the move and its merge back");
for step in ["draw_brush_ms", "hit_test_us", "move_ms", "float_ms", "deselect_merge_ms", "undo_ms", "render_ms"] {
assert!(out[step].as_f64().is_some_and(|v| v >= 0.0), "{step} was timed: {out}");
}
assert!(run(&["bench".into(), "--stroke".into(), "many".into()]).unwrap_err().contains("number of samples"));
// The same steps on a saved document's artwork.
let dir = std::env::temp_dir().join(format!("anicraft-cli-stroke-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let file = dir.join("stroke.anicraft");
let mut s = Session::default();
s.execute("draw.brush", &json!({"points": bench_stroke::scribble(200), "size": 8, "object": false})).unwrap();
s.execute("file.save", &json!({"path": file.display().to_string()})).unwrap();
let out: Value = serde_json::from_str(&run(&["bench".into(), "--stroke-file".into(), file.display().to_string()]).unwrap()).unwrap();
assert!(out["samples"].is_null() && out["elements"].as_u64() == Some(1) && out["deselect_merge_ms"].is_number(), "{out}");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn plugins_folder_flag() {
let dir = std::env::temp_dir().join(format!("anicraft-cli-plugins-{}", std::process::id()));
+32
View File
@@ -421,3 +421,35 @@ fn crossing_brush_strokes_keep_what_was_drawn() {
}
}
}
/// ADR 0129: an outline traced ahead (on the editor's other thread) is painted by the
/// `draw.brush` that asks for exactly that stroke, and by no other. Either way it is gone
/// afterwards, so it can never be painted by a later stroke.
#[test]
fn an_outline_traced_ahead_is_taken_by_its_own_stroke_only() {
let stroke = json!({"points": [[100, 100], [220, 130], [300, 90]], "size": 12, "color": "#000000"});
let other = json!({"points": [[100, 100], [220, 130], [300, 95]], "size": 12, "color": "#000000"});
// A marker no trace would give: a square far from the stroke.
let marker = anicraft_geom::Path::rect(600.0, 400.0, 50.0, 50.0);
let painted_at = |staged: &Value, painted: &Value| {
let mut s = blank(true);
let ahead = crate::cmds_brush::stroke_request(&s, staged).unwrap().prepare();
s.staged_stroke = Some(ahead.with_path(marker.clone()));
run(&mut s, "draw.brush", painted.clone());
assert!(s.staged_stroke.is_none(), "it doesn't linger");
(top_at(&s, Vec2::new(625.0, 425.0)).is_some(), top_at(&s, Vec2::new(220.0, 130.0)).is_some())
};
assert_eq!(painted_at(&stroke, &stroke), (true, false), "its own stroke takes the outline as it is");
assert_eq!(painted_at(&stroke, &other), (false, true), "another stroke traces its own");
// Traced ahead or by the command: the same document.
let mut plain = blank(true);
run(&mut plain, "draw.brush", stroke.clone());
let mut ahead = blank(true);
ahead.staged_stroke = Some(crate::cmds_brush::stroke_request(&ahead, &stroke).unwrap().prepare());
run(&mut ahead, "draw.brush", stroke.clone());
assert_eq!(shapes(&plain), shapes(&ahead));
// A stroke that fails leaves nothing staged either.
plain.staged_stroke = Some(crate::cmds_brush::stroke_request(&plain, &stroke).unwrap().prepare());
assert!(plain.execute("draw.brush", &json!({"points": []})).is_err());
assert!(plain.staged_stroke.is_none());
}
+79 -13
View File
@@ -10,7 +10,7 @@ use crate::params::*;
use crate::{CommandSpec, EngineError, Result, Session};
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, MAX_WIDTH_POINTS, Paint, Rgba, Shape, Stroke, WidthPoint, WidthProfile};
use anicraft_geom::planar;
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Tilt, Tip, TipShape, centre_stroke, outline_shaped};
use anicraft_geom::brush::{MAX_SAMPLES, Sample, Shaping, Tilt, Tip, TipShape, centre_stroke, outline_shaped};
use anicraft_geom::{Affine, FillRule, Path, PathCmd, Vec2};
use serde_json::{Value, json};
use std::sync::Arc;
@@ -237,31 +237,97 @@ fn paint_stacks(p: &Paint) -> bool {
}
}
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
/// What a Brush stroke's outline is traced from: the samples (their pressure already through
/// the brush's curve), the tip, the shaping, and how closely the hand and the outline are
/// followed. Tracing is the slow part of a long stroke and depends on nothing else, so the
/// editor does it on another thread and hands the result to `draw.brush` (ADR 0129).
#[derive(Clone, Debug, PartialEq)]
pub struct StrokeRequest {
pts: Vec<Sample>,
tip: Tip,
shaping: Shaping,
smoothing: f32,
tol: f32,
}
impl StrokeRequest {
/// The filled outline (`geom::brush::outline_shaped`). Bounded for any stroke: the grid by
/// `MAX_CELLS`, the sampling by `MAX_STAMP_WORK`, the loops by `MAX_LOOPS`.
pub fn trace(&self) -> Path {
outline_shaped(&self.pts, &self.tip, &self.shaping, self.smoothing, self.tol)
}
/// Traces the outline: what [`Session::staged_stroke`] takes.
pub fn prepare(self) -> PreparedStroke {
let path = self.trace();
PreparedStroke { request: self, path }
}
/// How many samples the stroke has.
pub fn samples(&self) -> usize {
self.pts.len()
}
}
/// A stroke's outline, traced ahead of the command that paints it.
#[derive(Clone, Debug)]
pub struct PreparedStroke {
request: StrokeRequest,
path: Path,
}
impl PreparedStroke {
/// The same request with another outline, so a test can tell a taken outline from a traced
/// one.
#[cfg(test)]
pub(crate) fn with_path(self, path: Path) -> PreparedStroke {
PreparedStroke { path, ..self }
}
}
/// The request `draw.brush` with params `p` would trace. An error is the command's own (the
/// same params fail the same way there).
pub fn stroke_request(s: &Session, p: &Value) -> Result<StrokeRequest> {
stroke_inputs(s, p).map(|x| x.0)
}
/// [`stroke_request`], with the brush it paints with and the opacity its pressure gives it.
fn stroke_inputs(s: &Session, p: &Value) -> Result<(StrokeRequest, BrushPreset, f32)> {
let pts = bounded_samples(p)?;
let b = brush_param(s, p)?;
let tip = b.tip();
let size = tip.size;
let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false);
let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?;
let mode_key = opt_str(p, "mode")?.unwrap_or("normal");
let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?;
let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill });
let color = Rgba { a: color.a * pressure_opacity(&b, &pts), ..color };
let object = object_param(s, p)?;
let opacity = pressure_opacity(&b, &pts);
// Pressure through the curve (ADR 0068) before it sizes the tip.
let pts: Vec<Sample> = pts.iter().map(|x| Sample { pressure: b.size_pressure(x.pressure), ..*x }).collect();
// Smoothing and accuracy are screen distances, so a stroke looks the same at any zoom: at 50
// the centre line may wander 3.3 screen points from the hand, at 0 a third of a point.
// The outline is fitted within a third of a screen point, or a hundredth of the size for
// small brushes (so a small dab is still round).
let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(size * 0.01));
let (smoothing, tol) = (unit * (0.3 + b.smoothing * 0.06), (unit * 0.35).min(tip.size * 0.01));
Ok((StrokeRequest { pts, tip, shaping: b.shaping(), smoothing, tol }, b, opacity))
}
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
// An outline traced ahead is this stroke's or nobody's: it never waits for a later one.
let staged = s.staged_stroke.take();
let (request, b, opacity) = stroke_inputs(s, p)?;
let pts = &request.pts;
let (smoothing, tol) = (request.smoothing, request.tol);
let as_stroke = opt_bool(p, "as_stroke")?.unwrap_or(false);
let mode_key = opt_str(p, "mode")?.unwrap_or("normal");
let mode = PaintMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown paint mode '{mode_key}' (normal, fills, behind, selection or inside)")))?;
let color = opt_color(p, "color")?.unwrap_or(if as_stroke { s.style.stroke } else { s.style.fill });
let color = Rgba { a: color.a * opacity, ..color };
let object = object_param(s, p)?;
if as_stroke {
return paint_stroke(s, &pts, &b, smoothing, tol, color, object);
return paint_stroke(s, pts, &b, smoothing, tol, color, object);
}
let start = pts.first().map_or(Vec2::ZERO, |x| x.at);
let mut path = outline_shaped(&pts, &tip, &b.shaping(), smoothing, tol);
let mut path = match staged {
Some(ahead) if ahead.request == request => ahead.path,
_ => request.trace(),
};
if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
return Err(EngineError::Param("the stroke is too small to paint".into()));
}
+4
View File
@@ -461,6 +461,9 @@ pub struct Session {
/// An import the editor prepared on another thread (ADR 0116): `file.import_video` asked
/// for the same thing takes it instead of decoding again. Never in the document.
pub staged_video: Option<video::Prepared>,
/// A Brush stroke's outline the editor traced on another thread (ADR 0129): `draw.brush`
/// asked for the same stroke takes it instead of tracing again. Never in the document.
pub staged_stroke: Option<cmds_brush::PreparedStroke>,
/// Files this session's publishes wrote: publishing again replaces them without asking.
pub published: std::collections::BTreeSet<PathBuf>,
/// The files opened and saved last, and pinned favourites (ADR 0059). They belong to the
@@ -599,6 +602,7 @@ impl Session {
picture_cache: RefCell::new(None),
job: None,
staged_video: None,
staged_stroke: None,
published: std::collections::BTreeSet::new(),
recent: cmds_recent::RecentFiles::default(),
brushes: brush_library::BrushLibrary::default(),
+106 -14
View File
@@ -35,6 +35,11 @@ use crate::{Affine, Path, PathCmd, Vec2, fit_curve, trace};
pub const MAX_CELLS: usize = 4_000_000;
/// Most samples one stroke may have.
pub const MAX_SAMPLES: usize = 100_000;
/// Most cells the stroke's pieces may visit between them while the distance field is sampled
/// (each piece visits the cells of its own bounds). A stroke that would visit more is sampled on
/// a coarser grid, so the time one stroke takes is bounded however long it is and however often
/// it crosses itself (#519): a fast scribble of 60 000 samples visited 190 million cells.
pub const MAX_STAMP_WORK: usize = 1 << 24;
/// The tip's size at zero pressure, as a fraction of its full size.
pub const MIN_PRESSURE_SIZE: f32 = 0.1;
@@ -442,14 +447,7 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
let fine: f64 = if shaping.texture > 0.0 { f64::min(fine, 1.0 / 18.0) } else { fine };
// In stage space the tip's narrow side is `round` radii across.
let narrow = if turns { round } else { 1.0 };
let mut c: f64 = (fmin / 2.5).min(fine) * narrow;
for _ in 0..4 {
let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0);
if cells <= MAX_CELLS as f64 {
break;
}
c *= (cells / MAX_CELLS as f64).sqrt() * 1.01;
}
let c = cell_size(&q, (lo, hi), (fmin / 2.5).min(fine) * narrow, narrow, dabbed);
let origin = (lo.0 - MARGIN * c, lo.1 - MARGIN * c);
let w = ((hi.0 - lo.0) / c + 2.0 * MARGIN).ceil() + 1.0;
let h = ((hi.1 - lo.1) / c + 2.0 * MARGIN).ceil() + 1.0;
@@ -481,9 +479,16 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
};
let scale = if turn.is_some() { round } else { 1.0 };
let (ta, tb) = (to_tip(a), to_tip(b));
let full = top as f32;
for y in y0 as usize..=y1 as usize {
let py = origin.1 + (y as f64 + 0.5) * c;
for x in x0 as usize..=x1 as usize {
let Some(row) = field.get_mut(y * w + x0 as usize..=y * w + x1 as usize) else { continue };
for (x, cell) in (x0 as usize..).zip(row) {
// Deep inside paint already: nothing can raise it (a stroke that goes over
// itself again and again costs a comparison here, not a distance).
if *cell >= full {
continue;
}
let px = origin.0 + (x as f64 + 0.5) * c;
let tx = to_tip((px, py));
let d = match tip.shape {
@@ -491,9 +496,7 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
TipShape::Square => square_dist(tx, ta, ra, tb, rb),
} * scale;
let v = (0.5 - d / c).clamp(OUTSIDE, top) as f32;
if let Some(cell) = field.get_mut(y * w + x)
&& v > *cell
{
if v > *cell {
*cell = v;
}
}
@@ -573,6 +576,46 @@ pub fn outline_shaped(samples: &[Sample], tip: &Tip, shaping: &Shaping, smoothin
out
}
/// The grid's cell size for the stroke through `q` (bounds `lo..hi`): `wanted`, or as much
/// larger as keeps the grid within [`MAX_CELLS`] and the sampling within [`MAX_STAMP_WORK`].
fn cell_size(q: &[(P, f64, f64)], (lo, hi): (P, P), wanted: f64, narrow: f64, dabbed: bool) -> f64 {
let mut c = wanted;
for _ in 0..4 {
let cells = ((hi.0 - lo.0) / c + 2.0 * MARGIN + 2.0) * ((hi.1 - lo.1) / c + 2.0 * MARGIN + 2.0);
if cells <= MAX_CELLS as f64 {
break;
}
c *= (cells / MAX_CELLS as f64).sqrt() * 1.01;
}
for _ in 0..6 {
let work = stamp_work(&thin(q, c * 0.5), c, narrow, dabbed);
if work <= MAX_STAMP_WORK as f64 {
break;
}
c *= (work / MAX_STAMP_WORK as f64).sqrt().max(1.05);
}
c
}
/// About how many cells of size `c` the pieces of the stroke through `q` visit between them:
/// each piece's own bounds, as the field is sampled (a long segment in pieces of [`PIECE`]).
fn stamp_work(q: &[(P, f64, f64)], c: f64, narrow: f64, dabbed: bool) -> f64 {
let cells = |len: (f64, f64), r: f64| {
let reach = 2.0 * (r.max(c / narrow) + (MARGIN - 1.0) * c);
((len.0 + reach) / c + 1.0) * ((len.1 + reach) / c + 1.0)
};
if dabbed || q.len() < 2 {
return q.iter().map(|(_, f, _)| cells((0.0, 0.0), *f)).sum();
}
q.windows(2)
.map(|pair| {
let &[(a, ra, _), (b, rb, _)] = pair else { return 0.0 };
let n = (dist(a, b) / PIECE.max(16.0 * c)).ceil().clamp(1.0, 1e6);
n * cells(((a.0 - b.0).abs() / n, (a.1 - b.1).abs() / n), ra.max(rb))
})
.sum()
}
/// Most loops one outline keeps (a fine paper grain on a long stroke opens many holes).
pub const MAX_LOOPS: usize = 20_000;
/// The paper grain's size, in tip radii.
@@ -630,7 +673,9 @@ fn v64(p: Vec2) -> P {
(f64::from(p.x), f64::from(p.y))
}
fn dist(a: P, b: P) -> f64 {
(a.0 - b.0).hypot(a.1 - b.1)
// Not `hypot`: nothing here is near overflow, and this runs for every cell a piece visits.
let (x, y) = (a.0 - b.0, a.1 - b.1);
(x * x + y * y).sqrt()
}
fn lerp(a: P, b: P, t: f64) -> P {
(a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t)
@@ -689,7 +734,7 @@ fn thin(q: &[(P, f64, f64)], gap: f64) -> Vec<(P, f64, f64)> {
/// to the segment) is the minimum.
fn round_dist(x: P, a: P, ra: f64, b: P, rb: f64) -> f64 {
let d = (b.0 - a.0, b.1 - a.1);
let l = d.0.hypot(d.1);
let l = (d.0 * d.0 + d.1 * d.1).sqrt();
let dr = rb - ra;
let ends = || (dist(x, a) - ra).min(dist(x, b) - rb);
if l < 1e-12 || dr.abs() >= l {
@@ -768,6 +813,53 @@ mod tests {
assert!(p.anchors().len() <= 16, "{} anchors", p.anchors().len());
}
/// A fast scribble over a 1280 × 720 stage that crosses itself again and again, with the
/// pressure swelling and fading: `n` samples about 16 units apart.
fn scribble(n: usize) -> Vec<Sample> {
(0..n)
.map(|i| i as f32 * 0.06)
.map(|t| Sample::new(Vec2::new(640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos(), 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin()), 0.55 + 0.45 * (t * 0.37).sin()))
.collect()
}
/// #519: the cells a stroke's pieces visit are bounded, however long the stroke is. A
/// scribble of 60 000 samples would visit several times the budget on the grid its size
/// asks for; the grid it gets keeps it inside, and the paint is still where the hand went.
#[test]
fn a_long_scribble_is_sampled_within_the_work_budget() {
let s = scribble(60_000);
let q: Vec<(P, f64, f64)> = centre_points(&s, 3.0, 0.08, &Shaping::default()).iter().map(|p| ((f64::from(p.at.x) / 5.0, f64::from(p.at.y) / 5.0), f64::from(p.f), 0.0)).collect();
let (lo, hi) = q.iter().fold(((f64::MAX, f64::MAX), (f64::MIN, f64::MIN)), |(lo, hi), (p, _, _)| ((lo.0.min(p.0), lo.1.min(p.1)), (hi.0.max(p.0), hi.1.max(p.1))));
let wanted = 0.04;
let grid_only = {
let cells = ((hi.0 - lo.0) / wanted + 8.0) * ((hi.1 - lo.1) / wanted + 8.0);
wanted * (cells / MAX_CELLS as f64).sqrt().max(1.0)
};
let unbounded = stamp_work(&thin(&q, grid_only * 0.5), grid_only, 1.0, false);
assert!(unbounded > 2.0 * MAX_STAMP_WORK as f64, "the scenario is past the budget without the bound: {unbounded}");
let c = cell_size(&q, (lo, hi), wanted, 1.0, false);
let work = stamp_work(&thin(&q, c * 0.5), c, 1.0, false);
assert!(work <= MAX_STAMP_WORK as f64 * 1.05, "{work}");
assert!(c > grid_only && c < 0.5, "coarser, but still well under the tip's radius: {c}");
// The outline it gives: paint under the hand at every sample, none far from all of them.
let p = outline(&s, &Tip::round(10.0), 3.0, 0.3);
assert!(s.iter().step_by(997).all(|x| p.contains(x.at, &Affine::IDENTITY, FillRule::EvenOdd)), "paint under the hand");
assert!(!p.contains(Vec2::new(20.0, 20.0), &Affine::IDENTITY, FillRule::EvenOdd), "and none in the corner it never reached");
}
#[test]
#[ignore = "a measurement, not a check"]
fn long_stroke_cost() {
for n in [1500, 6000, 20_000, 60_000, 100_000] {
for (name, size) in [("size 10", 10.0), ("size 3", 3.0), ("size 60", 60.0)] {
let s = scribble(n);
let t = std::time::Instant::now();
let p = outline(&s, &Tip::round(size), 3.0, 0.3);
println!("{n:6} samples, {name}: {:7.1} ms, {} segments", t.elapsed().as_secs_f64() * 1000.0, p.cmds.len());
}
}
}
#[test]
fn a_dab_is_the_tip() {
let p = outline(&[Sample::new(Vec2::new(10.0, 10.0), 1.0)], &Tip::round(8.0), 1.0, 0.05);
@@ -0,0 +1,81 @@
# ADR 0129: A long Brush stroke never holds the window
* Status: accepted (2026-11-21)
* Relates to: ADR 0033 (the Brush), ADR 0031 (merge drawing), ADR 0122 (a moved selection
merges when it is deselected), ADR 0116 (work prepared on another thread, then one command),
issue #519, backlog item P-003
## Context
Issue #519: a Brush stroke drawn for 40 to 50 seconds without lifting, then moved and
deselected, left the window "Not Responding", again and again, and the saved file did the same
when it was opened. The reporter's file holds one raw fill of 11 370 curves in 1 107 loops.
Measured on that file and on generated strokes (`anicraft-cli bench --stroke <samples>` and
`--stroke-file <file>`; a 32-thread desktop, so a laptop is several times slower):
| What | Before | Why |
|---|---|---|
| `draw.brush`, 6 000 / 20 000 / 60 000 samples of fast scribble | 306 / 807 / 1 563 ms | The distance field (ADR 0033) is sampled piece by piece, each piece over its own bounds. A stroke that goes over itself visits the same cells again and again: 190 million cell visits for 60 000 samples. The cost grew with the stroke's length without limit. |
| A frame with part of the stroke selected over the rest (after a marquee) | 3.2 s **a frame** (debug build) | The stipple of a selected raw fill is cut by the artwork above it. Every span of the selection was compared with every span of every occluder: tens of thousands by tens of thousands. |
| The merge when a moved stroke is deselected | 75 to 195 ms | `planar::merge`, already bounded (`MAX_SEGMENTS`, `MAX_PAIRS`). |
| Drawing the stage with the stroke on it | 3 to 5 ms CPU, 4 to 20 ms GPU | Not a problem. |
So there were two unbounded costs, one in the engine (the trace) and one in the shell (the
selection overlay, paid on every frame, which is the "loop" the reporter saw), and one bounded
cost that is still longer than a frame.
## Decision
1. **The trace is bounded.** `geom::brush` counts the cells a stroke's pieces would visit and,
past `MAX_STAMP_WORK` (2²⁴), samples on a coarser grid, as it already does past `MAX_CELLS`.
A cell that is already deep inside paint is skipped with one comparison, since nothing can
raise it. The result for a stroke under the budget is unchanged. Past it the grid is at
worst the size the brush's own tip asks for at full pressure (a sixth of its radius), so
thin parts of a very long stroke are a little less fine; the outline is still traced from a
true distance, well under a cell.
2. **The editor traces a long stroke on another thread.** The trace depends on nothing but the
stroke, so it is a pure function of a `StrokeRequest`. When the pointer lifts on a stroke of
400 samples or more, the shell starts the trace on a thread (`src/ink.rs`) and keeps drawing
the stroke as it was drawn. When the outline is ready, the shell runs the same `draw.brush`
as ever with the outline staged (`Session::staged_stroke`): the command takes a staged
outline only when it is for exactly the stroke it was asked to paint, and traces otherwise.
This is the pattern of ADR 0116 (`staged_video`). The command, its parameters, its undo step
and what a script or an assistant sees are unchanged; headless callers trace in the command.
3. **Nothing comes between a stroke and its paint.** Strokes are painted in the order they
were drawn. While strokes wait, only looking around and painting more go ahead: a frame
whose input could edit (any key, text, a press that is not the Brush on the stage, a dropped
file, playback, a dialog) first finishes the waiting strokes on the window's thread, as does
any command (`App::run`, so an assistant's commands too) and leaving the document. The wait
is bounded by decision 1. At most eight strokes wait; a ninth waits for the first.
4. **The merge stays on the window's thread**, bounded as before. A `Session` is not `Send`
and cannot be cloned (plug-ins, caches, the undo history), and a merge needs the drawing it
merges into, so moving it would mean running the command on a copy and adopting the result,
which is a second way for an edit to enter the document. It is not worth that for 75 to
220 ms on the largest strokes the app accepts. If it turns out to be, the copy-and-adopt
route is the one to take, for every slow command at once, in its own ADR.
5. **The selection overlay looks up occluders by row.** `subtract_spans` sorts the occluders by
their top edge and compares a span only with those in its own rows, in their original order,
so the pieces it leaves are the ones it always left.
## Consequences
* `draw.brush` on the three generated strokes: 218 / 461 / 383 ms, of which the trace is at
most about 300 ms whatever the stroke, and in the editor none of the trace is on the
window's thread. What is left there is the merge.
* The marquee case is 200 ms once (the cut) instead of seconds on every frame.
* A stroke can be on the stage for a moment before it is in the document. Undo, save and every
other edit see it, because they wait for it; an update is not installed while one waits.
* The web build has one thread: it traces in the command, bounded by decision 1.
* *Not done here:* the Subselection tool's click on a shape of 13 000 points (3 s once in a
debug build), the Paint Bucket in a gap of such a shape (0.8 s), and the shape tools' snapping
near it (about 100 ms a frame in a debug build). They are bounded and one-off or mild, and
are listed under P-003 in the roadmap.
* *Rejected:* a progress window ("processing strokes", as the reference app shows). With the
trace bounded and off the thread there is nothing long enough to report.
* *Rejected:* simplifying the outline to fewer curves. It changes what the artist drew, and
the curve count was not what cost the time.
+2 -1
View File
@@ -422,7 +422,8 @@ Both dialogs remember what you entered. Each command is one undo step.
## Transforming artwork
With the **Free Transform** tool (**Q**), drag a handle (a corner or the middle of an edge) to
**scale** (**Shift** keeps the proportions, **Alt** scales about the transformation point),
**scale** (the opposite handle stays where it is; **Shift** keeps the proportions, **Alt**
scales about the transformation point instead),
the line between two handles to **skew** (the opposite edge stays where it is; **Alt** skews
about the transformation point), just outside a corner to **rotate** (the pointer turns
into a curved arrow there; **Shift** snaps to 15°), or inside the box to **move**.
+1 -1
View File
@@ -99,7 +99,7 @@ not this table, says what matters most.
|---|---|---|
| Selection | **partial** | Raw shapes, objects, marquee, bend an edge, move a corner ([ADR 0041](adr/0041-selection-tool-on-raw-drawings.md), [ADR 0044](adr/0044-selection-across-layers.md)). Missing: a marquee that takes instances and objects it only touches ([#522](https://github.com/storytold/anicraft/issues/522)), Hide Edges ([#298](https://github.com/storytold/anicraft/issues/298)) (P-017). |
| Subselection | **done** | [ADR 0042](adr/0042-subselection-and-merging-everywhere.md), [ADR 0045](adr/0045-raw-points-and-raw-shapes-inside-symbols.md). |
| Free Transform | **partial** | Scale, skew, rotate, the transformation point, a box that turns with the object ([ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md)), Envelope ([ADR 0080](adr/0080-drawing-parity-leftovers.md)). Missing: Distort. Open bugs: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117)) (P-005). |
| Free Transform | **partial** | Scale, skew, rotate, the transformation point, a box that turns with the object ([ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md)), Envelope ([ADR 0080](adr/0080-drawing-parity-leftovers.md)). Missing: Distort. Open bug: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), not reproduced on Windows 10 (P-005). |
| Gradient Transform | **done** | Gradient and bitmap fills, Lock Fill. |
| Lasso | **missing** | P-018 ([#515](https://github.com/storytold/anicraft/issues/515)). |
| Polygon (lasso) | **missing** | P-018. |
+4
View File
@@ -9,6 +9,8 @@ oracle; its output must stay bit-identical).
```sh
cargo run --release -p anicraft-cli -- bench # 50 layers × 200 shapes × 240 frames
cargo run --release -p anicraft-cli -- bench --layers 200 --shapes 500 --frames 600
cargo run --release -p anicraft-cli -- bench --stroke 6000 # one long Brush stroke (ADR 0129)
cargo run --release -p anicraft-cli -- bench --stroke-file drawing.anicraft # the same steps on a file
```
`bench` builds a deterministic stress document (`doc::sample::stress`) and reports file size,
@@ -37,6 +39,8 @@ The default `bench` scenario: 50 layers × 200 shapes × 240 frames, 200k elemen
| UI frame while rendering | never blocked | worker thread ✅ | design (ADR 0002) |
| Autosave: time on the editing thread | < 1 ms | 7–15 µs ✅ | `bench --check` |
| Autosave of the 65 MB file, in the background | < 2 s | 183–184 ms ✅ | `bench --check` |
| A long Brush stroke: tracing its outline (ADR 0129) | bounded: `MAX_STAMP_WORK` cells visited, whatever the stroke | 45 to 310 ms for 1,500 to 100,000 samples, sizes 3 to 60 (2026-11-21; 1,500 ms and growing before) | test, every PR (the budget, not the time) |
| A long Brush stroke in the editor | the trace is never on the window's thread | worker thread ✅; the merge (75 to 220 ms at the largest) still is | test, every PR |
| GPU stage, 1,000 shapes at 4K, stage tiles (M3 exit) | < 16.7 ms | 4.5–4.7 ms ✅ (2026-11-10, RTX 5090) | `gpu_bench --check` |
| GPU stage, 10k shapes at 4K, stage tiles | < 16.7 ms | 10.1–10.4 ms ✅ | `gpu_bench --check` |
| GPU stage, 50k shapes at 1080p, stage tiles | < 33.3 ms (30 fps) | 24.8–26.3 ms ✅ | `gpu_bench --check` |
+3 -2
View File
@@ -44,9 +44,10 @@ the changelog.
| Id | Goal | Parity area | Size | Needs | Lane |
|---|---|---|---|---|---|
| P-001 | AniCraft starts on every supported machine: the launch failures on Windows and Linux graphics drivers ([#164](https://github.com/storytold/anicraft/issues/164), [#158](https://github.com/storytold/anicraft/issues/158), [#207](https://github.com/storytold/anicraft/issues/207), [#268](https://github.com/storytold/anicraft/issues/268), [#421](https://github.com/storytold/anicraft/issues/421), [#342](https://github.com/storytold/anicraft/issues/342); duplicates [#488](https://github.com/storytold/anicraft/issues/488), [#448](https://github.com/storytold/anicraft/issues/448), [#412](https://github.com/storytold/anicraft/issues/412), [#313](https://github.com/storytold/anicraft/issues/313), [#286](https://github.com/storytold/anicraft/issues/286), [#285](https://github.com/storytold/anicraft/issues/285)) each end in a window or a message that says what to do | Preferences, platforms | M | reports' logs | platform |
| P-003 | A long Brush stroke never freezes the app ([#519](https://github.com/storytold/anicraft/issues/519)): bound the trace and fit, keep the stage responsive while it merges | Tools | M | | stage |
| P-002 | Nested symbols can't exhaust memory or hang: a work budget on evaluation and bounds (outside PR [#13](https://github.com/storytold/anicraft/issues/13)) | Symbols | S | | doc |
| P-003 | What is left of "a long Brush stroke never freezes the app" ([#519](https://github.com/storytold/anicraft/issues/519)) after [ADR 0129](adr/0129-a-long-brush-stroke-never-holds-the-window.md) bounded the trace, took it off the window's thread and fixed the selection overlay: on one raw shape of ten thousand points and more, the Subselection tool's click (seconds, once), the Paint Bucket in a gap (about a second) and the shape tools' snapping (slow frames); and the merge of such a shape (75 to 220 ms) still runs on the window's thread | Tools | S each | | stage |
| P-004 | Memory and frame time stay flat: 900 MB for a 24-frame move in the web build ([#314](https://github.com/storytold/anicraft/issues/314)), stutter when zoomed in ([#477](https://github.com/storytold/anicraft/issues/477)); a budget test for each | Workspace | M | | render |
| P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117)); decide [#193](https://github.com/storytold/anicraft/issues/193) (see outside PR [#218](https://github.com/storytold/anicraft/issues/218)) and write the rule in the guide | Tools | M | | stage |
| P-005 | Free Transform works everywhere: rotation on Windows and FreeBSD ([#479](https://github.com/storytold/anicraft/issues/479)), which did not reproduce on Windows 10 (the curved pointer shows outside a corner in the real window; the headless press-and-drag tests pass) and needs the reporter's build number and steps. Done: handles on a skewed symbol ([#117](https://github.com/storytold/anicraft/issues/117), tested end to end), and [#193](https://github.com/storytold/anicraft/issues/193) decided by [ADR 0111](adr/0111-the-transformation-point-a-turning-box-and-layer-opacity.md) with the rule in the guide | Tools | S | the reporter's answer | stage |
| P-006 | Animate files open right: lines missing or filled in ([#498](https://github.com/storytold/anicraft/issues/498)), a `.fla` refused on macOS ([#347](https://github.com/storytold/anicraft/issues/347)); each fixed file joins the corpus | Import | M | the reporters' files | xfl |
| P-007 | The web build is usable: import, export and save ([#55](https://github.com/storytold/anicraft/issues/55)), preferences kept ([#56](https://github.com/storytold/anicraft/issues/56)), a web asset on each release ([#316](https://github.com/storytold/anicraft/issues/316), [#210](https://github.com/storytold/anicraft/issues/210)), a run in a real browser in CI | Preferences, platforms | M | | platform |
| P-008 | Text reads right: mixed directions (outside PR [#39](https://github.com/storytold/anicraft/issues/39)), then letters from a fallback face (outside PR [#40](https://github.com/storytold/anicraft/issues/40)) | Text | M | [#39](https://github.com/storytold/anicraft/issues/39) before [#40](https://github.com/storytold/anicraft/issues/40) | text |
+10
View File
@@ -477,6 +477,9 @@ pub struct App {
/// A filter preset being named in Properties (ADR 0091).
pub filter_naming: crate::panels::FilterNaming,
pub brush_samples: Vec<(anicraft_engine::geom::Vec2, Option<f32>)>,
/// Brush strokes drawn but not yet painted: their outlines are being traced on another
/// thread (ADR 0129). Oldest first.
pub ink: Vec<crate::ink::Pending>,
pub pen_pressure: Option<f32>,
/// Whether a pointer event has carried a pen's tilt this session (ADR 0093). Until one has,
/// the brushes' Tilt options stay hidden: they would do nothing.
@@ -860,6 +863,7 @@ impl App {
brush_lib: crate::brush_panel::BrushLibraryView::default(),
filter_naming: Default::default(),
brush_samples: Vec::new(),
ink: Vec::new(),
pen_pressure: None,
pen_tilt_seen: false,
eraser: crate::erasertool::EraserOptions::default(),
@@ -1035,6 +1039,9 @@ impl App {
}
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
// Strokes still on their way in are painted first: commands run in the order they
// were asked for (ADR 0129).
crate::ink::flush(self);
let result = self.s.execute(id, &params);
if platform::WEB && id.starts_with("file.") {
// In a browser, what a save or an export wrote is in memory: hand it to the
@@ -4763,6 +4770,9 @@ impl App {
}
}
self.handle_screenshot(&ctx);
// Brush strokes whose outlines are traced go into the document, before this frame's
// input can edit it (ADR 0129).
crate::ink::frame(self, &ctx);
// An assistant's edits (ADR 0104), before anything draws: they show in this frame.
#[cfg(not(target_arch = "wasm32"))]
crate::remote::poll(self, &ctx);
+33 -18
View File
@@ -323,7 +323,9 @@ pub fn sample(app: &mut App, p: Vec2, pressure: Option<f32>, xf: Xf, now: f64) {
}
/// Sends the stroke (one command, one undo step). Smoothing and accuracy follow the screen.
pub fn commit(app: &mut App, xf: Xf) {
/// A long Brush stroke's outline is traced on another thread first, the stroke staying on the
/// stage as drawn until it is painted (ADR 0129, `crate::ink`).
pub fn commit(app: &mut App, ctx: &egui::Context, xf: Xf) {
let samples = std::mem::take(&mut app.brush_samples);
if samples.is_empty() {
return;
@@ -344,12 +346,19 @@ pub fn commit(app: &mut App, xf: Xf) {
}
return;
}
if !crate::ink::defer(app, ctx, &samples, &params, o.mode) {
paint(app, params, o.mode);
}
}
/// Paints a Brush stroke: `draw.brush` with `params`, and what to say when nothing was painted.
pub fn paint(app: &mut App, params: serde_json::Value, mode: PaintMode) {
// Paint Selection keeps the selection it paints in, for the next stroke (ADR 0080).
let v = if o.mode == PaintMode::Selection { app.run("draw.brush", params) } else { app.draw("draw.brush", params) };
let v = if mode == PaintMode::Selection { app.run("draw.brush", params) } else { app.draw("draw.brush", params) };
if let Some(v) = v
&& v["elements"].as_array().is_some_and(Vec::is_empty)
{
match o.mode {
match mode {
PaintMode::Selection => app.status_ok(tr!("Nothing painted: Paint Selection paints only inside the selected fills. Select them with the Selection tool first.")),
PaintMode::Inside => app.status_ok(tr!("Nothing painted: Paint Inside paints only inside the fill where the stroke starts.")),
_ => app.status_ok(tr!("Nothing to paint behind there: Paint Behind only paints empty areas.")),
@@ -394,7 +403,7 @@ const MASK_MAX: usize = 2048;
/// The alpha the finished stroke will have: the fill (or the stroke colour) times, when
/// pressure drives opacity, the average mapped pressure so far. That average is what the
/// command stores for the whole stroke (ADR 0068).
fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option<f32>)]) -> f32 {
pub(crate) fn intended_alpha(o: &BrushOptions, paint_a: f32, samples: &[(Vec2, Option<f32>)]) -> f32 {
let paint_a = if paint_a.is_finite() { paint_a.clamp(0.0, 1.0) } else { 1.0 };
if !o.pressure_opacity || samples.is_empty() {
return paint_a;
@@ -430,15 +439,7 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
let (paint, tip) = if app.tool == Tool::PaintBrush { (app.s.style.stroke, BrushOptions { shape: TipShape::Round, roundness: 100.0, ..*o }) } else { (app.s.style.fill, *o) };
if app.drag == Drag::Brush {
let alpha = intended_alpha(&tip, paint.a, &app.brush_samples);
// Opaque ink stays the convex sweep the Eraser shares. A wash is one coverage image
// at the alpha the stroke will keep, so the pen-down ink matches the ink after you
// lift (ADR 0102).
if (alpha * 255.0).round() >= 255.0 {
let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint });
draw_sweep(painter, xf, &tip, &app.brush_samples, color);
} else {
draw_sweep_alpha(painter, xf, &tip, &app.brush_samples, paint, alpha);
}
draw_ink(painter, xf, &tip, &app.brush_samples, paint, alpha, 0);
}
if let Some(h) = hover {
// The tip's size and shape at the pointer, as Animate shows it.
@@ -446,6 +447,19 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
}
}
/// A stroke's ink as it is drawn: `paint` at `alpha`, the alpha the finished stroke will have.
/// Opaque ink is the convex sweep the Eraser shares. A wash is one coverage image at that
/// alpha, so the pen-down ink matches the ink after you lift (ADR 0102); `slot` names its
/// texture (the stroke in hand is 0, strokes waiting to be painted come after, ADR 0129).
pub(crate) fn draw_ink(painter: &egui::Painter, xf: Xf, tip: &BrushOptions, samples: &[(Vec2, Option<f32>)], paint: anicraft_engine::doc::Rgba, alpha: f32, slot: usize) {
if (alpha * 255.0).round() >= 255.0 {
let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..paint });
draw_sweep(painter, xf, tip, samples, color);
} else {
draw_sweep_alpha(painter, xf, tip, samples, paint, alpha, slot);
}
}
/// The tip swept along `samples` (shared with the Eraser, ADR 0034), filled with `color`.
pub fn draw_sweep(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)], color: egui::Color32) {
if samples.is_empty() {
@@ -502,7 +516,7 @@ fn sweep_hulls(xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)]) -> Vec
/// The same sweep as one coverage image, tinted at `alpha`. Overlapping pieces keep the
/// greater coverage, so a crossing in one stroke stays one alpha.
fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)], paint: anicraft_engine::doc::Rgba, alpha: f32) {
fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples: &[(Vec2, Option<f32>)], paint: anicraft_engine::doc::Rgba, alpha: f32, slot: usize) {
if alpha <= 0.0 {
return;
}
@@ -540,14 +554,15 @@ fn draw_sweep_alpha(painter: &egui::Painter, xf: Xf, o: &BrushOptions, samples:
pixels.push(egui::Color32::from_white_alpha(a));
}
let image = egui::ColorImage::new([w, h], pixels);
let tex = sweep_texture(painter.ctx(), image);
let tex = sweep_texture(painter.ctx(), image, slot);
let tint = to_color32(anicraft_engine::doc::Rgba { a: alpha, ..paint });
painter.image(tex.id(), view, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), tint);
}
/// One reused texture for the live wash, so a stroke does not leak a texture every frame.
fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage) -> egui::TextureHandle {
let id = egui::Id::new("anicraft.brush.sweep");
/// One reused texture for the live wash, so a stroke does not leak a texture every frame (and
/// one for each stroke that waits to be painted: a few at most).
fn sweep_texture(ctx: &egui::Context, image: egui::ColorImage, slot: usize) -> egui::TextureHandle {
let id = if slot == 0 { egui::Id::new("anicraft.brush.sweep") } else { egui::Id::new(("anicraft.brush.sweep", slot)) };
let options = egui::TextureOptions::LINEAR;
if let Some(mut tex) = ctx.data(|d| d.get_temp::<egui::TextureHandle>(id)) {
tex.set(image, options);
+156
View File
@@ -0,0 +1,156 @@
//! Brush strokes whose outline is still being traced (ADR 0129, issue #519).
//!
//! Tracing a long stroke's outline takes longer than a frame (a tenth of a second and more for
//! a stroke drawn over many seconds), and it depends on nothing but the stroke. So when the
//! pointer lifts on a long stroke, the trace runs on another thread; the stroke stays on the
//! stage as it was drawn, and the next stroke can start at once. When the trace is done the
//! stroke is painted by the same `draw.brush` as ever, which takes the traced outline
//! (`Session::staged_stroke`) instead of tracing it again.
//!
//! Strokes are painted in the order they were drawn, and nothing else may come between a stroke
//! and its paint: before any other edit (a key, a click anywhere but a brush on the stage, a
//! command from an assistant, playback, another document), the waiting strokes are finished
//! first, on this thread ([`flush`]). The wait is bounded, since a trace is
//! (`geom::brush::MAX_STAMP_WORK`).
use crate::app::{App, Tool};
use crate::brushtool::{self, BrushOptions};
use crate::pathtools::Xf;
use anicraft_engine::cmds_brush::{PaintMode, PreparedStroke, stroke_request};
use anicraft_engine::doc::Rgba;
use anicraft_engine::geom::Vec2;
use serde_json::Value;
use std::sync::mpsc::{Receiver, TryRecvError, channel};
/// Strokes with fewer samples are traced where they are: they take less than a frame.
pub const DEFER_SAMPLES: usize = 400;
/// Most strokes waiting at once; one more waits for the first.
const MAX_WAITING: usize = 8;
/// A stroke on its way into the document.
pub struct Pending {
/// The stroke as it was drawn, for the stage.
samples: Vec<(Vec2, Option<f32>)>,
tip: BrushOptions,
paint: Rgba,
alpha: f32,
/// What `draw.brush` is run with.
params: Value,
mode: PaintMode,
done: Receiver<PreparedStroke>,
}
/// Takes a Brush stroke whose trace should not hold the window up: `false` when it is short
/// enough to paint right away (nothing waiting before it), or can't be handed over (the web
/// build has one thread; a stroke the command would refuse is left for it to refuse).
pub fn defer(app: &mut App, ctx: &egui::Context, samples: &[(Vec2, Option<f32>)], params: &Value, mode: PaintMode) -> bool {
if crate::platform::WEB || (app.ink.is_empty() && samples.len() < DEFER_SAMPLES) {
return false;
}
let Ok(request) = stroke_request(&app.s, params) else { return false };
if app.ink.len() >= MAX_WAITING {
flush(app);
}
let (tx, done) = channel();
let wake = ctx.clone();
let started = std::thread::Builder::new().name("anicraft-ink".into()).spawn(move || {
let _ = tx.send(request.prepare());
wake.request_repaint();
});
if started.is_err() {
return false;
}
let tip = *brushtool::options(app);
let paint = app.s.style.fill;
let alpha = brushtool::intended_alpha(&tip, paint.a, samples);
app.ink.push(Pending { samples: samples.to_vec(), tip, paint, alpha, params: params.clone(), mode, done });
true
}
/// Paints the waiting strokes whose traces are done, oldest first, stopping at the first that
/// is not.
pub fn poll(app: &mut App) {
if app.ink.is_empty() {
return;
}
// Out of the app while they are painted, so painting one never waits on the others.
let mut waiting = std::mem::take(&mut app.ink).into_iter();
let mut rest = Vec::new();
for p in waiting.by_ref() {
match p.done.try_recv() {
Ok(traced) => paint(app, &p, Some(traced)),
// The thread is gone without an outline: the command traces it.
Err(TryRecvError::Disconnected) => paint(app, &p, None),
Err(TryRecvError::Empty) => {
rest.push(p);
break;
}
}
}
rest.extend(waiting);
app.ink = rest;
}
/// Paints every waiting stroke now, waiting for its trace: before anything else edits.
pub fn flush(app: &mut App) {
for p in std::mem::take(&mut app.ink) {
let traced = p.done.recv().ok();
paint(app, &p, traced);
}
}
fn paint(app: &mut App, p: &Pending, traced: Option<PreparedStroke>) {
app.s.staged_stroke = traced;
brushtool::paint(app, p.params.clone(), p.mode);
app.s.staged_stroke = None;
}
/// Whether what this frame brings may go ahead of the waiting strokes: looking around and
/// painting more. Anything that could edit (a key, text, a click that is not a brush on the
/// stage, a dropped file) may not.
fn only_painting(app: &App, ctx: &egui::Context) -> bool {
if app.playing || app.modal_open() || app.palette.is_some() {
return false;
}
// The presses this frame, unless something else came with them (the context is not asked
// about its layers while its input is being read).
let presses: Option<Vec<egui::Pos2>> = ctx.input(|i| {
if !i.raw.dropped_files.is_empty() {
return None;
}
let mut presses = Vec::new();
for e in &i.raw.events {
match e {
egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone | egui::Event::Touch { .. } | egui::Event::MouseWheel { .. } | egui::Event::Zoom(_) | egui::Event::WindowFocused(_) => {}
egui::Event::PointerButton { pressed: false, .. } => {}
egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => presses.push(*pos),
_ => return None,
}
}
Some(presses)
});
let Some(presses) = presses else { return false };
// A press paints when the Brush is in hand and it lands on the stage itself.
let canvas = app.stage_cache.canvas;
presses.iter().all(|pos| app.tool == Tool::Brush && canvas.contains(*pos) && ctx.layer_id_at(*pos).is_none_or(|l| l.order == egui::Order::Background))
}
/// At the start of a frame: strokes whose traces are done are painted; if this frame's input
/// could edit, all of them are, first.
pub fn frame(app: &mut App, ctx: &egui::Context) {
if app.ink.is_empty() {
return;
}
if only_painting(app, ctx) {
poll(app);
} else {
flush(app);
}
}
/// The waiting strokes on the stage, as they were drawn.
pub fn draw(app: &App, painter: &egui::Painter, xf: Xf) {
for (slot, p) in app.ink.iter().enumerate() {
brushtool::draw_ink(painter, xf, &p.tip, &p.samples, p.paint, p.alpha, slot + 1);
}
}
+270
View File
@@ -0,0 +1,270 @@
//! A long Brush stroke keeps the window answering (issue #519, P-003).
use crate::app::{App, Tool};
use anicraft_engine::geom::Vec2;
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2};
use serde_json::json;
use std::time::Instant;
/// The app on a document, a few frames in, with its clock and the worst frame so far.
struct Rig {
ctx: egui::Context,
app: App,
t: f64,
worst: (f64, String),
log: bool,
}
impl Rig {
fn new(doc: anicraft_engine::doc::Document) -> Rig {
let ctx = egui::Context::default();
let app = App::with_context(&ctx, anicraft_engine::Session::new(doc), Some(std::path::PathBuf::from("unused.png")));
let mut rig = Rig { ctx, app, t: 0.0, worst: (0.0, String::new()), log: false };
for _ in 0..3 {
rig.frame("start", Vec::new());
}
rig.worst = (0.0, String::new());
rig
}
fn frame(&mut self, what: &str, events: Vec<Event>) -> f64 {
self.t += 0.05;
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(self.t), events, ..Default::default() };
let t = Instant::now();
let mut out = self.ctx.run_ui(input, |ui| self.app.frame(ui));
out.textures_delta.clear();
let ms = t.elapsed().as_secs_f64() * 1000.0;
if self.log {
println!("{ms:9.1} ms {what}");
}
if ms > self.worst.0 {
self.worst = (ms, what.to_string());
}
ms
}
/// Where stage point `p` is on screen.
fn at(&self, p: Vec2) -> Pos2 {
let app = &self.app;
let size = vec2(app.s.doc.stage.width as f32, app.s.doc.stage.height as f32);
let origin = app.stage_cache.canvas.center() + app.view.pan - size * app.view.zoom * 0.5;
origin + vec2(p.x, p.y) * app.view.zoom
}
fn button(pos: Pos2, pressed: bool) -> Event {
Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }
}
fn click(&mut self, what: &str, p: Vec2) {
let sp = self.at(p);
self.frame(&format!("{what}: move"), vec![Event::PointerMoved(sp)]);
self.frame(&format!("{what}: press"), vec![Rig::button(sp, true)]);
self.frame(&format!("{what}: release"), vec![Rig::button(sp, false)]);
self.frame(&format!("{what}: after"), Vec::new());
}
fn drag(&mut self, what: &str, from: Vec2, to: Vec2) {
let (a, b) = (self.at(from), self.at(to));
self.frame(&format!("{what}: move"), vec![Event::PointerMoved(a)]);
self.frame(&format!("{what}: press"), vec![Rig::button(a, true)]);
for i in 1..=4 {
self.frame(&format!("{what}: drag"), vec![Event::PointerMoved(a + (b - a) * (i as f32 / 4.0))]);
}
self.frame(&format!("{what}: release"), vec![Rig::button(b, false)]);
for _ in 0..2 {
self.frame(&format!("{what}: after"), Vec::new());
}
}
/// A stage point on the ink, and one in a gap inside the drawing's bounds.
fn ink_and_gap(&self) -> (Vec2, Vec2) {
let b = self.app.s.display_list().items.iter().fold(anicraft_engine::geom::Rect::EMPTY, |r, i| r.union(&i.path.bounds().transformed(&i.transform)));
let grid = |hit: bool| {
(0..4000)
.map(|i| Vec2::new((i * 37 % 1280) as f32, (i * 53 % 720) as f32))
.find(|p| b.inflate(-20.0).contains(*p) && (0..9).all(|k| self.app.s.hit_test(*p + Vec2::new((k % 3 - 1) as f32 * 2.0, (k / 3 - 1) as f32 * 2.0), 0.0).is_some() == hit))
.unwrap_or_default()
};
(grid(true), grid(false))
}
}
/// A fast scribble across the stage, as stage points with pressure: `n` samples.
fn scribble(n: usize) -> Vec<(Vec2, Option<f32>)> {
(0..n).map(|i| i as f32 * 0.06).map(|t| (Vec2::new(640.0 + 420.0 * (t * 0.11).sin() + 170.0 * (t * 0.83).cos(), 360.0 + 200.0 * (t * 0.07).cos() + 130.0 * (t * 0.83).sin()), Some(0.55 + 0.45 * (t * 0.37).sin()))).collect()
}
impl Rig {
/// Draws `samples` with the Brush: a press, the samples, and the release.
fn brush(&mut self, samples: Vec<(Vec2, Option<f32>)>) {
self.app.tool = Tool::Brush;
let (first, last) = (samples.first().map_or(Vec2::ZERO, |s| s.0), samples.last().map_or(Vec2::ZERO, |s| s.0));
let a = self.at(first);
self.frame("brush: move", vec![Event::PointerMoved(a)]);
self.frame("brush: press", vec![Rig::button(a, true)]);
self.frame("brush: drag", vec![Event::PointerMoved(a + vec2(20.0, 12.0))]);
self.frame("brush: drag", vec![Event::PointerMoved(a + vec2(40.0, 24.0))]);
assert_eq!(self.app.drag, crate::app::Drag::Brush, "the press began a stroke");
self.app.brush_samples = samples;
let b = self.at(last);
self.frame("brush: release", vec![Rig::button(b, false)]);
}
/// Frames until no stroke waits (the trace is on another thread), or a long time has passed.
fn until_painted(&mut self) {
let started = Instant::now();
while !self.app.ink.is_empty() && started.elapsed().as_secs() < 120 {
std::thread::sleep(std::time::Duration::from_millis(2));
self.frame("waiting", Vec::new());
}
}
fn shapes(&self) -> usize {
self.app.s.visible_elements().len()
}
}
fn blank() -> Rig {
let mut rig = Rig::new(anicraft_engine::doc::Document::default());
rig.app.s.style.object_drawing = true;
rig
}
/// ADR 0129: when the pointer lifts on a long stroke, the frame does not wait for its outline.
/// The stroke stays on the stage as drawn, and goes into the document, as one undo step, once
/// its outline is traced.
#[test]
fn a_long_stroke_is_painted_after_the_pointer_lifts_without_holding_the_frame() {
let mut rig = blank();
let undo_before = rig.app.s.history().undo_len();
rig.brush(scribble(3000));
assert_eq!(rig.app.ink.len(), 1, "the stroke waits for its outline");
assert_eq!(rig.app.drag, crate::app::Drag::None);
// It is still drawn: the stage paints its sweep, piece by piece.
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 940.0))), time: Some(rig.t + 0.01), ..Default::default() };
let xf = crate::pathtools::Xf { origin: rig.at(Vec2::ZERO), zoom: rig.app.view.zoom };
let mut out = rig.ctx.run_ui(input, |ui| crate::ink::draw(&rig.app, ui.painter(), xf));
out.textures_delta.clear();
assert!(out.shapes.len() > 100, "{} pieces", out.shapes.len());
rig.until_painted();
assert_eq!(rig.shapes(), 1, "painted");
assert_eq!(rig.app.s.history().undo_len(), undo_before + 1, "one undo step");
// A short stroke never waits.
rig.brush(scribble(40));
assert!(rig.app.ink.is_empty());
assert_eq!(rig.shapes(), 2);
}
/// Nothing comes between a stroke and its paint: an edit asked for while it waits finds it in
/// the document already, strokes are painted in the order they were drawn, and a key press
/// (undo, say) acts on the stroke, not on what was there before it.
#[test]
fn edits_wait_for_the_strokes_drawn_before_them() {
let mut rig = blank();
rig.brush(scribble(3000));
rig.brush(scribble(60));
assert_eq!(rig.app.ink.len(), 2, "a short stroke queues behind a waiting one");
// A command: both strokes are in before it runs, the long one first (under the short one).
rig.app.run("edit.select_all", json!({}));
assert!(rig.app.ink.is_empty());
assert_eq!(rig.app.s.selection.len(), 2);
let widths: Vec<f32> = rig.app.s.visible_elements().iter().map(|e| rig.app.s.element_bounds(e.id).width()).collect();
assert!(widths.first() > widths.last(), "drawn first, painted first (the long one is under the short one): {widths:?}");
// A key: the waiting stroke is painted before the key is handled.
let mut rig = blank();
rig.brush(scribble(3000));
assert_eq!(rig.app.ink.len(), 1);
rig.frame("a key", vec![Event::Key { key: egui::Key::F13, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
assert!(rig.app.ink.is_empty());
assert_eq!(rig.shapes(), 1);
// Only a few strokes wait at once: one more paints the oldest first.
let mut rig = blank();
for _ in 0..10 {
rig.brush(scribble(450));
assert!(rig.app.ink.len() <= 8, "{} waiting", rig.app.ink.len());
}
rig.until_painted();
assert_eq!(rig.shapes(), 10, "every stroke was painted");
// Leaving the document: it takes its strokes with it.
let mut rig = blank();
rig.brush(scribble(3000));
crate::ink::flush(&mut rig.app);
assert_eq!(rig.shapes(), 1);
}
/// The reporter's steps and every tool's gesture on the reporter's file
/// (`ANICRAFT_STROKE_FILE`), each from a fresh window: the worst frame of each.
#[test]
#[ignore = "a measurement, not a check"]
fn long_stroke_frame_cost() {
let Ok(file) = std::env::var("ANICRAFT_STROKE_FILE") else { return };
let doc = anicraft_engine::format::load(std::path::Path::new(&file)).expect("the file loads");
let log = std::env::var("ANICRAFT_STROKE_LOG").is_ok();
type Scenario = (&'static str, fn(&mut Rig, Vec2, Vec2));
let scenarios: [Scenario; 12] = [
("move, then click a gap", |r, ink, gap| {
r.app.tool = Tool::Select;
r.drag("move", ink, ink + Vec2::new(40.0, 24.0));
r.click("deselect", gap + Vec2::new(40.0, 24.0));
}),
("click a gap", |r, _, gap| {
r.app.tool = Tool::Select;
r.click("gap", gap);
}),
("marquee over a part", |r, _, gap| {
r.app.tool = Tool::Select;
r.drag("marquee", gap, gap + Vec2::new(260.0, 180.0));
r.click("deselect", gap);
}),
("double-click", |r, ink, _| {
r.app.tool = Tool::Select;
r.click("first", ink);
r.click("second", ink);
}),
("select all, Free Transform", |r, ink, _| {
r.app.tool = Tool::Transform;
r.app.run("edit.select_all", json!({}));
r.frame("selected", Vec::new());
r.drag("move", ink, ink + Vec2::new(30.0, 10.0));
}),
("Subselection click", |r, ink, _| {
r.app.tool = Tool::Subselect;
r.click("ink", ink);
r.frame("shown", Vec::new());
}),
("Paint Bucket in a gap", |r, _, gap| {
r.app.tool = Tool::PaintBucket;
r.click("gap", gap);
}),
("Paint Bucket on the ink", |r, ink, _| {
r.app.tool = Tool::PaintBucket;
r.click("ink", ink);
}),
("Eraser across", |r, ink, _| {
r.app.tool = Tool::Eraser;
r.drag("erase", ink + Vec2::new(-200.0, -80.0), ink + Vec2::new(200.0, 80.0));
}),
("Brush across", |r, ink, _| {
r.app.tool = Tool::Brush;
r.drag("paint", ink + Vec2::new(-200.0, 80.0), ink + Vec2::new(200.0, -80.0));
}),
("Pencil across", |r, ink, _| {
r.app.tool = Tool::Pencil;
r.drag("draw", ink + Vec2::new(-200.0, 60.0), ink + Vec2::new(200.0, -60.0));
}),
("Rectangle over", |r, ink, _| {
r.app.tool = Tool::Rect;
r.drag("draw", ink + Vec2::new(-100.0, -60.0), ink + Vec2::new(100.0, 60.0));
r.app.tool = Tool::Select;
r.frame("select tool", Vec::new());
}),
];
for (name, run) in scenarios {
let mut rig = Rig::new(doc.clone());
rig.log = log;
let (ink, gap) = rig.ink_and_gap();
let t = Instant::now();
run(&mut rig, ink, gap);
println!("{:9.1} ms worst ({}), {:8.1} ms in all, {} elements <- {name}", rig.worst.0, rig.worst.1, t.elapsed().as_secs_f64() * 1000.0, rig.app.s.visible_elements().len());
}
}
+3
View File
@@ -525,4 +525,7 @@ mod parenting_ui_tests;
#[cfg(test)]
mod tilt_ui_tests;
#[cfg(test)]
mod long_stroke_tests;
mod ink;
#[cfg(test)]
mod zoom_tests;
+114 -3
View File
@@ -781,7 +781,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
Drag::BindMarquee { start, cur } => crate::bind_tool::drag_end(app, start, cur, shift, command),
Drag::BindPaint { .. } => crate::bind_tool::paint_end(app),
Drag::Pencil => crate::pathtools::commit_pencil(app, xf),
Drag::Brush => crate::brushtool::commit(app, xf),
Drag::Brush => crate::brushtool::commit(app, ui.ctx(), xf),
Drag::Eraser => crate::erasertool::commit(app, xf),
// Raw shapes merge where they landed, in the drag's step (ADR 0051).
Drag::MultiMove { .. } | Drag::MultiTransform { .. } => crate::onion::drag_end(app),
@@ -836,7 +836,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
Tool::Brush if !panning => {
// A click paints a dab.
crate::brushtool::start(app, to_v(sp), pressure, now);
crate::brushtool::commit(app, xf);
crate::brushtool::commit(app, ui.ctx(), xf);
}
Tool::Eraser if !panning => {
if app.eraser.faucet {
@@ -1399,6 +1399,8 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
crate::widthtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p)));
crate::gradient_tool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning));
crate::shape_envelope::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning));
// Strokes on their way into the document (ADR 0129), under the one in hand.
crate::ink::draw(app, &painter, xf);
crate::brushtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused));
crate::erasertool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p) && !panning && !paused));
// After this frame's edits, so a drag on the path shows where it is now.
@@ -2637,16 +2639,33 @@ fn exclude_overlying_artwork(fills: &mut Vec<Rect>, above: &[anicraft_engine::do
/// Remove areas covered by `occluders` from a collection of rectangles.
/// Each overlapping rectangle may produce up to four smaller rectangles.
///
/// Both lists are rows of runs, thousands of each for a long brush stroke, so a span is only
/// compared with the occluders in its own rows: they are looked up by their top edge. Comparing
/// every span with every occluder took seconds a frame on such a stroke (#519).
fn subtract_spans(spans: &mut Vec<Rect>, occluders: &[Rect]) {
let mut remaining = Vec::new();
let mut pieces = Vec::new();
let mut next = Vec::new();
// The occluders by top edge (their order among equals kept), and the tallest of them: one
// that reaches down into a span starts less than that above the span's top.
let mut by_top: Vec<usize> = (0..occluders.len()).collect();
let top_of = |i: usize| occluders.get(i).map_or(f32::INFINITY, |o| o.top());
by_top.sort_by(|&a, &b| top_of(a).total_cmp(&top_of(b)));
let tallest = occluders.iter().fold(0.0f32, |h, o| h.max(o.height()));
let mut rows: Vec<usize> = Vec::new();
for span in spans.drain(..) {
pieces.clear();
pieces.push(span);
let from = by_top.partition_point(|&i| top_of(i) <= span.top() - tallest);
let to = by_top.partition_point(|&i| top_of(i) < span.bottom());
rows.clear();
rows.extend(by_top.get(from..to).unwrap_or(&[]));
// In the order they were given, so the pieces come out as they always did.
rows.sort_unstable();
for &occluder in occluders {
for &occluder in rows.iter().filter_map(|&i| occluders.get(i)) {
// Skip occluders that cannot touch the original span.
let overlap = span.intersect(occluder);
if overlap.width() <= 0.0 || overlap.height() <= 0.0 {
@@ -2790,6 +2809,34 @@ mod pattern_tests {
}
}
/// #519: occluders are looked up by row instead of each being tried against every span.
/// What is left is the same as trying them all: every point of a span is kept exactly when
/// no occluder covers it, whatever the occluders' heights and order.
#[test]
fn spans_lose_exactly_what_the_occluders_in_their_rows_cover() {
// A fixed scatter: rows of runs, and occluders one row to many rows tall, unsorted.
let n = |i: u32, k: u32, m: u32| (i.wrapping_mul(2_654_435_761).wrapping_add(k.wrapping_mul(40_503)) >> 7) % m;
let spans: Vec<Rect> = (0..300).map(|i| Rect::from_min_size(pos2(n(i, 1, 180) as f32, (n(i, 2, 50) * 4) as f32), vec2(4.0 + n(i, 3, 40) as f32, 4.0))).collect();
let occluders: Vec<Rect> = (0..400).map(|i| Rect::from_min_size(pos2(n(i, 4, 190) as f32 + 0.5, n(i, 5, 200) as f32 + 0.25), vec2(1.0 + n(i, 6, 25) as f32, if i % 7 == 0 { 30.0 } else { 1.0 }))).collect();
let mut left = spans.clone();
subtract_spans(&mut left, &occluders);
let inside = |rects: &[Rect], p: Pos2| rects.iter().any(|r| r.contains(p));
let mut kept = 0;
for y in 0..420 {
for x in 0..460 {
let p = pos2(x as f32 * 0.5 + 0.13, y as f32 * 0.5 + 0.11);
let want = inside(&spans, p) && !inside(&occluders, p);
assert_eq!(inside(&left, p), want, "at {p:?}");
kept += usize::from(want);
}
}
assert!(kept > 1000, "the scatter leaves something to compare: {kept}");
// Nothing to take away leaves the spans as they were.
let mut same = spans.clone();
subtract_spans(&mut same, &[]);
assert_eq!(same, spans);
}
/// A thin opaque foreground shape must hide the selection
/// backing of artwork behind it, even between stipple rows.
#[test]
@@ -5367,6 +5414,70 @@ mod pointer_tests {
assert_eq!((icon, arrowheads), (CursorIcon::Move, 0), "inside the box: move");
}
/// #117: a symbol instance that is skewed still answers Free Transform on the stage. Its
/// box is the slanted one its artwork has, the handles are on that box's corners, and a
/// drag from a corner scales it, one from just outside a corner turns it, and one on an
/// edge skews it further: each changes the instance, and each is one undo step.
#[test]
fn free_transform_handles_work_on_a_skewed_symbol() {
let (mut app, ctx, at) = scene();
app.run("edit.select_all", json!({}));
app.run("edit.delete", json!({}));
app.run("draw.rect", json!({"x": 300, "y": 200, "w": 200, "h": 100, "fill": "#3366ff", "stroke": null, "object": true}));
app.run("modify.convert_to_symbol", json!({"name": "Slanted"}));
// Slant it: the top slides right of the bottom.
app.run("modify.transform", json!({"a": 1, "b": 0, "c": -0.6, "d": 1, "e": 150, "f": 0}));
app.tool = Tool::Transform;
let mut t = 2.0;
let mut frame = |app: &mut App, events: Vec<Event>| {
t += 0.05;
run_frame(&ctx, app, t, events);
};
frame(&mut app, Vec::new());
let instance = |app: &App| app.s.selected_elements().first().map(|(_, e)| e.transform).expect("the instance is selected");
let box_of = |app: &App| crate::xform::frame(app).expect("a selection has a box");
let slanted = box_of(&app);
let [tl, tr, br, bl] = slanted.corners();
assert!((tl.x - bl.x).abs() > 30.0 && (tl.y - tr.y).abs() < 1.0, "the box slants with the instance: {tl:?} {tr:?} {br:?} {bl:?}");
let mut drag = |app: &mut App, from: Vec2, to: Vec2| {
let (a, b) = (at(from.x, from.y), at(to.x, to.y));
frame(app, vec![Event::PointerMoved(a)]);
frame(app, vec![button(a, true)]);
for i in 1..=5 {
frame(app, vec![Event::PointerMoved(a + (b - a) * (i as f32 / 5.0))]);
}
frame(app, vec![button(b, false)]);
frame(app, Vec::new());
};
let steps = |app: &App| app.s.history().undo_len();
// The bottom right corner, pulled away from the box: larger, and still as slanted.
let (before, undo) = (instance(&app).decompose(), steps(&app));
let out = (br - tl).normalized() * 60.0;
drag(&mut app, br, br + out);
let after = instance(&app).decompose();
assert!(after.sx > before.sx * 1.1 && after.sy > before.sy * 1.1, "scaled from the corner handle: {before:?} to {after:?}");
assert_eq!(steps(&app), undo + 1, "one undo step");
let now = box_of(&app);
assert!(now.corners()[0].distance(tl) < 1.0, "the opposite corner stays where it was");
// Just outside the top right corner: a turn.
let (before, undo) = (instance(&app).decompose(), steps(&app));
let [_, tr, _, _] = now.corners();
let outside = tr + (tr - now.handle(0, 0)).normalized() * (14.0 / app.view.zoom);
drag(&mut app, outside, outside + Vec2::new(40.0, 120.0));
let after = instance(&app).decompose();
assert!((after.rotation - before.rotation).abs().to_degrees() > 5.0, "turned from outside the corner: {before:?} to {after:?}");
assert_eq!(steps(&app), undo + 1);
// The top edge between its handles, slid along itself: more slant, the bottom edge kept.
let now = box_of(&app);
let (undo, bottom) = (steps(&app), now.handle(0, 1));
let on_edge = now.handle(-1, -1).lerp(now.handle(0, -1), 0.5);
let along = (now.handle(1, -1) - now.handle(-1, -1)).normalized() * 50.0;
drag(&mut app, on_edge, on_edge + along);
let skewed = box_of(&app);
assert!(skewed.handle(0, -1).distance(now.handle(0, -1)) > 20.0 && skewed.handle(0, 1).distance(bottom) < 1.0, "the top edge slid, the bottom stayed");
assert_eq!(steps(&app), undo + 1);
}
/// A double-click: press, release, `gap` seconds, press, release (each its own frame).
fn double_click(gap: f64) -> App {
let (mut app, ctx, at) = scene();
+2
View File
@@ -272,6 +272,8 @@ fn busy(app: &App) -> Option<&'static str> {
/// Finishes what is in progress on the shown document, before it is put aside or closed: text
/// being typed and a pen path are kept, playback stops, an open drag ends its undo step.
fn settle(app: &mut App) {
// Brush strokes on their way into this document (ADR 0129).
crate::ink::flush(app);
if app.playing {
app.toggle_play();
}
+1
View File
@@ -25,6 +25,7 @@ pub(crate) fn safe_to_install(app: &crate::app::App) -> bool {
&& app.pen.is_none()
&& app.pencil.is_empty()
&& app.brush_samples.is_empty()
&& app.ink.is_empty()
&& app.raw_touched.is_empty()
&& app.drag == crate::app::Drag::None
&& app.motion_drag.is_none()