mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-21 18:12:28 +01:00
Merge pull request #96 from storytold/m7/eraser-eyedropper
feat(draw): Eraser and Eyedropper tools (M7)
This commit is contained in:
26 files changed
+1472
-104
No files matched your search
+2
-1
@@ -19,7 +19,7 @@ shaders or SDK code).
|
||||
| Hack Regular (via `epaint_default_fonts`) | UI monospace font | Source Foundry Authors; Bitstream (Vera) | <https://github.com/source-foundry/Hack> | MIT + Bitstream Vera licence, [`licenses/fonts/LICENSE-Hack.txt`](licenses/fonts/LICENSE-Hack.txt) |
|
||||
| Noto Emoji (via `epaint_default_fonts`) | Symbol fallback | Google | <https://github.com/googlefonts/noto-emoji> | SIL OFL 1.1, [`licenses/fonts/OFL-1.1-NotoEmoji.txt`](licenses/fonts/OFL-1.1-NotoEmoji.txt) |
|
||||
| emoji-icon-font (via `epaint_default_fonts`) | Symbol fallback | John Slegers | <https://github.com/jslegers/emoji-icon-font> | MIT, [`licenses/fonts/LICENSE-emoji-icon-font.txt`](licenses/fonts/LICENSE-emoji-icon-font.txt) |
|
||||
| `assets/icons/anicraft-*.svg` (13 files: align, distribute, mask and masked layer, width tool, camera, brush) | Align panel, layer-type, Width tool, Camera and Brush tool icons | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style | MIT OR Apache-2.0 |
|
||||
| `assets/icons/anicraft-*.svg` (15 files: align, distribute, mask and masked layer, width tool, camera, brush, eraser, eyedropper) | Align panel, layer-type, Width tool, Camera, Brush, Eraser and Eyedropper tool icons | AniCraft contributors | Original work, drawn on Lucide's 24-unit grid and stroke style | MIT OR Apache-2.0 |
|
||||
| `crates/svg/fixtures/clips-masks-text.svg` | SVG import test drawing (clip paths, a mask, text) | AniCraft contributors | Original work | MIT OR Apache-2.0 |
|
||||
| `assets/icons/*.svg` except `anicraft-*` (33 files: tools, transport, layer toggles, folders, guide, image, text, sound, chevrons) | UI icons, stroked by `src/icons.rs` | Lucide Icons and Contributors (some derived from Feather by Cole Bemis) | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`), copied unchanged from the PhotoCraft sibling project's set (`volume-2.svg` from Lucide 0.512.0) | ISC (Lucide) and MIT (Feather), [`licenses/icons/LICENSE-lucide.txt`](licenses/icons/LICENSE-lucide.txt) |
|
||||
| `assets/app-icon/` (`anicraft.svg`, `anicraft-small.svg` and every render: PNGs, `anicraft.ico`, `hicolor/`) | App icon (engraved rabbit): window, Dock, taskbar, `anicraft.exe`, Help › About | Project owner (ArtCraft team) | Original artwork drawn in ArtCraft for AniCraft, vectorised by `assets/app-icon/trace.py` and rendered by `scripts/icons.sh` | MIT OR Apache-2.0 ([`assets/app-icon/LICENSE.txt`](assets/app-icon/LICENSE.txt)) |
|
||||
@@ -95,6 +95,7 @@ OR Apache-2.0) is noted in the table.
|
||||
| Monotone cubic interpolation of stroke widths (width profiles) | `crates/doc/src/width.rs` | F. N. Fritsch and R. E. Carlson, *Monotone Piecewise Cubic Interpolation*, SIAM J. Numer. Anal. 17(2), 1980 | Published algorithm (harmonic-mean tangents). |
|
||||
| Variable-width stroke outlines (trapezoids, outer round joins, caps) | `crates/render/src/stroke.rs` | Standard stroking construction from the public computer-graphics literature | Own implementation (ADR 0018); built-in profiles are AniCraft's own. |
|
||||
| Brush outlines (the swept tip as a signed distance field: exact distance to the convex hull of two tips, L2 for round and L∞ for square tips, minimised in closed form; traced at level zero) | `crates/geom/src/brush.rs` | Standard sweep and distance-field constructions from the public computer-graphics literature; behaviour of Animate's Brush tool learned from Adobe's public help and observation | Own implementation (ADR 0033); no Adobe code or presets. |
|
||||
| Eraser (the swept tip as a fill in the planar merge whose regions are dropped; exact fill areas by Green's theorem with five-point Gauss–Legendre quadrature) and Eyedropper | `crates/engine/src/cmds_erase.rs`, `crates/engine/src/cmds_paint.rs` | Green's theorem and Gauss–Legendre quadrature (public mathematical results); behaviour of Animate's Eraser and Eyedropper learned from Adobe's public help and observation | Own implementation (ADR 0034); no Adobe code or presets. |
|
||||
| WebAssembly plug-in host (module validation, limits, fuel, resumable host calls) | `crates/plugins` | W3C WebAssembly Core Specification 1.0 / 2.0 (W3C Royalty-Free Patent Policy); the `wasmi` interpreter (MIT OR Apache-2.0) | Host model ported from PhotoCraft's filter plug-ins (same project family and licence) and extended with the AniCraft request ABI (ADR 0017). |
|
||||
| De Casteljau subdivision, Ramer–Douglas–Peucker simplification | `crates/geom/src/edit.rs` | Public mathematical results (de Casteljau 1959; Ramer 1972; Douglas & Peucker 1973) | |
|
||||
| WAV (RIFF WAVE) reading and writing: PCM 8/16/24/32-bit, IEEE float, `WAVE_FORMAT_EXTENSIBLE` | `crates/audio/src/wav.rs` | Microsoft/IBM, *Multimedia Programming Interface and Data Specifications 1.0* (1991), and Microsoft's public `WAVE_FORMAT_EXTENSIBLE` description | Public file format descriptions. |
|
||||
|
||||
@@ -2,6 +2,26 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
* **Eraser and Eyedropper** (E and I, ADR 0034, first slice).
|
||||
* The Eraser sweeps the same tip as the Brush and takes what it covers out of the lines and
|
||||
fills on the active layer that were drawn with Object Drawing off. Drawing objects,
|
||||
symbols and text are kept, as in Animate.
|
||||
* Erase modes: Erase Normal, Erase Fills, Erase Lines, Erase Selected Fills and Erase Inside
|
||||
(only the fill where the stroke starts).
|
||||
* The Faucet option deletes a whole fill or line with one click.
|
||||
* Double-clicking the Eraser tool, or Erase Everything… in its options, clears the visible,
|
||||
unlocked layers at this frame. It asks first, and you can undo it.
|
||||
* The erased area shows as you drag, `[` and `]` change the size, and each stroke is one
|
||||
undo step. A stroke that erases nothing leaves no undo step.
|
||||
* The Eyedropper picks a fill's colour, gradient or bitmap into the fill swatch, or a line's
|
||||
colour, width and width profile into the stroke settings. It then becomes the Paint Bucket
|
||||
or the Ink Bottle.
|
||||
* A picked gradient stays where it is on the stage, so it carries on across the shapes you
|
||||
pour it into.
|
||||
* With shapes selected, the Eyedropper applies the picked style to them. Shift-click picks
|
||||
into the other swatch only.
|
||||
* For scripts and AI assistants: `draw.erase`, `draw.faucet`, `draw.erase_all`,
|
||||
`paint.pick` and `paint.apply_style`.
|
||||
* **Brush tool** (B, ADR 0033, first slice). The brush paints filled shapes in the fill colour,
|
||||
as Animate's Brush tool does: the shape is exactly the area the tip sweeps along the drag.
|
||||
* Tip options: round or square, size, angle and roundness (for oval and flat calligraphic
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M13.5 4.5 L20.5 11.5 L11 21 L4 14 Z" />
|
||||
<path d="M7.3 10.7 L14.3 17.7" />
|
||||
<path d="M14 21 H20" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 302 B |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M11 6 L18 13" />
|
||||
<path d="M12.5 7.5 L15.5 4.5 A2.85 2.85 0 0 1 19.5 8.5 L16.5 11.5" />
|
||||
<path d="M13 9 L5 17 L5 19 L7 19 L15 11" />
|
||||
<path d="M3 21 L3.01 21" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 365 B |
@@ -124,6 +124,18 @@ impl Paint {
|
||||
}
|
||||
}
|
||||
|
||||
/// The paint carried by `m` (its geometry moved from one space to another), so a shape in
|
||||
/// the new space shows it where it was: gradient ends and centre are mapped, a radial
|
||||
/// gradient's radius scales by the mean scale, a bitmap's matrix is composed.
|
||||
pub fn transformed(&self, m: &Affine) -> Paint {
|
||||
match self {
|
||||
Paint::Solid(_) => self.clone(),
|
||||
Paint::Linear { start, end, stops } => Paint::Linear { start: m.apply(*start), end: m.apply(*end), stops: stops.clone() },
|
||||
Paint::Radial { center, radius, stops } => Paint::Radial { center: m.apply(*center), radius: radius * m.mean_scale(), stops: stops.clone() },
|
||||
Paint::Bitmap { bitmap, repeat, matrix } => Paint::Bitmap { bitmap: *bitmap, repeat: *repeat, matrix: m.mul(matrix) },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lerp(&self, o: &Paint, t: f32) -> Paint {
|
||||
let lerp_stops = |a: &[GradientStop], b: &[GradientStop]| -> Option<Vec<GradientStop>> {
|
||||
(a.len() == b.len()).then(|| {
|
||||
|
||||
@@ -72,7 +72,7 @@ impl PaintMode {
|
||||
}
|
||||
}
|
||||
|
||||
fn samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
pub(crate) fn samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
let bad = || EngineError::Param("param 'points' must be a list of [x, y] or [x, y, pressure]".into());
|
||||
let list = p.get("points").and_then(Value::as_array).ok_or_else(bad)?;
|
||||
if list.is_empty() {
|
||||
@@ -97,7 +97,7 @@ fn samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ranged(p: &Value, key: &str, range: std::ops::RangeInclusive<f32>, default: f32) -> Result<f32> {
|
||||
pub(crate) fn ranged(p: &Value, key: &str, range: std::ops::RangeInclusive<f32>, default: f32) -> Result<f32> {
|
||||
match opt_f32(p, key)? {
|
||||
None => Ok(default),
|
||||
Some(v) if range.contains(&v) => Ok(v),
|
||||
@@ -105,24 +105,37 @@ fn ranged(p: &Value, key: &str, range: std::ops::RangeInclusive<f32>, default: f
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// The stroke's samples, refused when they reach too far.
|
||||
pub(crate) fn bounded_samples(p: &Value) -> Result<Vec<Sample>> {
|
||||
let pts = samples(p)?;
|
||||
let mut bounds = anicraft_geom::Rect::EMPTY;
|
||||
pts.iter().for_each(|x| bounds.include(x.at));
|
||||
if bounds.width() > MAX_EXTENT || bounds.height() > MAX_EXTENT || bounds.min.x.abs().max(bounds.max.x.abs()).max(bounds.min.y.abs()).max(bounds.max.y.abs()) > MAX_EXTENT {
|
||||
return Err(EngineError::Param("the stroke is too large".into()));
|
||||
}
|
||||
Ok(pts)
|
||||
}
|
||||
|
||||
/// The tip from `size`, `shape`, `angle` and `roundness` (shared with the Eraser, ADR 0034).
|
||||
pub(crate) fn tip(p: &Value) -> Result<Tip> {
|
||||
let size = ranged(p, "size", SIZE_RANGE, 10.0)?;
|
||||
let shape = match opt_str(p, "shape")?.unwrap_or("round") {
|
||||
"round" => TipShape::Round,
|
||||
"square" => TipShape::Square,
|
||||
other => return Err(EngineError::Param(format!("unknown brush shape '{other}' (round or square)"))),
|
||||
other => return Err(EngineError::Param(format!("unknown tip shape '{other}' (round or square)"))),
|
||||
};
|
||||
let angle = opt_f32(p, "angle")?.unwrap_or(0.0);
|
||||
if !angle.is_finite() || angle.abs() > 1e6 {
|
||||
return Err(EngineError::Param("param 'angle' must be a finite number of degrees".into()));
|
||||
}
|
||||
let roundness = ranged(p, "roundness", 5.0..=100.0, 100.0)?;
|
||||
Ok(Tip { shape, size, angle, roundness: roundness / 100.0 })
|
||||
}
|
||||
|
||||
fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = bounded_samples(p)?;
|
||||
let tip = tip(p)?;
|
||||
let size = tip.size;
|
||||
let smoothing = ranged(p, "smoothing", 0.0..=100.0, 50.0)?;
|
||||
let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?;
|
||||
let mode_key = opt_str(p, "mode")?.unwrap_or("normal");
|
||||
@@ -130,7 +143,6 @@ fn draw_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let color = opt_color(p, "color")?.unwrap_or(s.style.fill);
|
||||
let object = object_param(s, p)?;
|
||||
|
||||
let tip = Tip { shape, size, angle, roundness: roundness / 100.0 };
|
||||
// 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
|
||||
|
||||
@@ -55,7 +55,8 @@ pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option<Pain
|
||||
} else {
|
||||
match opt_color(p, "fill")? {
|
||||
Some(c) => Some(Paint::Solid(c)),
|
||||
None => s.style.use_fill.then_some(Paint::Solid(s.style.fill)),
|
||||
// The fill swatch, in stage space (`add_shape` maps it into the shape).
|
||||
None => s.style.use_fill.then(|| s.style.fill_paint()),
|
||||
}
|
||||
};
|
||||
let width = match opt_f32(p, "stroke_width")? {
|
||||
@@ -63,7 +64,7 @@ pub(crate) fn style(s: &Session, p: &Value, closed: bool) -> Result<(Option<Pain
|
||||
Some(_) => return Err(EngineError::Param("param 'stroke_width' must be in 0..=1000".into())),
|
||||
None => s.style.stroke_width,
|
||||
};
|
||||
let profile = opt_profile(p, "profile")?.unwrap_or_else(|| s.style.stroke_profile.profile());
|
||||
let profile = opt_profile(p, "profile")?.unwrap_or_else(|| s.style.profile());
|
||||
let stroke = if p.get("stroke").is_some_and(Value::is_null) || width <= 0.0 {
|
||||
None
|
||||
} else {
|
||||
@@ -95,6 +96,9 @@ fn rect_params(p: &Value) -> Result<(f32, f32, f32, f32)> {
|
||||
/// (Object Drawing), it merges with the raw shapes it touches (ADR 0031), and the pieces of it
|
||||
/// that come out are selected.
|
||||
pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2, fill: Option<Paint>, stroke: Option<Stroke>, object: bool) -> Result<Value> {
|
||||
// A gradient or bitmap from the fill swatch is in stage space: it stays where it is on the
|
||||
// stage (Animate's Lock Fill after the Eyedropper).
|
||||
let fill = fill.map(|f| f.transformed(&Affine::translate(-origin.x, -origin.y)));
|
||||
let merge = !object && crate::merge::can_merge(fill.as_ref(), stroke.as_ref());
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
@@ -301,13 +305,13 @@ fn set_stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(EngineError::Param("param 'width' must be in 0..=1000".into()));
|
||||
}
|
||||
let profile = opt_profile(p, "profile")?;
|
||||
let default = s.style;
|
||||
let default = s.style.clone();
|
||||
for sh in shapes_mut(s)? {
|
||||
if remove {
|
||||
sh.stroke = None;
|
||||
continue;
|
||||
}
|
||||
let mut st = sh.stroke.take().unwrap_or_else(|| Stroke::new(default.stroke, default.stroke_width).with_profile(default.stroke_profile.profile()));
|
||||
let mut st = sh.stroke.take().unwrap_or_else(|| Stroke::new(default.stroke, default.stroke_width).with_profile(default.profile()));
|
||||
if let Some(c) = color {
|
||||
st.color = c;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
//! The Eraser's commands (ADR 0034). The eraser sweeps the Brush's tip (ADR 0033) and takes
|
||||
//! the area it covers out of the raw shapes on the active layer (ADR 0031): the swept outline
|
||||
//! goes into the planar merge as a fill whose regions come out empty, placed by the erase mode.
|
||||
//! Drawing objects, symbols and text are left alone, as in Animate.
|
||||
|
||||
use crate::cmds_brush::{bounded_samples, ranged, tip};
|
||||
use crate::merge::{self, Part, mergeable, reach};
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind, LayerKind};
|
||||
use anicraft_geom::brush::outline;
|
||||
use anicraft_geom::planar::SNAP;
|
||||
use anicraft_geom::{Affine, Path, PathCmd, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c("draw.erase", "Eraser", "", None, "{points: [[x, y] or [x, y, pressure], ..] (one point erases a dab), size? (stage units, default 10), shape?: round|square, angle?, roundness?, mode?: normal|fills|lines|selected_fills|inside (Erase Normal takes fills and lines, Erase Fills leaves lines, Erase Lines leaves fills, Erase Selected Fills only the selected fills, Erase Inside only the fill the stroke starts on), unit? (stage units per screen point)} erases from the raw shapes on the active layer; drawing objects, symbols and text are kept", true, erase as crate::RunFn),
|
||||
c("draw.faucet", "Faucet", "", None, "{x, y, slop?} deletes the whole raw fill or stroke under the point on the active layer", true, faucet),
|
||||
c("draw.erase_all", "Erase Everything", "", None, "{} clears every visible, unlocked layer at the playhead (asks first; undoable)", true, erase_all),
|
||||
]
|
||||
}
|
||||
|
||||
/// An erase mode (Animate's names).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum EraseMode {
|
||||
#[default]
|
||||
Normal,
|
||||
Fills,
|
||||
Lines,
|
||||
SelectedFills,
|
||||
Inside,
|
||||
}
|
||||
|
||||
impl EraseMode {
|
||||
pub const ALL: [EraseMode; 5] = [EraseMode::Normal, EraseMode::Fills, EraseMode::Lines, EraseMode::SelectedFills, EraseMode::Inside];
|
||||
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
EraseMode::Normal => "normal",
|
||||
EraseMode::Fills => "fills",
|
||||
EraseMode::Lines => "lines",
|
||||
EraseMode::SelectedFills => "selected_fills",
|
||||
EraseMode::Inside => "inside",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
EraseMode::Normal => "Erase Normal",
|
||||
EraseMode::Fills => "Erase Fills",
|
||||
EraseMode::Lines => "Erase Lines",
|
||||
EraseMode::SelectedFills => "Erase Selected Fills",
|
||||
EraseMode::Inside => "Erase Inside",
|
||||
}
|
||||
}
|
||||
pub fn hint(self) -> &'static str {
|
||||
match self {
|
||||
EraseMode::Normal => "Erases lines and fills on the layer.",
|
||||
EraseMode::Fills => "Erases fills only, leaving lines alone.",
|
||||
EraseMode::Lines => "Erases lines only, leaving fills alone.",
|
||||
EraseMode::SelectedFills => "Erases only the selected fills.",
|
||||
EraseMode::Inside => "Erases only inside the fill where the stroke starts.",
|
||||
}
|
||||
}
|
||||
pub fn from_key(k: &str) -> Option<EraseMode> {
|
||||
EraseMode::ALL.into_iter().find(|m| m.key() == k)
|
||||
}
|
||||
}
|
||||
|
||||
fn erase(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let pts = bounded_samples(p)?;
|
||||
let tip = tip(p)?;
|
||||
let unit = ranged(p, "unit", 0.001..=1000.0, 1.0)?;
|
||||
let mode_key = opt_str(p, "mode")?.unwrap_or("normal");
|
||||
let mode = EraseMode::from_key(mode_key).ok_or_else(|| EngineError::Param(format!("unknown erase mode '{mode_key}' (normal, fills, lines, selected_fills or inside)")))?;
|
||||
let start = pts.first().map_or(Vec2::ZERO, |x| x.at);
|
||||
// The eraser follows the hand (a third of a screen point), fitted as finely as the brush.
|
||||
let path = outline(&pts, &tip, unit * 0.3, (unit * 0.35).min(tip.size * 0.01));
|
||||
if !path.cmds.iter().any(|c| matches!(c, PathCmd::CubicTo(..) | PathCmd::LineTo(..))) {
|
||||
return Err(EngineError::Param("the stroke is too small to erase with".into()));
|
||||
}
|
||||
erase_with(s, &path, mode, start)
|
||||
}
|
||||
|
||||
/// Erases `eraser` (keyframe space) from the active layer's raw shapes, as `mode` says.
|
||||
pub(crate) fn erase_with(s: &mut Session, eraser: &Path, mode: EraseMode, start: Vec2) -> Result<Value> {
|
||||
let nothing = |why: &str| Ok(json!({"erased": false, "mode": mode.key(), "elements": [], "reason": why}));
|
||||
// Nothing may change when nothing is erased (no keyframe made, no undo step).
|
||||
let before = s.doc.clone();
|
||||
let els = s.editable_keyframe()?.elements.clone();
|
||||
let area = eraser.bounds().inflate(2.0 * SNAP);
|
||||
let touching: Vec<usize> = (0..els.len()).filter(|&i| els.get(i).and_then(|e| mergeable(e).map(|sh| !reach(sh, &e.transform).intersect(&area).is_empty())).unwrap_or(false)).collect();
|
||||
let el = |i: &usize| els.get(*i).map(|e| e.as_ref());
|
||||
let is_fill = |i: &usize| el(i).and_then(mergeable).is_some_and(|sh| sh.fill.is_some());
|
||||
let fills: Vec<usize> = touching.iter().copied().filter(is_fill).collect();
|
||||
let lines: Vec<usize> = touching.iter().copied().filter(|i| !is_fill(i)).collect();
|
||||
// What the eraser takes from (it sits right above them), and what goes into the merge.
|
||||
let (targets, members): (Vec<usize>, Vec<usize>) = match mode {
|
||||
EraseMode::Normal => (touching.clone(), touching.clone()),
|
||||
EraseMode::Fills => (fills.clone(), touching.clone()),
|
||||
// Only the lines take part, so the fills stay exactly as they are.
|
||||
EraseMode::Lines => (lines.clone(), lines.clone()),
|
||||
EraseMode::SelectedFills => (fills.iter().copied().filter(|i| el(i).is_some_and(|e| s.selection.contains(&e.id))).collect(), touching.clone()),
|
||||
EraseMode::Inside => {
|
||||
// The topmost raw fill under the start of the stroke.
|
||||
let at = fills.iter().rev().copied().find(|i| el(i).is_some_and(|e| mergeable(e).is_some_and(|sh| sh.path.contains(start, &e.transform, sh.fill_rule))));
|
||||
(at.into_iter().collect(), touching.clone())
|
||||
}
|
||||
};
|
||||
if targets.is_empty() {
|
||||
s.doc = before;
|
||||
return nothing(match mode {
|
||||
EraseMode::SelectedFills if s.selection.is_empty() => "select the fills to erase first",
|
||||
EraseMode::Inside => "start the stroke on a fill to erase inside it",
|
||||
_ => "nothing raw to erase there",
|
||||
});
|
||||
}
|
||||
// Bottom to top: the targets, the eraser, then the rest (fills before lines, so lines still
|
||||
// cut the fills they cross and nothing hides them).
|
||||
let rest: Vec<usize> = members.iter().copied().filter(|i| !targets.contains(i)).collect();
|
||||
let (rest_fills, rest_lines): (Vec<usize>, Vec<usize>) = rest.into_iter().partition(is_fill);
|
||||
let selected = s.selection.clone();
|
||||
let shape = |i: &usize| el(i).map(|e| Part::Shape(e, selected.contains(&e.id)));
|
||||
let parts: Vec<Part> = targets.iter().filter_map(shape).chain(std::iter::once(Part::Eraser(eraser))).chain(rest_fills.iter().filter_map(shape)).chain(rest_lines.iter().filter_map(shape)).collect();
|
||||
let Some((out, picked)) = merge::remerge(s, &parts) else {
|
||||
s.doc = before;
|
||||
return Err(EngineError::State("there is too much artwork under the eraser to erase at once; erase a smaller area".into()));
|
||||
};
|
||||
// Erased nothing (the eraser only came near): leave the drawing as it was.
|
||||
let was = measure(members.iter().filter_map(el));
|
||||
let now = measure(out.iter().map(|e| e.as_ref()));
|
||||
let close = |a: f64, b: f64| (a - b).abs() <= 1e-3 + 1e-7 * a.abs().max(b.abs());
|
||||
if close(was.0, now.0) && close(was.1, now.1) {
|
||||
s.doc = before;
|
||||
return nothing("nothing raw to erase there");
|
||||
}
|
||||
let ids: Vec<u64> = out.iter().map(|e| e.id.0).collect();
|
||||
let gone: Vec<ElementId> = members.iter().filter_map(el).map(|e| e.id).collect();
|
||||
merge::replace(s, &members, out, false)?;
|
||||
// What stays selected: the rest of the selection, and what is left of selected shapes.
|
||||
s.selection.retain(|id| !gone.contains(id));
|
||||
s.selection.extend(picked);
|
||||
Ok(json!({"erased": true, "mode": mode.key(), "elements": ids, "area_erased": (was.0 - now.0).max(0.0), "length_erased": (was.1 - now.1).max(0.0)}))
|
||||
}
|
||||
|
||||
/// Total fill area and stroke length of raw shapes, in keyframe space. Fill areas are exact
|
||||
/// (Green's theorem with Gauss–Legendre nodes, exact for cubics); lengths are by Gauss–Legendre
|
||||
/// too, so a shape that comes back from the merge unchanged measures exactly the same.
|
||||
fn measure<'a>(els: impl Iterator<Item = &'a Element>) -> (f64, f64) {
|
||||
let (mut area, mut length) = (0.0, 0.0);
|
||||
for e in els {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
if sh.fill.is_some() {
|
||||
area += signed_area(&sh.path, &e.transform).abs();
|
||||
}
|
||||
if sh.stroke.is_some() {
|
||||
length += path_length(&sh.path, &e.transform);
|
||||
}
|
||||
}
|
||||
(area, length)
|
||||
}
|
||||
|
||||
/// The path's segments as cubics, in the space `m` maps to (closing segments included).
|
||||
fn cubics(path: &Path, m: &Affine) -> Vec<[Vec2; 4]> {
|
||||
let mut out = Vec::new();
|
||||
let (mut start, mut cur) = (Vec2::ZERO, Vec2::ZERO);
|
||||
let line = |a: Vec2, b: Vec2| [a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b];
|
||||
for c in &path.cmds {
|
||||
match *c {
|
||||
PathCmd::MoveTo(p) => {
|
||||
start = m.apply(p);
|
||||
cur = start;
|
||||
}
|
||||
PathCmd::LineTo(p) => {
|
||||
let p = m.apply(p);
|
||||
out.push(line(cur, p));
|
||||
cur = p;
|
||||
}
|
||||
PathCmd::QuadTo(q, p) => {
|
||||
let (q, p) = (m.apply(q), m.apply(p));
|
||||
out.push([cur, cur.lerp(q, 2.0 / 3.0), p.lerp(q, 2.0 / 3.0), p]);
|
||||
cur = p;
|
||||
}
|
||||
PathCmd::CubicTo(a, b, p) => {
|
||||
let (a, b, p) = (m.apply(a), m.apply(b), m.apply(p));
|
||||
out.push([cur, a, b, p]);
|
||||
cur = p;
|
||||
}
|
||||
PathCmd::Close => {
|
||||
if cur != start {
|
||||
out.push(line(cur, start));
|
||||
}
|
||||
cur = start;
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A cubic's point and derivative at `t`, in f64.
|
||||
fn point_and_tangent(c: &[Vec2; 4], t: f64) -> ((f64, f64), (f64, f64)) {
|
||||
let p = |v: Vec2| (f64::from(v.x), f64::from(v.y));
|
||||
let [p0, p1, p2, p3] = c.map(p);
|
||||
let u = 1.0 - t;
|
||||
let (b0, b1, b2, b3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
|
||||
let at = (b0 * p0.0 + b1 * p1.0 + b2 * p2.0 + b3 * p3.0, b0 * p0.1 + b1 * p1.1 + b2 * p2.1 + b3 * p3.1);
|
||||
let (d0, d1, d2) = (3.0 * u * u, 6.0 * u * t, 3.0 * t * t);
|
||||
let d = (d0 * (p1.0 - p0.0) + d1 * (p2.0 - p1.0) + d2 * (p3.0 - p2.0), d0 * (p1.1 - p0.1) + d1 * (p2.1 - p1.1) + d2 * (p3.1 - p2.1));
|
||||
(at, d)
|
||||
}
|
||||
|
||||
/// Five-point Gauss–Legendre nodes and weights on 0..1.
|
||||
const GAUSS: [(f64, f64); 5] = [
|
||||
(0.046_910_077_030_668, 0.118_463_442_528_094_5),
|
||||
(0.230_765_344_947_158_45, 0.239_314_335_249_683_2),
|
||||
(0.5, 0.284_444_444_444_444_4),
|
||||
(0.769_234_655_052_841_6, 0.239_314_335_249_683_2),
|
||||
(0.953_089_922_969_332, 0.118_463_442_528_094_5),
|
||||
];
|
||||
|
||||
fn signed_area(path: &Path, m: &Affine) -> f64 {
|
||||
// ½ ∮ (x dy − y dx): a degree-5 polynomial per cubic, which these nodes integrate exactly.
|
||||
cubics(path, m).iter().map(|c| GAUSS.iter().map(|&(t, w)| {
|
||||
let ((x, y), (dx, dy)) = point_and_tangent(c, t);
|
||||
w * (x * dy - y * dx)
|
||||
}).sum::<f64>()).sum::<f64>() * 0.5
|
||||
}
|
||||
|
||||
fn path_length(path: &Path, m: &Affine) -> f64 {
|
||||
cubics(path, m).iter().map(|c| GAUSS.iter().map(|&(t, w)| {
|
||||
let (_, (dx, dy)) = point_and_tangent(c, t);
|
||||
w * (dx * dx + dy * dy).sqrt()
|
||||
}).sum::<f64>()).sum()
|
||||
}
|
||||
|
||||
/// `draw.faucet`: Animate's Faucet deletes a whole fill or stroke with one click.
|
||||
fn faucet(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let els = s.visible_elements();
|
||||
// Topmost shape on the active layer under the point: in a fill, or on a stroke.
|
||||
let hit = els.iter().rev().find(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => {
|
||||
let hw = sh.stroke.as_ref().map_or(0.0, |st| st.reach() * e.transform.mean_scale());
|
||||
let near = sh.path.bounds().transformed(&e.transform).inflate(hw + slop).contains(at);
|
||||
near && ((sh.fill.is_some() && sh.path.contains(at, &e.transform, sh.fill_rule)) || (sh.stroke.is_some() && sh.path.distance_to_edge(at, &e.transform) <= hw + slop))
|
||||
}
|
||||
ElementKind::Symbol { .. } | ElementKind::Text(_) => s.element_bounds(e.id).contains(at),
|
||||
ElementKind::Camera => false,
|
||||
});
|
||||
let Some(hit) = hit else {
|
||||
return Err(EngineError::State("click a fill or a line on this layer to delete it".into()));
|
||||
};
|
||||
if mergeable(hit).is_none() {
|
||||
return Err(EngineError::State("the faucet deletes raw fills and lines; drawing objects, symbols and text are kept (select one and press Delete)".into()));
|
||||
}
|
||||
let (id, line) = (hit.id, matches!(&hit.kind, ElementKind::Shape(sh) if sh.fill.is_none()));
|
||||
let kf = s.editable_keyframe()?;
|
||||
kf.elements.retain(|e| e.id != id);
|
||||
s.selection.retain(|x| *x != id);
|
||||
Ok(json!({"deleted": id.0, "kind": if line { "line" } else { "fill" }}))
|
||||
}
|
||||
|
||||
/// The layers `draw.erase_all` clears: visible, unlocked layers that hold artwork (not folders,
|
||||
/// not the camera), with the number of elements at the playhead on each.
|
||||
pub(crate) fn erasable_layers(s: &Session) -> Vec<(anicraft_doc::LayerId, usize)> {
|
||||
let tl = s.doc.timeline(s.scene);
|
||||
tl.layers
|
||||
.iter()
|
||||
.filter(|l| l.visible && !l.locked && !tl.locked_by_folder(l.id) && !matches!(l.kind, LayerKind::Folder | LayerKind::Camera))
|
||||
.filter_map(|l| l.keyframe_at(s.frame).map(|k| (l.id, k.elements.len())))
|
||||
.filter(|(_, n)| *n > 0)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `draw.erase_all`: double-clicking the Eraser clears the stage at this frame: every element on
|
||||
/// the visible, unlocked layers' keyframes at the playhead (raw shapes, objects, symbols, text).
|
||||
fn erase_all(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let layers = erasable_layers(s);
|
||||
let (scene, frame) = (s.scene, s.frame);
|
||||
let mut erased = 0;
|
||||
for (id, _) in &layers {
|
||||
let Some(layer) = s.doc.timeline_mut(scene).layer_mut(*id) else { continue };
|
||||
let Some(i) = layer.keyframe_index_at(frame) else { continue };
|
||||
let Some(kf) = layer.keyframe_mut(i) else { continue };
|
||||
erased += kf.elements.len();
|
||||
kf.elements.clear();
|
||||
// Nothing is left to tween.
|
||||
kf.tween = None;
|
||||
kf.motion = None;
|
||||
}
|
||||
s.selection.clear();
|
||||
Ok(json!({"erased": erased, "layers": layers.len()}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn measure_els(els: &[std::sync::Arc<Element>]) -> (f64, f64) {
|
||||
measure(els.iter().map(|e| e.as_ref()))
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Paint Bucket and Ink Bottle.
|
||||
//! Paint Bucket, Ink Bottle and Eyedropper.
|
||||
//!
|
||||
//! AniCraft shapes are independent objects (like object drawing), so a fill for an area
|
||||
//! enclosed by several shapes has to be found, not looked up:
|
||||
@@ -32,6 +32,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
c("paint.bucket", "Paint Bucket", "", None, "{x, y, color?, gap? (stage units: how wide an opening still counts as closed)}", true, bucket as crate::RunFn),
|
||||
c("paint.ink", "Ink Bottle", "", None, "{x, y, color?, width?, profile?}", true, ink),
|
||||
c("paint.pick", "Eyedropper", "", None, "{x, y, other?: bool (into the other swatch only: a fill's colour into the stroke, a line's into the fill), slop?} picks the style under the point on any visible layer into the tool settings: a fill's paint (solid, gradient or bitmap, kept where it is on the stage) into the fill swatch, a line's colour, width and profile into the stroke settings", false, pick_style),
|
||||
c("paint.apply_style", "Apply Style", "", None, "{fill?: bool, stroke?: bool} (default both) gives the selected shapes the fill swatch's paint (shapes with a fill) and the stroke settings (shapes with a line, and drawing objects without one)", true, apply_style),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -68,7 +70,8 @@ fn element_shape_mut(s: &mut Session, id: ElementId) -> Result<&mut Shape> {
|
||||
|
||||
fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let color = opt_color(p, "color")?.unwrap_or(s.style.fill);
|
||||
// The fill swatch (a picked gradient or bitmap stays where it is on the stage).
|
||||
let paint = opt_color(p, "color")?.map_or_else(|| s.style.fill_paint(), Paint::Solid);
|
||||
let gap = opt_f32(p, "gap")?.unwrap_or(0.0);
|
||||
if !(0.0..=1000.0).contains(&gap) {
|
||||
return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into()));
|
||||
@@ -76,7 +79,8 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let items = layer_items(s);
|
||||
// 1. On a fill: recolour it.
|
||||
if let Some((id, true)) = pick(&items, at, 0.0) {
|
||||
element_shape_mut(s, id)?.fill = Some(Paint::Solid(color));
|
||||
let to_local = items.iter().find(|i| i.element == id).and_then(|i| i.transform.inverse()).unwrap_or(Affine::IDENTITY);
|
||||
element_shape_mut(s, id)?.fill = Some(paint.transformed(&to_local));
|
||||
return Ok(json!({"recolored": id.0}));
|
||||
}
|
||||
// 2. Find the enclosed area.
|
||||
@@ -91,7 +95,7 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color: ColorEffect::default(),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(Paint::Solid(color)), stroke: None, fill_rule: FillRule::EvenOdd, merge: false }),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(local), fill: Some(paint.transformed(&Affine::translate(-c.x, -c.y))), stroke: None, fill_rule: FillRule::EvenOdd, merge: false }),
|
||||
};
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() >= 100_000 {
|
||||
@@ -283,8 +287,128 @@ fn ink(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (id, _) = pick(&items, at, slop).ok_or_else(|| EngineError::State("click a shape to give it this stroke".into()))?;
|
||||
let profile = match opt_profile(p, "profile")? {
|
||||
Some(pr) => pr,
|
||||
None => s.style.stroke_profile.profile(),
|
||||
None => s.style.profile(),
|
||||
};
|
||||
element_shape_mut(s, id)?.stroke = Some(Stroke::new(color, width).with_profile(profile));
|
||||
Ok(json!({"element": id.0}))
|
||||
}
|
||||
|
||||
/// The kind of a paint, as commands report it.
|
||||
fn paint_kind(p: &Paint) -> &'static str {
|
||||
match p {
|
||||
Paint::Solid(_) => "solid",
|
||||
Paint::Linear { .. } => "linear",
|
||||
Paint::Radial { .. } => "radial",
|
||||
Paint::Bitmap { .. } => "bitmap",
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Eyedropper found: a fill's paint (stage space), or a line's stroke and the scale it
|
||||
/// is drawn at.
|
||||
enum Picked {
|
||||
Fill(Paint),
|
||||
Line(Stroke, f32),
|
||||
}
|
||||
|
||||
/// `paint.pick`: the Eyedropper. The topmost thing drawn under the point on any visible layer
|
||||
/// (locked ones too: picking reads, it doesn't change them): on a line, its stroke; in a fill,
|
||||
/// its paint.
|
||||
fn pick_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let other = opt_bool(p, "other")?.unwrap_or(false);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let dl = s.display_list();
|
||||
let hit = dl.items.iter().rev().find_map(|it| {
|
||||
// Mask artwork isn't drawn, and masked-away parts can't be picked.
|
||||
if it.masks.is_some() || it.clip.is_some_and(|c| !dl.clip_contains(c, at)) {
|
||||
return None;
|
||||
}
|
||||
let hw = it.stroke.as_ref().map_or(0.0, |st| st.reach() * it.transform.mean_scale());
|
||||
if !it.path.bounds().transformed(&it.transform).inflate(hw + slop).contains(at) {
|
||||
return None;
|
||||
}
|
||||
if let Some(st) = &it.stroke
|
||||
&& it.path.distance_to_edge(at, &it.transform) <= hw + slop
|
||||
{
|
||||
return Some(Picked::Line(st.clone(), it.transform.mean_scale()));
|
||||
}
|
||||
match &it.fill {
|
||||
Some(f) if it.path.contains(at, &it.transform, it.fill_rule) => Some(Picked::Fill(f.transformed(&it.transform))),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
let st = &mut s.style;
|
||||
match hit {
|
||||
Some(Picked::Fill(paint)) => {
|
||||
let color = paint.primary_color();
|
||||
if other {
|
||||
st.stroke = color;
|
||||
st.use_stroke = true;
|
||||
return Ok(json!({"picked": "fill", "into": "stroke", "paint": paint_kind(&paint), "color": color.to_hex()}));
|
||||
}
|
||||
st.fill = color;
|
||||
st.fill_paint = (!matches!(paint, Paint::Solid(_))).then(|| paint.clone());
|
||||
st.use_fill = true;
|
||||
Ok(json!({"picked": "fill", "into": "fill", "paint": paint_kind(&paint), "color": color.to_hex()}))
|
||||
}
|
||||
Some(Picked::Line(stroke, scale)) => {
|
||||
if other {
|
||||
st.set_fill_color(stroke.color);
|
||||
st.use_fill = true;
|
||||
return Ok(json!({"picked": "line", "into": "fill", "paint": "solid", "color": stroke.color.to_hex()}));
|
||||
}
|
||||
st.stroke = stroke.color;
|
||||
st.stroke_width = (stroke.width * scale).clamp(0.1, 1000.0);
|
||||
st.use_stroke = true;
|
||||
let preset = anicraft_doc::ProfilePreset::ALL.into_iter().find(|pr| pr.profile() == stroke.profile);
|
||||
let profile = match preset {
|
||||
Some(pr) => {
|
||||
st.set_profile(pr);
|
||||
pr.key()
|
||||
}
|
||||
None => {
|
||||
st.custom_profile = stroke.profile.clone();
|
||||
"custom"
|
||||
}
|
||||
};
|
||||
Ok(json!({"picked": "line", "into": "stroke", "color": stroke.color.to_hex(), "width": st.stroke_width, "profile": profile}))
|
||||
}
|
||||
None => Err(EngineError::State("click a fill or a line to pick its colour".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `paint.apply_style`: what the Eyedropper does with a selection (Animate applies the picked
|
||||
/// style to it).
|
||||
fn apply_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let fill = opt_bool(p, "fill")?.unwrap_or(true);
|
||||
let stroke = opt_bool(p, "stroke")?.unwrap_or(true);
|
||||
if !fill && !stroke {
|
||||
return Err(EngineError::Param("apply the fill, the stroke or both".into()));
|
||||
}
|
||||
let style = s.style.clone();
|
||||
let paint = style.fill_paint();
|
||||
let line = Stroke::new(style.stroke, style.stroke_width).with_profile(style.profile());
|
||||
let mut changed = 0;
|
||||
for e in s.selected_elements_mut()? {
|
||||
let to_local = e.transform.inverse();
|
||||
let ElementKind::Shape(sh) = &mut e.kind else { continue };
|
||||
let mut hit = false;
|
||||
if fill
|
||||
&& sh.fill.is_some()
|
||||
&& let Some(m) = to_local
|
||||
{
|
||||
sh.fill = Some(paint.transformed(&m));
|
||||
hit = true;
|
||||
}
|
||||
// Raw fills stay fill-only: the lines round them are shapes of their own (ADR 0031).
|
||||
if stroke && (sh.stroke.is_some() || !sh.merge) {
|
||||
sh.stroke = Some(line.clone());
|
||||
hit = true;
|
||||
}
|
||||
changed += usize::from(hit);
|
||||
}
|
||||
if changed == 0 {
|
||||
return Err(EngineError::State("none of the selected items is a shape that takes this style".into()));
|
||||
}
|
||||
Ok(json!({"changed": changed}))
|
||||
}
|
||||
@@ -145,6 +145,17 @@ pub fn confirmation(s: &Session, id: &str, p: &Value) -> Option<Confirmation> {
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"draw.erase_all" => {
|
||||
// Double-clicking the Eraser: everything on the stage at this frame (ADR 0034).
|
||||
let layers = crate::cmds_erase::erasable_layers(s);
|
||||
let elements: usize = layers.iter().map(|(_, n)| n).sum();
|
||||
(elements > 0).then(|| Confirmation {
|
||||
title: "Erase everything?".into(),
|
||||
message: format!("Everything on the stage at frame {} goes: {} on {}. Locked and hidden layers are kept. You can undo this.", s.frame + 1, plural(elements, "element"), plural(layers.len(), "layer")),
|
||||
action: "Erase Everything".into(),
|
||||
irreversible: false,
|
||||
})
|
||||
}
|
||||
"camera.remove" => camera_removal(s, s.doc.timeline(s.scene).camera_layer()?),
|
||||
"layer.delete" => {
|
||||
let l = target_layer(s, p)?;
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! The Eraser's commands (ADR 0034).
|
||||
|
||||
use crate::Session;
|
||||
use crate::cmds_erase::measure_els;
|
||||
use anicraft_doc::{ElementKind, Paint, Rgba, Shape};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn blank(object: bool) -> Session {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": object}));
|
||||
s
|
||||
}
|
||||
|
||||
/// The keyframe's shapes, bottom to top, with their transforms.
|
||||
fn shapes(s: &Session) -> Vec<(Shape, Affine)> {
|
||||
s.visible_elements()
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => Some((sh.clone(), e.transform)),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fill_of(sh: &Shape) -> Option<Rgba> {
|
||||
match sh.fill {
|
||||
Some(Paint::Solid(c)) => Some(c),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill colour covering stage point `p` (the topmost filled shape containing it).
|
||||
fn top_at(s: &Session, p: Vec2) -> Option<Rgba> {
|
||||
shapes(s).iter().rev().filter(|(sh, _)| sh.fill.is_some()).find(|(sh, m)| sh.path.contains(p, m, sh.fill_rule)).and_then(|(sh, _)| fill_of(sh))
|
||||
}
|
||||
|
||||
/// Total raw fill area and line length on the active layer.
|
||||
fn measure(s: &Session) -> (f64, f64) {
|
||||
measure_els(&s.visible_elements())
|
||||
}
|
||||
|
||||
fn stroke(x0: f32, y0: f32, x1: f32, y1: f32) -> Vec<[f32; 2]> {
|
||||
(0..=30).map(|i| i as f32 / 30.0).map(|t| [x0 + (x1 - x0) * t, y0 + (y1 - y0) * t]).collect()
|
||||
}
|
||||
|
||||
const BLUE: &str = "#0000ff";
|
||||
const RED: &str = "#ff0000";
|
||||
const BLACK: &str = "#000000";
|
||||
|
||||
fn near(a: f64, b: f64, tol: f64) -> bool {
|
||||
(a - b).abs() <= tol
|
||||
}
|
||||
|
||||
/// A raw 200 × 100 blue rectangle at (100, 100), outlined in black 4 wide when `outlined`.
|
||||
fn rect(outlined: bool) -> Session {
|
||||
let mut s = blank(false);
|
||||
let stroke = if outlined { json!(BLACK) } else { Value::Null };
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": BLUE, "stroke": stroke, "stroke_width": 4}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erasing_a_band_out_of_a_rectangle_leaves_the_analytic_area() {
|
||||
let mut s = rect(false);
|
||||
assert!(near(measure(&s).0, 20_000.0, 0.01));
|
||||
let steps = s.history_len();
|
||||
// A round tip 20 wide straight down through the middle: its ends are outside the shape.
|
||||
let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 240.0), "size": 20}));
|
||||
assert_eq!(r["erased"], true);
|
||||
let (area, _) = measure(&s);
|
||||
assert!(near(area, 18_000.0, 40.0), "area {area}, want 20000 − 20 × 100");
|
||||
let blues = shapes(&s).iter().filter(|(sh, _)| fill_of(sh) == Some(Rgba::hex(0x0000ff))).count();
|
||||
assert_eq!(blues, 2, "the band cuts the rectangle in two");
|
||||
assert!(shapes(&s).iter().all(|(sh, _)| sh.merge), "what is left is raw");
|
||||
assert_eq!(top_at(&s, Vec2::new(200.0, 150.0)), None);
|
||||
assert_eq!(top_at(&s, Vec2::new(150.0, 150.0)), Some(Rgba::hex(0x0000ff)));
|
||||
// The CPU renderer agrees (the oracle): the stage shows through the band.
|
||||
let img = anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap();
|
||||
let bg = s.doc.stage.background;
|
||||
let (gap, kept) = (img.pixel(200, 150).unwrap(), img.pixel(150, 150).unwrap());
|
||||
assert!((gap[0] - bg.r).abs() < 0.02 && (gap[2] - bg.b).abs() < 0.02, "{gap:?}");
|
||||
assert!(kept[2] > 0.9 && kept[0] < 0.1, "{kept:?}");
|
||||
// One stroke, one undo step.
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(near(measure(&s).0, 20_000.0, 0.01));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erase_modes_take_what_animate_takes() {
|
||||
let band = stroke(50.0, 150.0, 350.0, 150.0);
|
||||
// Fill 200 × 100 = 20000, lines 2 × (200 + 100) = 600; the band is 20 tall across it all.
|
||||
let after = |mode: &str| {
|
||||
let mut s = rect(true);
|
||||
let r = run(&mut s, "draw.erase", json!({"points": band, "size": 20, "mode": mode}));
|
||||
assert_eq!(r["erased"], true, "{mode}");
|
||||
measure(&s)
|
||||
};
|
||||
let (area, length) = after("normal");
|
||||
assert!(near(area, 16_000.0, 40.0) && near(length, 560.0, 1.0), "normal: {area} {length}");
|
||||
let (area, length) = after("fills");
|
||||
assert!(near(area, 16_000.0, 40.0) && near(length, 600.0, 0.01), "fills keeps lines: {area} {length}");
|
||||
let (area, length) = after("lines");
|
||||
assert!(near(area, 20_000.0, 0.01) && near(length, 560.0, 1.0), "lines keeps fills: {area} {length}");
|
||||
}
|
||||
|
||||
/// Blue at x 100..200 and red at 200..300 (raw, side by side), no outlines.
|
||||
fn two_fills() -> Session {
|
||||
let mut s = blank(false);
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": BLUE, "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 200, "y": 100, "w": 100, "h": 100, "fill": RED, "stroke": null}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
s
|
||||
}
|
||||
|
||||
fn fill_area(s: &Session, c: u32) -> f64 {
|
||||
let els: Vec<_> = s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if fill_of(sh) == Some(Rgba::hex(c)))).collect();
|
||||
measure_els(&els).0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erase_selected_fills_and_erase_inside_keep_the_other_fills() {
|
||||
let band = stroke(50.0, 150.0, 350.0, 150.0);
|
||||
// Selected fills: only the selected (blue) one loses the band, and what's left stays selected.
|
||||
let mut s = two_fills();
|
||||
let r = run(&mut s, "draw.erase", json!({"points": band, "size": 20, "mode": "selected_fills"}));
|
||||
assert_eq!(r["erased"], false, "nothing selected, nothing erased");
|
||||
let blue = s.visible_elements().iter().find(|e| matches!(&e.kind, ElementKind::Shape(sh) if fill_of(sh) == Some(Rgba::hex(0x0000ff)))).map(|e| e.id.0).unwrap();
|
||||
run(&mut s, "element.select", json!({"ids": [blue]}));
|
||||
run(&mut s, "draw.erase", json!({"points": band, "size": 20, "mode": "selected_fills"}));
|
||||
assert!(near(fill_area(&s, 0x0000ff), 8_000.0, 30.0) && near(fill_area(&s, 0xff0000), 10_000.0, 0.01), "{} {}", fill_area(&s, 0x0000ff), fill_area(&s, 0xff0000));
|
||||
assert_eq!(s.selection.len(), 2, "both blue pieces stay selected");
|
||||
// Inside: only the fill the stroke starts on (a 50 × 20 band and the round start's half disc).
|
||||
let mut s = two_fills();
|
||||
run(&mut s, "draw.erase", json!({"points": stroke(150.0, 150.0, 350.0, 150.0), "size": 20, "mode": "inside"}));
|
||||
let want = 10_000.0 - 1_000.0 - std::f64::consts::PI * 50.0;
|
||||
assert!(near(fill_area(&s, 0x0000ff), want, 20.0) && near(fill_area(&s, 0xff0000), 10_000.0, 0.01), "{} {}", fill_area(&s, 0x0000ff), fill_area(&s, 0xff0000));
|
||||
// Starting off the artwork erases nothing, and leaves no undo step.
|
||||
let steps = s.history_len();
|
||||
let r = run(&mut s, "draw.erase", json!({"points": stroke(50.0, 150.0, 350.0, 150.0), "size": 20, "mode": "inside"}));
|
||||
assert_eq!(r["erased"], false);
|
||||
assert_eq!(s.history_len(), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drawing_objects_and_symbols_are_not_erased() {
|
||||
let mut s = blank(true);
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 200, "h": 100, "fill": BLUE}));
|
||||
run(&mut s, "draw.ellipse", json!({"x": 100, "y": 220, "w": 200, "h": 60, "fill": RED}));
|
||||
run(&mut s, "modify.convert_to_symbol", json!({"name": "Disc"}));
|
||||
let (doc, steps) = (s.doc.clone(), s.history_len());
|
||||
let r = run(&mut s, "draw.erase", json!({"points": stroke(200.0, 60.0, 200.0, 300.0), "size": 30}));
|
||||
assert_eq!(r["erased"], false);
|
||||
assert_eq!(s.doc, doc, "objects and symbols are untouched");
|
||||
assert_eq!(s.history_len(), steps, "no undo step");
|
||||
// Raw shapes beside them are erased, the object stays whole.
|
||||
run(&mut s, "draw.rect", json!({"x": 320, "y": 100, "w": 100, "h": 100, "fill": BLUE, "stroke": null, "object": false}));
|
||||
run(&mut s, "draw.erase", json!({"points": stroke(150.0, 150.0, 450.0, 150.0), "size": 20}));
|
||||
let objects = shapes(&s).into_iter().filter(|(sh, _)| !sh.merge).collect::<Vec<_>>();
|
||||
assert_eq!(objects.len(), 1, "the rectangle object is whole");
|
||||
assert!(near(measure_els(&s.visible_elements()).0, 8_000.0, 30.0), "only the raw square lost the band");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_faucet_deletes_a_whole_fill_or_line() {
|
||||
let mut s = rect(true);
|
||||
let lines = shapes(&s).iter().filter(|(sh, _)| sh.stroke.is_some()).count();
|
||||
let r = run(&mut s, "draw.faucet", json!({"x": 150, "y": 150}));
|
||||
assert_eq!(r["kind"], "fill");
|
||||
assert!(shapes(&s).iter().all(|(sh, _)| sh.fill.is_none()), "the fill is gone, its outline stays");
|
||||
let r = run(&mut s, "draw.faucet", json!({"x": 100, "y": 150}));
|
||||
assert_eq!(r["kind"], "line");
|
||||
assert_eq!(shapes(&s).len(), lines - 1, "one side of the outline is gone");
|
||||
assert!(s.execute("draw.faucet", &json!({"x": 600, "y": 600})).is_err(), "nothing there");
|
||||
// Drawing objects are kept.
|
||||
run(&mut s, "draw.rect", json!({"x": 400, "y": 100, "w": 50, "h": 50, "fill": RED, "object": true}));
|
||||
assert!(s.execute("draw.faucet", &json!({"x": 425, "y": 125})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erase_everything_asks_first_and_keeps_locked_layers() {
|
||||
let mut s = rect(true);
|
||||
run(&mut s, "layer.new", json!({"name": "Kept"}));
|
||||
run(&mut s, "draw.ellipse", json!({"x": 0, "y": 0, "w": 50, "h": 50, "fill": RED, "object": true}));
|
||||
run(&mut s, "layer.toggle_lock", json!({}));
|
||||
let c = s.confirmation("draw.erase_all", &json!({})).expect("it asks");
|
||||
assert!(!c.irreversible, "undoable");
|
||||
assert!(c.message.contains("5 elements on 1 layer"), "{}", c.message);
|
||||
let r = run(&mut s, "draw.erase_all", json!({}));
|
||||
assert_eq!(r["erased"], 5);
|
||||
let tl = s.doc.timeline(0);
|
||||
let counts: Vec<usize> = tl.layers.iter().map(|l| l.keyframe_at(0).map_or(0, |k| k.elements.len())).collect();
|
||||
assert!(counts.contains(&0) && counts.contains(&1), "{counts:?}");
|
||||
assert!(s.confirmation("draw.erase_all", &json!({})).is_none(), "nothing left to ask about");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.timeline(0).layers.iter().map(|l| l.keyframe_at(0).map_or(0, |k| k.elements.len())).sum::<usize>(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn erased_drawings_round_trip_through_the_file_format() {
|
||||
let mut s = rect(true);
|
||||
run(&mut s, "draw.erase", json!({"points": [[150, 150, 0.3], [200, 160, 1.0], [260, 140, 0.6]], "size": 24}));
|
||||
let json = crate::format::to_json(&s.doc).unwrap();
|
||||
assert_eq!(crate::format::from_json(&json).unwrap(), s.doc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_are_errors_and_plug_ins_may_erase() {
|
||||
let mut s = rect(true);
|
||||
for p in [
|
||||
json!({}),
|
||||
json!({"points": []}),
|
||||
json!({"points": [[0, 0]], "size": 0}),
|
||||
json!({"points": [[0, 0]], "mode": "behind"}),
|
||||
json!({"points": [[0, 0]], "shape": "star"}),
|
||||
json!({"points": [[0, 0], [1e7, 0]]}),
|
||||
] {
|
||||
assert!(s.execute("draw.erase", &p).is_err(), "{p}");
|
||||
}
|
||||
assert!(s.execute("draw.faucet", &json!({"x": "a"})).is_err());
|
||||
for id in ["draw.erase", "draw.faucet", "draw.erase_all", "paint.pick", "paint.apply_style"] {
|
||||
assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The Eyedropper's commands (ADR 0034).
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{ElementId, ElementKind, GradientStop, Paint, ProfilePreset, Rgba, Shape};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn shape(s: &Session, id: u64) -> (Shape, Affine) {
|
||||
s.visible_elements()
|
||||
.iter()
|
||||
.find(|e| e.id == ElementId(id))
|
||||
.and_then(|e| match &e.kind {
|
||||
ElementKind::Shape(sh) => Some((sh.clone(), e.transform)),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a shape")
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f32, fill: &str) -> u64 {
|
||||
run(s, "draw.rect", json!({"x": x, "y": 100, "w": 100, "h": 100, "fill": fill, "stroke": null}))["element"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
/// A linear gradient across the shape's own width (local space: the shape is centred on 0).
|
||||
fn gradient() -> Paint {
|
||||
Paint::Linear { start: Vec2::new(-50.0, 0.0), end: Vec2::new(50.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff8800) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0044ff) }] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_a_solid_fill_sets_the_fill_colour_and_records_no_step() {
|
||||
let mut s = Session::default();
|
||||
rect(&mut s, 100.0, "#ff0000");
|
||||
let steps = s.history_len();
|
||||
let r = run(&mut s, "paint.pick", json!({"x": 150, "y": 150}));
|
||||
assert_eq!((r["picked"].as_str(), r["into"].as_str(), r["paint"].as_str()), (Some("fill"), Some("fill"), Some("solid")));
|
||||
assert_eq!(s.style.fill, Rgba::hex(0xff0000));
|
||||
assert!(s.style.fill_paint.is_none());
|
||||
assert_eq!(s.history_len(), steps, "picking changes the tool, not the document");
|
||||
assert!(s.execute("paint.pick", &json!({"x": 900, "y": 900})).is_err(), "nothing there");
|
||||
// Shift-click: into the other swatch only.
|
||||
s.style.set_fill_color(Rgba::hex(0x00ff00));
|
||||
let r = run(&mut s, "paint.pick", json!({"x": 150, "y": 150, "other": true}));
|
||||
assert_eq!(r["into"], "stroke");
|
||||
assert_eq!((s.style.stroke, s.style.fill), (Rgba::hex(0xff0000), Rgba::hex(0x00ff00)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picked_gradient_stays_where_it_is_on_the_stage() {
|
||||
let mut s = Session::default();
|
||||
let a = rect(&mut s, 100.0, "#ff0000");
|
||||
let b = rect(&mut s, 300.0, "#00ff00");
|
||||
for e in s.editable_keyframe().unwrap().elements_mut_where(|id| id == ElementId(a)) {
|
||||
if let ElementKind::Shape(sh) = &mut e.kind {
|
||||
sh.fill = Some(gradient());
|
||||
}
|
||||
}
|
||||
let r = run(&mut s, "paint.pick", json!({"x": 150, "y": 150}));
|
||||
assert_eq!(r["paint"], "linear");
|
||||
assert_eq!(s.style.fill, Rgba::hex(0xff8800), "the swatch shows its first colour");
|
||||
// In stage space: the shape's centre is (150, 150).
|
||||
match &s.style.fill_paint {
|
||||
Some(Paint::Linear { start, end, .. }) => assert!(start.distance(Vec2::new(100.0, 150.0)) < 1e-3 && end.distance(Vec2::new(200.0, 150.0)) < 1e-3, "{start:?} {end:?}"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// The Paint Bucket pours it into the other shape, mapped into that shape's space, so the
|
||||
// gradient carries on across the stage (Animate's Lock Fill).
|
||||
run(&mut s, "paint.bucket", json!({"x": 350, "y": 150}));
|
||||
let (sh, m) = shape(&s, b);
|
||||
match sh.fill {
|
||||
Some(Paint::Linear { start, .. }) => assert!(m.apply(start).distance(Vec2::new(100.0, 150.0)) < 1e-3, "{:?}", m.apply(start)),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
// Picking a colour in the swatch drops the gradient.
|
||||
s.style.set_fill_color(Rgba::hex(0x123456));
|
||||
assert!(s.style.fill_paint.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_a_line_takes_its_colour_width_and_profile() {
|
||||
let mut s = Session::default();
|
||||
run(&mut s, "draw.line", json!({"x0": 100, "y0": 100, "x1": 300, "y1": 100, "stroke": "#336699", "stroke_width": 6, "profile": "taper_both"}));
|
||||
let r = run(&mut s, "paint.pick", json!({"x": 200, "y": 101}));
|
||||
assert_eq!((r["picked"].as_str(), r["profile"].as_str()), (Some("line"), Some("taper_both")));
|
||||
assert_eq!(s.style.stroke, Rgba::hex(0x336699));
|
||||
assert!((s.style.stroke_width - 6.0).abs() < 1e-4);
|
||||
assert_eq!(s.style.stroke_profile, ProfilePreset::TaperBoth);
|
||||
// A custom profile, on a line drawn twice the size: the width is as it shows on the stage.
|
||||
run(&mut s, "draw.line", json!({"x0": 100, "y0": 300, "x1": 300, "y1": 300, "stroke": "#000000", "stroke_width": 4, "profile": [[0, 1, 1], [0.3, 2, 2], [1, 0.5, 0.5]]}));
|
||||
run(&mut s, "element.set_transform", json!({"sx": 2, "sy": 2}));
|
||||
let r = run(&mut s, "paint.pick", json!({"x": 200, "y": 300}));
|
||||
assert_eq!(r["profile"], "custom");
|
||||
assert!(s.style.custom_profile.is_some() && (s.style.stroke_width - 8.0).abs() < 1e-3, "{}", s.style.stroke_width);
|
||||
// New lines get it.
|
||||
let id = run(&mut s, "draw.line", json!({"x0": 0, "y0": 0, "x1": 50, "y1": 0}))["element"].as_u64().unwrap();
|
||||
assert_eq!(shape(&s, id).0.stroke.and_then(|st| st.profile), s.style.custom_profile);
|
||||
// Shift-click on a line: its colour into the fill.
|
||||
run(&mut s, "paint.pick", json!({"x": 200, "y": 101, "other": true}));
|
||||
assert_eq!(s.style.fill, Rgba::hex(0x336699));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_the_picked_style_to_the_selection_is_one_step() {
|
||||
let mut s = Session::default();
|
||||
let a = rect(&mut s, 100.0, "#ff0000");
|
||||
let b = rect(&mut s, 300.0, "#00ff00");
|
||||
run(&mut s, "element.select", json!({"ids": [b]}));
|
||||
run(&mut s, "paint.pick", json!({"x": 150, "y": 150}));
|
||||
let steps = s.history_len();
|
||||
let r = run(&mut s, "paint.apply_style", json!({"fill": true, "stroke": false}));
|
||||
assert_eq!(r["changed"], 1);
|
||||
assert_eq!(s.history_len(), steps + 1);
|
||||
assert_eq!(shape(&s, b).0.fill, Some(Paint::Solid(Rgba::hex(0xff0000))));
|
||||
assert_eq!(shape(&s, a).0.fill, Some(Paint::Solid(Rgba::hex(0xff0000))), "the source is unchanged");
|
||||
// The stroke settings go onto a drawing object that had none.
|
||||
run(&mut s, "paint.apply_style", json!({"fill": false}));
|
||||
assert!(shape(&s, b).0.stroke.is_some());
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
assert!(s.execute("paint.apply_style", &json!({})).is_err(), "nothing selected");
|
||||
assert!(s.execute("paint.apply_style", &json!({"fill": false, "stroke": false})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_reads_locked_layers_too() {
|
||||
let mut s = Session::default();
|
||||
rect(&mut s, 100.0, "#ff0000");
|
||||
run(&mut s, "layer.toggle_lock", json!({}));
|
||||
run(&mut s, "paint.pick", json!({"x": 150, "y": 150}));
|
||||
assert_eq!(s.style.fill, Rgba::hex(0xff0000));
|
||||
}
|
||||
@@ -9,6 +9,7 @@ mod cmds_actions;
|
||||
pub mod cmds_brush;
|
||||
mod cmds_camera;
|
||||
mod cmds_draw;
|
||||
pub mod cmds_erase;
|
||||
mod cmds_file;
|
||||
mod cmds_frames;
|
||||
mod cmds_modify;
|
||||
@@ -107,6 +108,7 @@ pub fn commands() -> Vec<CommandSpec> {
|
||||
v.extend(cmds_modify::specs());
|
||||
v.extend(cmds_path::specs());
|
||||
v.extend(cmds_brush::specs());
|
||||
v.extend(cmds_erase::specs());
|
||||
v.extend(cmds_paint::specs());
|
||||
v.extend(cmds_text::specs());
|
||||
v.extend(cmds_width::specs());
|
||||
@@ -134,15 +136,20 @@ pub use history::{Snapshot, StateId};
|
||||
pub const MAX_FRAME: u32 = 100_000;
|
||||
|
||||
/// Drawing defaults used by the drawing commands when params omit colours.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ToolStyle {
|
||||
pub fill: anicraft_doc::Rgba,
|
||||
/// The fill swatch holds a gradient or a bitmap (picked with the Eyedropper, ADR 0034), in
|
||||
/// stage space; `fill` is then its representative colour. `None`: the solid `fill`.
|
||||
pub fill_paint: Option<anicraft_doc::Paint>,
|
||||
pub stroke: anicraft_doc::Rgba,
|
||||
pub stroke_width: f32,
|
||||
pub use_fill: bool,
|
||||
pub use_stroke: bool,
|
||||
/// The width profile new strokes get (ADR 0018).
|
||||
pub stroke_profile: anicraft_doc::ProfilePreset,
|
||||
/// A picked width profile that is none of the presets (it wins over `stroke_profile`).
|
||||
pub custom_profile: Option<anicraft_doc::WidthProfile>,
|
||||
/// Object Drawing: new shapes are drawing objects. Off, they merge with the raw shapes they
|
||||
/// touch (ADR 0031). On by default, so a script's draw command makes one element; the editor
|
||||
/// starts with it off, as Animate does.
|
||||
@@ -151,7 +158,28 @@ pub struct ToolStyle {
|
||||
|
||||
impl Default for ToolStyle {
|
||||
fn default() -> Self {
|
||||
ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, object_drawing: true }
|
||||
ToolStyle { fill: anicraft_doc::Rgba::hex(0x3d8bfd), fill_paint: None, stroke: anicraft_doc::Rgba::hex(0x1b2a4a), stroke_width: 2.0, use_fill: true, use_stroke: true, stroke_profile: anicraft_doc::ProfilePreset::Uniform, custom_profile: None, object_drawing: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolStyle {
|
||||
/// The fill swatch's paint, in stage space.
|
||||
pub fn fill_paint(&self) -> anicraft_doc::Paint {
|
||||
self.fill_paint.clone().unwrap_or(anicraft_doc::Paint::Solid(self.fill))
|
||||
}
|
||||
/// Sets the fill swatch to a solid colour (dropping a picked gradient or bitmap).
|
||||
pub fn set_fill_color(&mut self, c: anicraft_doc::Rgba) {
|
||||
self.fill = c;
|
||||
self.fill_paint = None;
|
||||
}
|
||||
/// The width profile new strokes get.
|
||||
pub fn profile(&self) -> Option<anicraft_doc::WidthProfile> {
|
||||
self.custom_profile.clone().or_else(|| self.stroke_profile.profile())
|
||||
}
|
||||
/// Sets the profile to a preset (dropping a picked custom one).
|
||||
pub fn set_profile(&mut self, p: anicraft_doc::ProfilePreset) {
|
||||
self.stroke_profile = p;
|
||||
self.custom_profile = None;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,7 +321,7 @@ impl Session {
|
||||
|
||||
/// Replaces the document (new/open), clearing history.
|
||||
pub fn replace_document(&mut self, doc: Document, path: Option<PathBuf>) {
|
||||
let style = self.style;
|
||||
let style = std::mem::take(&mut self.style);
|
||||
let rev = self.revision;
|
||||
let budget = self.history.budget_bytes;
|
||||
let clipboard = std::mem::take(&mut self.clipboard);
|
||||
@@ -706,3 +734,7 @@ mod tests_camera;
|
||||
mod merge_tests;
|
||||
#[cfg(test)]
|
||||
mod brush_tests;
|
||||
#[cfg(test)]
|
||||
mod erase_tests;
|
||||
#[cfg(test)]
|
||||
mod eyedropper_tests;
|
||||
+68
-32
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
/// A raw shape the merge can take: a solid fill (or none) and a stroke of one width (or none).
|
||||
fn mergeable(e: &Element) -> Option<&Shape> {
|
||||
pub(crate) fn mergeable(e: &Element) -> Option<&Shape> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(s) if s.merge && matches!(s.fill, None | Some(Paint::Solid(_))) && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s),
|
||||
_ => None,
|
||||
@@ -32,7 +32,7 @@ pub(crate) fn can_merge(fill: Option<&Paint>, stroke: Option<&Stroke>) -> bool {
|
||||
matches!(fill, None | Some(Paint::Solid(_))) && stroke.is_none_or(|st| st.profile.is_none())
|
||||
}
|
||||
|
||||
fn reach(s: &Shape, m: &Affine) -> Rect {
|
||||
pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect {
|
||||
let pad = s.stroke.as_ref().map_or(0.0, Stroke::reach) * m.mean_scale();
|
||||
s.path.bounds().transformed(m).inflate(pad + 2.0 * SNAP)
|
||||
}
|
||||
@@ -71,28 +71,13 @@ pub(crate) fn merge_in_order(s: &mut Session, new: Vec<Element>, order: Order) -
|
||||
.collect();
|
||||
let old: Vec<&Element> = touching.iter().filter_map(|&i| existing.get(i).map(|e| e.as_ref())).collect();
|
||||
let is_line = |e: &&Element| mergeable(e).is_some_and(|sh| sh.fill.is_none());
|
||||
// Bottom to top, each with whether it is new.
|
||||
let all: Vec<(&Element, bool)> = match order {
|
||||
Order::Top => old.iter().map(|e| (*e, false)).chain(new.iter().map(|e| (e, true))).collect(),
|
||||
Order::Behind => new.iter().map(|e| (e, true)).chain(old.iter().map(|e| (*e, false))).collect(),
|
||||
Order::UnderLines => old.iter().filter(|e| !is_line(e)).map(|e| (*e, false)).chain(new.iter().map(|e| (e, true))).chain(old.iter().filter(|e| is_line(e)).map(|e| (*e, false))).collect(),
|
||||
// Bottom to top, the new shapes marked (their pieces are selected).
|
||||
let all: Vec<Part> = match order {
|
||||
Order::Top => old.iter().map(|e| Part::Shape(e, false)).chain(new.iter().map(|e| Part::Shape(e, true))).collect(),
|
||||
Order::Behind => new.iter().map(|e| Part::Shape(e, true)).chain(old.iter().map(|e| Part::Shape(e, false))).collect(),
|
||||
Order::UnderLines => old.iter().filter(|e| !is_line(e)).map(|e| Part::Shape(e, false)).chain(new.iter().map(|e| Part::Shape(e, true))).chain(old.iter().filter(|e| is_line(e)).map(|e| Part::Shape(e, false))).collect(),
|
||||
};
|
||||
// Style tables: equal entries are one style to the merge.
|
||||
let mut fills: Vec<(Paint, ColorEffect)> = Vec::new();
|
||||
let mut strokes: Vec<(Stroke, ColorEffect)> = Vec::new();
|
||||
let mut paths: Vec<Path> = Vec::with_capacity(all.len());
|
||||
let mut styles: Vec<(Option<u32>, Option<u32>, anicraft_geom::FillRule)> = Vec::with_capacity(all.len());
|
||||
let mut fresh: Vec<bool> = Vec::with_capacity(all.len());
|
||||
for (e, is_new) in &all {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
paths.push(sh.path.transformed(&e.transform));
|
||||
let fill = sh.fill.clone().map(|f| index_of(&mut fills, (f, e.color)));
|
||||
let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (Stroke { width: st.width * e.transform.mean_scale(), ..st }, e.color)));
|
||||
styles.push((fill, stroke, sh.fill_rule));
|
||||
fresh.push(*is_new);
|
||||
}
|
||||
let items: Vec<Item> = paths.iter().zip(&styles).map(|(path, &(fill, stroke, fill_rule))| Item { path, fill, fill_rule, stroke }).collect();
|
||||
let Some(merged) = planar::merge(&items) else {
|
||||
let Some((out, picked)) = remerge(s, &all) else {
|
||||
// Too much to merge at once: keep the new shapes whole, as objects.
|
||||
kept.extend(new.iter().map(|e| e.id));
|
||||
let objects = new
|
||||
@@ -107,11 +92,58 @@ pub(crate) fn merge_in_order(s: &mut Session, new: Vec<Element>, order: Order) -
|
||||
add_whole(s.editable_keyframe()?, objects, order);
|
||||
return Ok(kept);
|
||||
};
|
||||
replace(s, &touching, out, order == Order::Behind)?;
|
||||
kept.extend(picked);
|
||||
Ok(kept)
|
||||
}
|
||||
|
||||
/// One entry of a merge, bottom to top.
|
||||
pub(crate) enum Part<'a> {
|
||||
/// A raw shape, and whether it is marked (the pieces it ends up on top of are reported).
|
||||
Shape(&'a Element, bool),
|
||||
/// The eraser (ADR 0034): a fill whose regions come out empty. Above a shape it takes away
|
||||
/// what it covers, fills and the lines it covers on both sides; under a shape, nothing of it.
|
||||
Eraser(&'a Path),
|
||||
}
|
||||
|
||||
/// The fill style the eraser paints: regions of it are dropped.
|
||||
const ERASED: u32 = u32::MAX;
|
||||
|
||||
/// Merges `parts` into raw shapes (one element per fill region and per stroke run, fills first)
|
||||
/// and returns them with the ids of the pieces whose topmost source part was marked. `None` when
|
||||
/// there is too much to merge at once.
|
||||
pub(crate) fn remerge(s: &mut Session, parts: &[Part]) -> Option<(Vec<Arc<Element>>, Vec<ElementId>)> {
|
||||
// Style tables: equal entries are one style to the merge.
|
||||
let mut fills: Vec<(Paint, ColorEffect)> = Vec::new();
|
||||
let mut strokes: Vec<(Stroke, ColorEffect)> = Vec::new();
|
||||
let mut paths: Vec<Path> = Vec::with_capacity(parts.len());
|
||||
let mut styles: Vec<(Option<u32>, Option<u32>, anicraft_geom::FillRule)> = Vec::with_capacity(parts.len());
|
||||
let mut marked: Vec<bool> = Vec::with_capacity(parts.len());
|
||||
for part in parts {
|
||||
match part {
|
||||
Part::Shape(e, mark) => {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
paths.push(sh.path.transformed(&e.transform));
|
||||
let fill = sh.fill.clone().map(|f| index_of(&mut fills, (f, e.color)));
|
||||
let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (Stroke { width: st.width * e.transform.mean_scale(), ..st }, e.color)));
|
||||
styles.push((fill, stroke, sh.fill_rule));
|
||||
marked.push(*mark);
|
||||
}
|
||||
Part::Eraser(path) => {
|
||||
paths.push((*path).clone());
|
||||
styles.push((Some(ERASED), None, anicraft_geom::FillRule::NonZero));
|
||||
marked.push(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
let items: Vec<Item> = paths.iter().zip(&styles).map(|(path, &(fill, stroke, fill_rule))| Item { path, fill, fill_rule, stroke }).collect();
|
||||
let merged = planar::merge(&items)?;
|
||||
let mut out: Vec<Arc<Element>> = Vec::with_capacity(merged.fills.len() + merged.strokes.len());
|
||||
let mut picked = Vec::new();
|
||||
for (piece, is_fill) in merged.fills.iter().map(|p| (p, true)).chain(merged.strokes.iter().map(|p| (p, false))) {
|
||||
let (fill, stroke, color) = if is_fill {
|
||||
let Some((f, c)) = fills.get(piece.style as usize) else { continue };
|
||||
// Erased regions (and anything without a style) are left out.
|
||||
let Some((f, c)) = fills.get(piece.style as usize).filter(|_| piece.style != ERASED) else { continue };
|
||||
(Some(f.clone()), None, *c)
|
||||
} else {
|
||||
let Some((st, c)) = strokes.get(piece.style as usize) else { continue };
|
||||
@@ -120,7 +152,7 @@ pub(crate) fn merge_in_order(s: &mut Session, new: Vec<Element>, order: Order) -
|
||||
// Local origin at the centre of the piece, as the drawing tools place shapes.
|
||||
let c = piece.path.bounds().center();
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
if fresh.get(piece.item).copied().unwrap_or(false) {
|
||||
if marked.get(piece.item).copied().unwrap_or(false) {
|
||||
picked.push(id);
|
||||
}
|
||||
out.push(Arc::new(Element {
|
||||
@@ -131,22 +163,26 @@ pub(crate) fn merge_in_order(s: &mut Session, new: Vec<Element>, order: Order) -
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill, stroke, fill_rule: Default::default(), merge: true }),
|
||||
}));
|
||||
}
|
||||
Some((out, picked))
|
||||
}
|
||||
|
||||
/// Replaces the keyframe's elements at `taken` (ascending indices) with `out`, placed where the
|
||||
/// lowest of them was (raw shapes sit under objects); taking nothing, on top, or at the bottom
|
||||
/// when `behind`.
|
||||
pub(crate) fn replace(s: &mut Session, taken: &[usize], out: Vec<Arc<Element>>, behind: bool) -> Result<()> {
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() - touching.len() + out.len() > 100_000 {
|
||||
if kf.elements.len().saturating_sub(taken.len()) + out.len() > 100_000 {
|
||||
return Err(crate::EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
// The drawing goes where the lowest shape it took in was (raw shapes sit under objects);
|
||||
// touching nothing, on top, or at the bottom when painting behind.
|
||||
let at = touching.first().copied().unwrap_or(if order == Order::Behind { 0 } else { kf.elements.len() });
|
||||
for &i in touching.iter().rev() {
|
||||
let at = taken.first().copied().unwrap_or(if behind { 0 } else { kf.elements.len() });
|
||||
for &i in taken.iter().rev() {
|
||||
if i < kf.elements.len() {
|
||||
kf.elements.remove(i);
|
||||
}
|
||||
}
|
||||
let at = at.min(kf.elements.len());
|
||||
kf.elements.splice(at..at, out);
|
||||
kept.extend(picked);
|
||||
Ok(kept)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Shapes added whole (objects): on top, or at the bottom when painting behind.
|
||||
|
||||
@@ -565,6 +565,11 @@ fn panic_hunt_every_command() {
|
||||
json!({"points": [[0, 0, 0.0], [99_999, 99_999, 1.0], [-99_999, 5, 0.5]], "size": 2000, "shape": "square", "angle": 1e6, "roundness": 5, "smoothing": 0, "mode": "behind", "unit": 0.001}),
|
||||
json!({"points": (0..3000).map(|i| json!([i % 7, (i * 13) % 11, f64::from(i % 3) * 0.5])).collect::<Vec<_>>(), "size": 0.1, "mode": "fills", "smoothing": 100, "unit": 1000}),
|
||||
json!({"points": [[5, 5, -1], [6, 6, "x"]], "shape": 3, "mode": null, "roundness": f64::NAN}),
|
||||
// Eraser and Eyedropper (ADR 0034): strokes over the raw shapes, a tip larger than the
|
||||
// stage, picks into the other swatch, styles applied to whatever is selected.
|
||||
json!({"points": [[0, 0], [40, 40], [90, 5]], "size": 30, "mode": "selected_fills", "x": 30, "y": 30, "slop": 0}),
|
||||
json!({"points": [[45, 45]], "size": 2000, "mode": "inside", "x": 45, "y": 45, "other": true, "fill": false, "stroke": true}),
|
||||
json!({"points": [[5, 5], [55, 55]], "size": 4, "mode": "lines", "shape": "square", "x": 1, "y": 1, "fill": "yes"}),
|
||||
];
|
||||
// File commands are exercised separately (they touch the disk).
|
||||
let skip = |id: &str| id.starts_with("file.");
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
# ADR 0034: Eraser and Eyedropper
|
||||
|
||||
* Status: accepted (2026-11-09)
|
||||
* Relates to: ADR 0033 (Brush tool), ADR 0031 (merge drawing), ADR 0018 (variable-width
|
||||
strokes), ADR 0004 (destructive actions)
|
||||
|
||||
## Context
|
||||
|
||||
Animate's Brush has two companions that artists reach for constantly:
|
||||
|
||||
* **Eraser (E).** It sweeps a tip over the drawing and takes away what it covers, on the active
|
||||
layer only. Its modes choose what it takes: *Erase Normal* (lines and fills), *Erase Fills*,
|
||||
*Erase Lines*, *Erase Selected Fills* and *Erase Inside* (only the fill where the stroke
|
||||
starts). The *Faucet* option deletes a whole fill or line with one click. Drawing objects and
|
||||
symbols are not erased. Double-clicking the tool erases everything on the stage.
|
||||
* **Eyedropper (I).** A click on a fill picks its colour, gradient or bitmap; a click on a line
|
||||
picks its colour, width and style. The tool then becomes the Paint Bucket or the Ink Bottle,
|
||||
and with shapes selected the picked style goes onto them.
|
||||
|
||||
We learned the behaviour from Adobe's public help pages and by watching the program. Nothing
|
||||
was copied.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **The eraser is a fill in the merge that comes out empty.** The eraser's outline is the
|
||||
Brush's swept tip (`anicraft_geom::brush::outline`, the same tip model: size, round or
|
||||
square, angle, roundness, pressure), with almost no smoothing (a third of a screen point).
|
||||
It goes into the planar merge (ADR 0031) as one more item with a reserved fill style. The
|
||||
merge already gives each face the topmost fill over it and hides a line that a later fill
|
||||
covers on both sides, so whatever sits under the eraser is replaced by "erased", which is
|
||||
then dropped. The rest comes back as ordinary raw shapes: one element per fill region and
|
||||
per stroke run, lines rejoined through the cut points. There is no new geometry and no
|
||||
format change.
|
||||
|
||||
The mode is only **where the eraser goes in the stack**, among the raw shapes its bounds
|
||||
touch:
|
||||
|
||||
| Mode | Bottom to top |
|
||||
| --- | --- |
|
||||
| Erase Normal | everything, eraser |
|
||||
| Erase Fills | fills, eraser, lines |
|
||||
| Erase Lines | lines, eraser (the fills stay out of the merge, exactly as they are) |
|
||||
| Erase Selected Fills | selected fills, eraser, other fills, lines |
|
||||
| Erase Inside | the fill under the stroke's first point, eraser, other fills, lines |
|
||||
|
||||
Fills don't overlap in a merged drawing, so a fill above the eraser keeps its whole area.
|
||||
Lines above it are only cut at the eraser's edge and joined again. In Erase Lines the fills
|
||||
are left out of the merge, because a fill above a line that ends inside it would hide that
|
||||
line.
|
||||
|
||||
*Rejected:* a general boolean subtraction on paths. The merge already is that operation for
|
||||
raw shapes, with snapping, exact sub-curves and the selection model. A second engine would
|
||||
disagree with it at the edges.
|
||||
|
||||
2. **Only raw shapes are erased.** Drawing objects, gradient or bitmap fills and width-profiled
|
||||
strokes (which the merge keeps whole, ADR 0031), symbols and text are left alone, as in
|
||||
Animate. AniCraft has no "edit inside a symbol" mode yet, so symbols are never erased.
|
||||
|
||||
3. **Nothing erased, nothing changed.** A stroke that only comes near the artwork must not
|
||||
create a keyframe or an undo step. The command compares the total fill area and line length
|
||||
of the shapes it took in with what came out. Areas are exact (Green's theorem with
|
||||
five-point Gauss–Legendre nodes, exact for the degree-5 integrand of a cubic) and lengths use
|
||||
the same nodes. A shape that the merge returns unchanged comes back as the same sub-curves,
|
||||
so it measures the same. If nothing changed, the document is put back as it was.
|
||||
|
||||
4. **Commands** (everything is a command, so it works over the CLI and MCP):
|
||||
* `draw.erase {points, size?, shape?, angle?, roundness?, mode?, unit?}`: one stroke is one
|
||||
undo step. It returns `erased: false` and a reason when there was nothing to erase.
|
||||
* `draw.faucet {x, y, slop?}` deletes the raw fill or line under the point on the active
|
||||
layer. It refuses objects, symbols and text with a message saying how to delete them.
|
||||
* `draw.erase_all {}` clears every visible, unlocked layer's keyframe at the playhead
|
||||
(raw shapes, objects, symbols, text). Tweens on those keyframes are removed, since nothing
|
||||
is left to tween. Locked and hidden layers are kept. ADR 0004: this is a large undoable
|
||||
deletion, so `confirm.rs` asks first, with the counts. The engine doesn't require
|
||||
`"confirm": true` (undo brings it back). The shell runs it on a double-click of the Eraser
|
||||
tool button and from "Erase Everything…" in the Eraser's options.
|
||||
* `paint.pick {x, y, other?, slop?}` (non-mutating, like `draw.object_drawing`) picks from
|
||||
the topmost item drawn under the point on any visible layer, including locked ones.
|
||||
Picking reads; it changes nothing. On a line it picks the colour, the width as drawn
|
||||
(times the transform's scale) and the width profile (a preset when it matches one,
|
||||
otherwise kept as a custom profile). In a fill it picks the paint. `other: true`
|
||||
(Shift-click) puts the picked colour into the other swatch only.
|
||||
* `paint.apply_style {fill?, stroke?}` gives the selected shapes the fill swatch (shapes
|
||||
with a fill) and the stroke settings (shapes with a line, and drawing objects without
|
||||
one). Raw fills don't gain strokes, because their lines are elements of their own.
|
||||
|
||||
All of these are in the existing `draw` and `paint` namespaces, which plug-ins may call.
|
||||
|
||||
5. **A picked gradient or bitmap stays where it is on the stage.** `ToolStyle` gains
|
||||
`fill_paint: Option<Paint>`, in stage space, with `fill` kept as its first colour for the
|
||||
swatch. It also gains `custom_profile` for a picked profile that is none of the presets.
|
||||
Whatever uses the fill swatch maps the paint into the shape's local space
|
||||
(`Paint::transformed`): the Paint Bucket, `paint.apply_style`, and the shape tools. So the
|
||||
gradient carries on across the shapes it is poured into, which is Animate's *Lock Fill*
|
||||
after the Eyedropper. Choosing a colour in the swatch drops it. Linear gradient ends and
|
||||
radial centres are mapped exactly; a radial radius scales by the mean scale, so a skewed or
|
||||
unevenly scaled source picks a near match.
|
||||
|
||||
6. **The tools** are view state over those commands.
|
||||
* **Eraser (E, after the Brush).** A drag collects samples like the Brush and shows the
|
||||
sweep in the stage colour as it goes. Letting go sends one command; a click erases a dab.
|
||||
`[` and `]` step the size.
|
||||
* **Eraser options:** Faucet, Size, Shape, Mode and Erase Everything….
|
||||
* **Eyedropper (I, after the Ink Bottle).** A click picks. With shapes selected, it also
|
||||
applies the picked style. It then becomes the Paint Bucket (after a fill) or the Ink
|
||||
Bottle (after a line). Shift-click picks into the other swatch and stays.
|
||||
* The Fill row in the tool options says when the swatch holds a gradient or a bitmap.
|
||||
* The icons are original, drawn on Lucide's grid.
|
||||
|
||||
## Consequences
|
||||
|
||||
* Measured in release, 32 threads, median of 7. The eraser's outline is computed once per
|
||||
stroke, when it ends, and the merge only takes in what its bounds touch.
|
||||
|
||||
| Stroke | Raw shapes | Median |
|
||||
| --- | --- | --- |
|
||||
| 1000 px wave, size 20, through a grid of 40 outlined rectangles | 200 | 6.4 ms |
|
||||
| Same, Erase Lines | 200 | 6.0 ms |
|
||||
| Same, size 80 | 200 | 4.0 ms |
|
||||
| Same wave through 30 brushed waves | 30 | 22 ms |
|
||||
|
||||
* Tested:
|
||||
* A 20 wide band through a 200 × 100 rectangle leaves 18 000 units², within 40.
|
||||
* Each mode's area and line length are analytic.
|
||||
* The faucet; objects and symbols untouched, with no undo step.
|
||||
* Erase Everything asks and keeps locked layers.
|
||||
* Solid, gradient and line picks; picking into the other swatch; applying to the selection.
|
||||
* The every-command fuzz and the file round trip.
|
||||
* The eraser cuts lines by their centre line. A thin eraser grazing the edge of a thick line
|
||||
without crossing its centre takes nothing, and the cut ends keep their round caps.
|
||||
* The live preview paints the stage colour over everything, including objects and other layers
|
||||
that the stroke will keep.
|
||||
|
||||
## Not yet
|
||||
|
||||
* Erasing inside symbols (needs an edit-in-place mode).
|
||||
* Erasing gradient, bitmap or width-profiled shapes (needs them in the merge).
|
||||
* Eraser pressure.
|
||||
* A preview through the merge.
|
||||
* The Eyedropper picking a bitmap's pixel colour (it picks the bitmap fill itself) and text
|
||||
styles.
|
||||
* An eyedropper cursor.
|
||||
* Showing a gradient in the toolbar swatch.
|
||||
+3
-3
@@ -11,7 +11,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| Architecture | M0 skeleton in place: geom → doc → render → engine → cli → shell, layering enforced by `cargo test` (`src/architecture_tests.rs`: lower layers only, no UI crates below the shell, and the AGENTS.md map must match). |
|
||||
| Rendering | CPU oracle with analytic AA, non-zero/even-odd, solid + linear/radial gradients, round-join strokes. **Mask clipping**: the display list carries nested clips; a clip is the anti-aliased union of its mask fills (strokes and opacity ignored), intersected with any enclosing clip, computed once per render band; an empty mask hides everything under it. **Group alpha**: a symbol instance below full opacity is a group in the display list; each render band composites the group's run of ops into its own buffer (nested groups stack) and blends it once at the group's alpha, so overlaps don't show through; SVG export writes `<g opacity>`. **Blend modes** (Animate's 14, on movie clip and button instances): an instance with one is an isolated group that blends at its close with the W3C separable formulas on premultiplied colour (Alpha and Erase keep or clear the backdrop); SVG gets CSS `mix-blend-mode`, Lottie the layer `bm`. **Bitmaps**: `Paint::Bitmap` fills (once or tiled) with bilinear sampling in premultiplied space, colour effects per sample; PNG/JPEG import to stage (a rectangle of the image's size); stored in the document as PNG (base64 in `.anicraft`), decoded once on first use; SVG export embeds each image once as a pattern. **Filters**: a filtered group is drawn on its own (by the same renderer, recursively, so nested filters work) into a buffer over its artwork grown by the filters' reach, filtered (box-blur passes; shadow and glow from the blurred, offset opacity; **bevel and gradient bevel** from the difference of the blurred opacity offset towards and away from the light, **gradient glow** from the glow's intensity, both through a colour ramp whose rest stop is pinned transparent, inner/outer/full and knockout, ADR 0025; colour matrix), and composited back as one image in its group, so alpha and blend apply; clips from inside the symbol apply before filtering and the instance's own clip after. **GPU stage, first slice** (M3, ADR 0019; `--features gpu-stage`, off by default): Preferences › Stage › Renderer *GPU (preview)* draws the stage with wgpu compute from the oracle's own prepared fills (tile binning with per-row backdrops on the CPU, exact area coverage and src-over per pixel on the GPU): solid and gradient fills and strokes, non-zero and even-odd; masks, group opacity, blend modes, filters and bitmaps fall back to the CPU per tile, and the status bar says so. Parity with the oracle: max 1/255, mean < 0.0001/255 on the sample, stress and analytic scenes (tests skip without an adapter). 4K with 1,000 shapes: 8.8–9.0 ms vs the CPU's 17.4–17.8 ms. **Second slice** (ADR 0029): on the window's wgpu device the stage tiles are drawn straight into textures egui shows (no readback; a headless device with readback when the window is on OpenGL); **masks** (nested, united artwork), **group opacity** and **all 14 blend modes** on the GPU, same parity (max 1/255, mean ≤ 0.0011/255); 4K: 1,000 shapes in 2.1–2.4 ms, 10k shapes in 10.2 ms as stage tiles, masked scenes 7× the CPU. **Third slice** (ADR 0032): **bitmap fills** (textures uploaded once per image and cached under a 256 MB budget, sampled with the oracle's own bilinear filter, colour effect and repeat rules: byte-identical) and **all seven filters** (each filtered symbol drawn into a layer of its own and filtered by compute passes that run the oracle's resolved steps: max 1/255, mean ≤ 0.007/255) on the GPU; the shaders now build with Direct3D's FXC, so DX12 windows get the GPU stage too (parity suite green on Vulkan and DX12); software adapters are refused (the CPU is faster), the start-up self-test compares with the oracle. **The GPU is the default stage renderer**: the shell's `gpu-stage` feature is on by default, Preferences › Stage › Renderer defaults to *Graphics card (GPU)*, and the CPU draws whenever there is no usable card, a tile is past the GPU's limits (more than 16 images, filters nested deeper than 4) or anything fails. 4K: the filtered sample in 3.9 ms (CPU 31.5), 200 bitmap fills in 4.4 ms (CPU 37.2). Not yet: sharing a filtered layer across a frame's tiles, more than 16 images per tile, GPU binning (ADR 0029), buffer reuse across tiles, GPU exports, a GPU runner in CI; the CPU stays the oracle and the export path. |
|
||||
| Timeline | **Frame selection**: click, Shift-click or drag across frames and layers; F5/Shift+F5, F6/F7 and Shift+F6 (keys, buttons and right-click menu) act on the whole selection; drag selected keyframes left or right to move them, and up or down onto other layers (the source keeps empty frames, as in Animate) (with a drop outline; one undo step; keys they land on are replaced, and spans fill the frames left behind); removing or clearing selected frames that hold artwork asks first. **Cut/Copy/Paste Frames** (Ctrl+Alt+X/C/V, and plain Ctrl+X/C/V after clicking the timeline): own clipboard, copies cut exactly at the selection edges (mid-tween state kept), paste inserts like Animate, several layers paste onto the layers below (missing ones are created), fresh element ids, symbols travel with them. **Span length by dragging its end** (resize cursor, live outline with the length in frames and seconds; later frames move with it). Headless: `layers`/`count` on the frame commands, `timeline.move_keyframes`, `timeline.cut_frames/copy_frames/paste_frames`. Layers (show/lock/outline), keyframes, blank keyframes, insert/remove frames, classic tweens with 8 easing presets + curve preview, **shape tweens** (morph between any two shapes: segments made cubic, subpaths paired by size and grown from or shrunk to a point when counts differ, segment counts equalized by subdivision, windings matched and start points aligned; amber spans; classic ⇄ shape keeps the easing; **shape hints** (ADR 0023): Modify › Shape › Add Shape Hint (Ctrl+Shift+H) adds lettered markers `a`–`z` that the artist drags onto an edge on the first and last keyframe (rose until placed, amber placed on the first, mint on the last; right-click removes), the morph cuts both outlines at the hinted points and matches the pieces in order by length; `tween.add_hint/move_hint/remove_hint/clear_hints/hints`; not yet: View › Show Shape Hints, hints inside symbols edited in place), auto-key when editing inside a tween, frame labels, symbol nesting: graphics keep step with their timeline (loop, play once, single frame, first frame; set in Properties), movie clips loop their own timeline from when the instance appears (continuous across keyframes holding the same instance), buttons show their Up frame, onion skin (±2 frames), looping playback. **Mask layers**: right-click a layer › Mask turns it into a mask over the layer below (Masked adds more layers to it); masked layers are indented under a stencil icon; the mask applies on the stage and in every export alike, and while the mask layer is unlocked its edge shows in the layer colour so it can be picked and reshaped; masked-away parts cannot be picked; layers moved in under a mask join it, moved out leave it, and a mask moves with its whole group; masks inside symbols nest. Headless: `layer.toggle_mask`, `layer.set_type`. **Scenes** (ADR 0011): the movie is an ordered list of scenes, each its own timeline, edited one at a time (scene menu on the edit bar, Insert › Scene, Modify › Scene, Shift+PageUp/PageDown); add, duplicate (fresh ids), rename, reorder and remove (asks when the scene has artwork; undoable); PNG-sequence and GIF exports play every scene in order. **Layer folders**: nestable folders (depth ≤ 16) holding layers and masks through `Layer.parent`, one invariant (`Timeline::repair_masks`: a child sits below its parent inside the parent's unbroken run; broken links fall back to the nearest valid ancestor); hiding or locking a folder hides or locks its contents (rendering, picking, drawing); folders open and close on the timeline (view state); layers move in and out with Up/Down, a folder moves with its contents; deleting a folder deletes its contents (asks first). **Motion tweens** (ADR 0016): a span's object animated property by property (x, y, scale, rotation, skew, alpha, tint), each property its own curve of property keyframes with a per-segment ease (presets or a custom cubic Bézier, overshoot allowed); auto-key turns any edit of the object inside the span into property keys (every command, through the session), F6 keys every property, splits and copies keep the motion; sky-blue spans with property-key diamonds; **Motion Editor** tab beside the timeline: property list with values at the playhead, curve graph with draggable keys and Bézier handles, one undo step per drag. **Motion paths** (ADR 0030): a motion tween may carry a cubic path its object travels by arc length, timed by the X/Y curves (a straight path reproduces them exactly, overshoot included); shown on the stage in the motion colour with a dot per frame when the object or span is selected; Selection drags the path to bend it and its ends to move them, Subselection drags anchors and handles; moving the object reshapes the path; Orient to path and Straighten in Properties; splits cut the path. Headless: `timeline.create_motion_tween`, `motion.*` (`motion.set_path/clear_path/orient`). Not yet: adding/deleting path poLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. Not yet: bending segments by dragging, snapping, moving shared points together, partial marquee selection, merging bucket fills and pastes, XFL raw shapes, gradients and width profiles in the merge. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and PLine truncated
|
||||
| Drawing | Selection (click, shift-add, marquee, drag-move, arrow nudge), **Free Transform (Q)**: scale from corner/edge handles (Shift proportional, Alt from centre), rotate outside corners (Shift snaps 15°), move; one undo step per drag. Rectangle (corner radius), oval, PolyStar, line (45° snap), hand, zoom. **Pen (P)**: click for corners, drag for smooth handles (Alt breaks them), close on the first point, Enter/Esc/last-point click finishes, Backspace takes back a point; one undo step per path. **Pencil (Shift+Y)**: Smooth (Schneider curve fitting with corner detection), Straighten and Ink modes, smoothing relative to the screen. **Subselection (A)**: anchors and handles on selected shapes, drag points/handles (anchors bring their handles; one undo step per drag), point marquee, double-click an edge to add a point, Delete removes points, right-click Make Smooth/Corner; closed shapes' start point and closing edge edit like any other. **Cut/Copy/Paste in Center/Paste in Place** (the clipboard carries symbols across documents). **Rotate 90° CW/CCW, Flip H/V. Align** left/centre/right/top/middle/bottom (Ctrl+Alt+1…6; a single element aligns to the stage) and distribute. Convert to symbol / break apart; arrange; duplicate. Headless: `draw.path`, `draw.freehand`, `path.move_points/add_point/delete_points/convert_point`. **Paint Bucket (K)**: click a fill to recolour it, or inside an outline (one shape or several) to fill the enclosed area; gap size None/Small/Medium/Large closes openings; the fill is traced and curve-fitted into a new shape placed under its lines; open areas say so instead of flooding. **Ink Bottle (S)**: gives the clicked shape the current stroke. Headless: `paint.bucket`, `paint.ink`. Tool options show first in Properties while a drawing tool is active. **Text (T)** (ADR 0012): click to type on the stage, click or double-click text to edit it; font (installed families, plus the embedded Inter), size, colour, bold, italic, alignment, letter/line spacing, wrap width; the last style is kept for new text; laid out by `anicraft-text` (`fontdb` discovery, `harfrust` shaping, `skrifa` outlines) and stored as outlines with the source, so rendering never needs the font; Break Apart makes a shape. **Variable-width strokes** (ADR 0018): a stroke's width varies along it through width points (position by arc length, a width on each side as a factor of the stroke width, smooth monotone interpolation); built-in profiles (Uniform, Taper both ends, Taper start, Taper end, Bulge, Pinch) in Properties › Width with a picture of each, and in the drawing tools' options for new strokes; the **Width tool (U)**: hover a stroke to see its width points, drag a handle to widen or narrow (Alt: one side), drag the dot to slide a point, drag anywhere on the stroke to add one, Delete removes; one undo step per drag; rendered by the oracle as trapezoids with outer round joins and cross-section caps, written by SVG and Lottie export as the same filled outlines; shape tweens blend profiles; `.anicraft` keeps them (older files open as uniform). Headless: `stroke.set_profile`, `stroke.set_width_point`, `stroke.delete_width_point`, `stroke.width_at`, `profile` on `element.set_stroke`, the drawing commands and `paint.ink`. Not yet: width data from or to Animate files, saved custom profiles, pressure. **Merge drawing** (ADR 0031, first slice): with Object Drawing (J) off, the editor's default, the shape tools, Pen and Pencil draw raw strokes and fills that cut and join the raw shapes they touch (a fill on top replaces what it covers or joins the same colour, lines cut each other and the fills they cross, a fill hides the lines under it, points within 0.2 px are one; exact Bézier pieces, `anicraft_geom::planar`); one element per fill region and stroke run, selected with Animate's dot pattern; double-click selects connected strokes, or a fill with its outline; a dragged or nudged raw shape merges where it lands; arrows move 1 screen pixel (Shift 10). Headless: `object` on the drawing commands (scripts draw objects by default), `draw.object_drawing`, `draw.drop`, `element.select_connected`. Not yet: bending segments by dragging, snapping, moving shared points together, partial marquee selection, merging bucket fills and pastes, XFL raw shapes, gradients and width profiles in the merge. **Brush (B)** (ADR 0033, first slice): paints filled shapes in the fill colour, the exact area the tip sweeps (a distance field traced and fitted with cubics); round or square tip with size, angle and roundness (oval and flat calligraphic tips), pen pressure from a tablet (10–100 % of the size; a mouse paints full size), smoothing relative to the screen, Paint Normal, Paint Fills and Paint Behind; a raw shape that merges with the drawing, or a drawing object with Object Drawing on; a click paints a dab; live preview while dragging; `[` and `]` change the size; one undo step per stroke. Headless: `draw.brush`. Not yet: Paint Selection and PLine truncated
|
||||
| Plug-ins | **WebAssembly plug-ins** (ADR 0017, `docs/plugins.md`): sandboxed modules run by `wasmi` with no imports but the AniCraft ABI (`anicraft.call`/`anicraft.response`: JSON requests that run registry commands, read a compact document view or the active layer's elements, and log); fuel (10⁹ instructions), memory (256 MiB), wall-clock (5 s), request, size and log limits, a fresh instance per run; file, plug-in, undo and clipboard commands refused. `plugin.install/list/run/remove/reload`; a run is atomic and one undo step named after the plug-in. App: **Commands** menu (Plug-ins, Install, Manage, Reload), palette entries, a dialog generated from the manifest's parameters with a live preview; plug-ins load from `<settings>/plugins` or `ANICRAFT_PLUGINS`; CLI `--plugins`. Samples in Rust (Star Field, Jitter Selection, guest SDK) in `examples/plugins`. Frame scripts: see Interactivity. Not yet: exporter and easing kinds, background runs with cancel, a binary document view. |
|
||||
| Interactivity | **Frame actions, frame scripts and Test Movie, first slice** (ADR 0024): a typed timeline action IR (`anicraft-actions`: stop, play, go to a frame or label in a scene, next/previous frame and scene, trace, set x/y/alpha/visible/rotation/scale, instance-name target paths) on keyframes and on button and movie clip instances (click, press, release, over, out); a pure, deterministic, budgeted player in `anicraft-doc` (`step(doc, &state, &events)`; movie clip playheads, button Up/Over/Down states with Hit-frame hit tests, script-set properties) drawn by `evaluate_player`, while `evaluate` and exports stay script-free. **Actions panel** (F9: structured lists, targets/labels/scenes picked from the document; movie clip timelines too), instance name and events in Properties, an "a" on keyframes with actions. **Frame scripts** on the plug-in host (`kind: "frame-script"`, entry points, `player`/`action` ops, 20 M instructions per frame shared, no document access). **Test Movie** (Control › Test Movie, Ctrl+Enter): the player at the document frame rate in its own window with the pointer, restart/pause/step and an Output panel. Headless: `actions.set/clear/list`, `instance.set_name`, `control.test_movie` (timed pointer events, returns output and state). **HTML canvas export** (ADR 0028, `file.export_html`, File › Export › Export HTML Canvas…): one self-contained page (data, player and drawing code inline; images and sounds embedded) that plays in any browser with canvas 2D; every used timeline baked frame by frame (tweens of every kind exact, identical paths, paints and frames stored once), movie clips, buttons with Hit areas and every action run by `player.js`, a port of the Rust player checked against it step by step in Boa (state, output and display list); masks and fading/blending groups on offscreen layers; Web Audio for Event/Start/Stop/Stream sounds; filters, Subtract/Invert, bitmap tints and plug-in frame scripts reported. Not yet: ActionScript (ADR 0013 tiers), filters and keyboard focus in the HTML page, sound actions, keyboard events, variables, persistent script state, masks in hit tests, a separate OS window. |
|
||||
| Headless | CLI: info, render, render-seq, **gif**, commands, exec, run, serve (JSON-lines). **MCP server** (`anicraft-cli mcp`, `docs/mcp.md`): stdio JSON-RPC, protocol 2025-06-18 (and 2025-03-26, 2024-11-05); five tools over the command registry (list, run, run a script, describe the document, render a frame as a PNG picture); confirmation tiers and undo apply as in the app. |
|
||||
@@ -36,7 +36,7 @@ milestone ends with a green tree: build, tests, clippy, a `--screenshot` check a
|
||||
| **M4** | Interchange *(in progress)* | **XFL import** (DOMDocument.xml, symbols, edges/fill styles decoded from the public format descriptions) with a corpus of self-authored files: first slice ✅ (see Files above); ~~SVG import (Import to Stage)~~ ✅, ~~SVG frame export~~ ✅; ~~Lottie export~~ ✅ (frame-accurate; easing curves instead of per-frame keys later); ~~sprite sheet + JSON~~ ✅; ~~MP4/WebM via ffmpeg pipe~~ ✅. |
|
||||
| **M5** | Rich media | ~~Text engine~~ ✅ first slice (ADR 0012: `harfrust` shaping, `skrifa` outlines, line wrapping, outlines stored with the text; per-character styles, text on a path and input fields later); ~~bitmap import and bitmap fills~~ ✅; ~~audio layers, waveform display, stream sync~~ ✅ first slice (ADR 0020: WAV, Ogg Vorbis, MP3; `cpal` output; effects, volume and sounds in symbols later); ~~filters (blur, drop shadow, glow, colour matrix)~~ ✅, ~~bevel, gradient glow and gradient bevel~~ ✅ (ADR 0025; SVG export and XFL import; filter presets, reordering, on/off and tweened filter values later) and ~~blend modes~~ ✅ on Movie Clips. |
|
||||
| **M6** | Interactivity & extensibility | **Plug-ins: the Craft-family WebAssembly system** (same host model as PhotoCraft: `wasmi` sandbox, `plugin.*` commands; AniCraft ABI for vector/timeline operations and exporters): first slice ✅ (command plug-ins over the registry, ADR 0017; exporter and easing kinds later); ~~frame scripts on the same sandbox~~ ✅ and ~~button states in test-movie preview~~ ✅ first slice (ADR 0024: action IR, pure player, Actions panel, Test Movie); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028: one self-contained page, baked frames, a JS port of the player tested against it); command macros. **ActionScript compatibility, low priority** (ADR 0013), last in M6 and free to slip past M8: tier 1 keeps scripts (XFL frame scripts and class names stored verbatim, Actions panel, `script.*` commands); tier 2 runs the ActionScript 3 timeline subset (stop, play, go to frame or label, named instances, button events) in Test Movie and HTML canvas export through the same action IR as WebAssembly frame scripts. The full language, the `flash.*` API and SWF bytecode are not planned. |
|
||||
| **M7** | Advanced animation | Bone/IK tool; ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside, Eraser, Eyedropper) and brush library; asset warp; graph-based easing presets library. |
|
||||
| **M7** | Advanced animation | Bone/IK tool; ~~camera layer with depth~~ ✅ first slice (ADR 0027: one camera layer per scene, pan/zoom/rotate/tint, classic and motion tweens, pan-only layer depth, Camera tool, Preview Through Camera, every export; not yet: editing while previewing, perspective depth, brightness/advanced colour, attaching layers to the camera, XFL camera import); ~~variable-width strokes~~ ✅ first slice (ADR 0018: width profiles, Width tool, exports, tweens); ~~Brush tool~~ ✅ first slice (ADR 0033: filled sweeps, tips, pressure, Paint Normal/Fills/Behind; not yet: Paint Selection/Inside); ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034: five erase modes, Faucet, Erase Everything; picks solid, gradient, bitmap and line styles; not yet: erasing inside symbols, gradients and width profiles in the merge) and brush library; asset warp; graph-based easing presets library. |
|
||||
| **M8** | Release quality | ~~Installers and signing for Windows/macOS/Linux~~ ✅ first slice (ADR 0026: family `packaging/` layout, MSI, DMG, AppImage/deb/rpm/Flatpak/tar.gz, `.anicraft` registered everywhere, signing wired to the release environment; next: opening documents from Finder, AppImage desktop integration, portable mode, store submissions); web build (wasm) of the editor; localisation; accessibility: first pass ✅ (ADR 0022: screen-reader names for every control, Ctrl+F6 panel focus, high-contrast theme, 200 % scale), next: stage elements and frames for screen readers, keyboard menu bar, the OS contrast setting; ~~crash-recovery autosave~~ ✅ (ADR 0015); documentation book. |
|
||||
|
||||
## Releases
|
||||
@@ -57,7 +57,7 @@ titled with its milestone.
|
||||
| M4 | Text from Animate files | XFL import, text engine (M5 first slice) |
|
||||
| M5 | Audio layers: import, waveform, playback sync | timeline, layers |
|
||||
| M6 | ~~WebAssembly plug-ins (U2)~~ ✅ first slice (ADR 0017); ~~frame scripts and Test Movie on the plug-in host~~ ✅ first slice (ADR 0024); ~~HTML canvas runtime export~~ ✅ first slice (ADR 0028); next: command macros | command registry, plug-in host, action IR and player |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Brush tool~~ ✅ first slice (ADR 0033); next: Eraser and Eyedropper, then Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M7 | ~~Variable-width strokes~~ ✅ (ADR 0018), ~~camera layer with depth~~ ✅ first slice (ADR 0027), ~~Brush tool~~ ✅ first slice (ADR 0033), ~~Eraser and Eyedropper~~ ✅ first slice (ADR 0034); next: Paint Selection/Inside and the brush library | strokes, Pen and Pencil, width profiles, timeline evaluation |
|
||||
| M8 | ~~Crash-recovery autosave~~ ✅, ~~accessibility first pass~~ ✅ (ADR 0022), ~~installers and signing~~ ✅ first slice (ADR 0026); next: the accessibility follow-ups, or macOS document opening | `.anicraft` format, session, AccessKit in eframe |
|
||||
|
||||
Tasks that wait on an open track: XFL motion tweens (on M2's motion tweens); frame scripts and
|
||||
|
||||
+1
-1
@@ -348,7 +348,7 @@ mod tests {
|
||||
fn every_interactive_node_has_a_name_and_a_role() {
|
||||
let mut found = Vec::new();
|
||||
found.extend(check("default", |_, _| {}));
|
||||
for tool in [Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::PaintBucket, Tool::InkBottle, Tool::Pen] {
|
||||
for tool in [Tool::Rect, Tool::Star, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Pen] {
|
||||
found.extend(check(&format!("{tool:?} tool"), |a, _| a.tool = tool));
|
||||
}
|
||||
for panel in ["select", "motion", "motionspan", "motionpath", "motionpoints", "camera", "cameraview", "sound", "prefs", "shortcuts", "palette", "about", "files", "licenses", "confirm", "recovery", "frames"] {
|
||||
|
||||
+47
-1
@@ -20,12 +20,14 @@ pub enum Tool {
|
||||
Text,
|
||||
Pencil,
|
||||
Brush,
|
||||
Eraser,
|
||||
Rect,
|
||||
Oval,
|
||||
Star,
|
||||
Line,
|
||||
PaintBucket,
|
||||
InkBottle,
|
||||
Eyedropper,
|
||||
Camera,
|
||||
Hand,
|
||||
Zoom,
|
||||
@@ -63,7 +65,7 @@ impl GapSize {
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
pub const ALL: [Tool; 17] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Width, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Camera, Tool::Hand, Tool::Zoom];
|
||||
pub const ALL: [Tool; 19] = [Tool::Select, Tool::Subselect, Tool::Transform, Tool::Width, Tool::Pen, Tool::Text, Tool::Pencil, Tool::Brush, Tool::Eraser, Tool::Rect, Tool::Oval, Tool::Star, Tool::Line, Tool::PaintBucket, Tool::InkBottle, Tool::Eyedropper, Tool::Camera, Tool::Hand, Tool::Zoom];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
@@ -75,12 +77,14 @@ impl Tool {
|
||||
Tool::Text => "Text",
|
||||
Tool::Pencil => "Pencil",
|
||||
Tool::Brush => "Brush",
|
||||
Tool::Eraser => "Eraser",
|
||||
Tool::Rect => "Rectangle",
|
||||
Tool::Oval => "Oval",
|
||||
Tool::Star => "PolyStar",
|
||||
Tool::Line => "Line",
|
||||
Tool::PaintBucket => "Paint Bucket",
|
||||
Tool::InkBottle => "Ink Bottle",
|
||||
Tool::Eyedropper => "Eyedropper",
|
||||
Tool::Camera => "Camera",
|
||||
Tool::Hand => "Hand",
|
||||
Tool::Zoom => "Zoom",
|
||||
@@ -97,12 +101,14 @@ impl Tool {
|
||||
Tool::Text => Some("T"),
|
||||
Tool::Pencil => Some("Shift+Y"),
|
||||
Tool::Brush => Some("B"),
|
||||
Tool::Eraser => Some("E"),
|
||||
Tool::Rect => Some("R"),
|
||||
Tool::Oval => Some("O"),
|
||||
Tool::Star => None,
|
||||
Tool::Line => Some("N"),
|
||||
Tool::PaintBucket => Some("K"),
|
||||
Tool::InkBottle => Some("S"),
|
||||
Tool::Eyedropper => Some("I"),
|
||||
Tool::Camera => Some("C"),
|
||||
Tool::Hand => Some("H"),
|
||||
Tool::Zoom => Some("Z"),
|
||||
@@ -116,6 +122,7 @@ impl Tool {
|
||||
Tool::Text => "Click to type new text, or click text to edit it. Esc or a click elsewhere finishes. The options set the font, size and colour; double-click text with the Selection tool to edit it too.",
|
||||
Tool::Pencil => "Drag to draw freehand. The options bar sets Smooth, Straighten or Ink.",
|
||||
Tool::Brush => "Drag to paint filled shapes in the fill colour (a click paints a dab). [ and ] change the size; the options set the shape, smoothing and paint mode.",
|
||||
Tool::Eraser => "Drag to erase lines and fills drawn with Object Drawing off (drawing objects and symbols are kept). [ and ] change the size; the options set the shape and erase mode, and the Faucet deletes a whole fill or line with a click. Double-click the tool to erase everything on the stage.",
|
||||
Tool::Width => "Hover a stroke to see its width points. Drag a point's handle to widen or narrow the stroke there (Alt: one side only), drag its dot to slide it along, or drag anywhere on the stroke to add a point. Click a point and press Delete to remove it.",
|
||||
Tool::Transform => "Drag a corner or edge to scale (Shift keeps proportions, Alt scales from the centre), just outside a corner to rotate (Shift snaps 15°), inside to move.",
|
||||
Tool::Rect => "Drag to draw a rectangle. Shift draws a square.",
|
||||
@@ -124,6 +131,7 @@ impl Tool {
|
||||
Tool::Line => "Drag to draw a line. Shift snaps to 45°.",
|
||||
Tool::PaintBucket => "Click inside an outline to fill it (on the layer's lines), or on a fill to recolour it. The gap size closes small openings.",
|
||||
Tool::InkBottle => "Click a shape to give it the current stroke colour and width.",
|
||||
Tool::Eyedropper => "Click a fill to pick its colour, gradient or bitmap (then pour it with the Paint Bucket), or a line to pick its colour, width and profile (then apply it with the Ink Bottle). With shapes selected, the picked style goes onto them. Shift-click picks into the other swatch only.",
|
||||
Tool::Camera => "Drag on the stage to pan the camera, drag the round handle to turn it, and use the wheel to zoom (each drag is one undo step). Picking the tool adds a camera if the scene has none.",
|
||||
Tool::Hand => "Drag to pan the stage. Space works with any tool.",
|
||||
Tool::Zoom => "Click to zoom in, Alt-click to zoom out. Ctrl+wheel zooms anywhere.",
|
||||
@@ -177,6 +185,8 @@ pub enum Drag {
|
||||
Pencil,
|
||||
/// Brush stroke; the samples are in `App::brush_samples`.
|
||||
Brush,
|
||||
/// Eraser stroke; the samples are in `App::brush_samples` too (ADR 0034).
|
||||
Eraser,
|
||||
/// Width tool: resizing (or sliding) width point `index` of shape `id`, found on subpath
|
||||
/// `sub`; `start` is its left and right width when the drag began.
|
||||
Width { id: anicraft_engine::doc::ElementId, sub: usize, index: usize, grip: crate::widthtool::Grip, start: (f32, f32) },
|
||||
@@ -291,6 +301,8 @@ pub struct App {
|
||||
pub brush: crate::brushtool::BrushOptions,
|
||||
pub brush_samples: Vec<(anicraft_engine::geom::Vec2, Option<f32>)>,
|
||||
pub pen_pressure: Option<f32>,
|
||||
/// Eraser tool options (ADR 0034); its stroke's samples are `brush_samples`.
|
||||
pub eraser: crate::erasertool::EraserOptions,
|
||||
pub bucket_gap: GapSize,
|
||||
/// Align panel: align to the stage rather than the selection's bounds.
|
||||
pub align_to_stage: bool,
|
||||
@@ -443,6 +455,7 @@ impl App {
|
||||
brush: crate::brushtool::BrushOptions::default(),
|
||||
brush_samples: Vec::new(),
|
||||
pen_pressure: None,
|
||||
eraser: crate::erasertool::EraserOptions::default(),
|
||||
bucket_gap: GapSize::default(),
|
||||
align_to_stage: false,
|
||||
points: Vec::new(),
|
||||
@@ -777,6 +790,35 @@ impl App {
|
||||
self.drag = Drag::Brush;
|
||||
}
|
||||
}
|
||||
Some(which @ ("eraser" | "erasing")) => {
|
||||
// Erased artwork on a new layer (ADR 0034): a band through an outlined raw
|
||||
// rectangle (Erase Normal), the outline of a raw oval erased but not its fill
|
||||
// (Erase Lines), a fill deleted by the Faucet, and a drawing object the eraser
|
||||
// passed over untouched; "erasing" also has a stroke in progress.
|
||||
self.run("layer.new", json!({"name": "Ink"}));
|
||||
self.run("draw.object_drawing", json!({"on": false}));
|
||||
self.run("draw.rect", json!({"x": 140, "y": 150, "w": 380, "h": 230, "fill": "#f2c14e", "stroke": "#1b2a4a", "stroke_width": 4}));
|
||||
let band: Vec<[f32; 2]> = (0..=80).map(|i| [100.0 + i as f32 * 5.5, 265.0 + (i as f32 * 0.12).sin() * 60.0]).collect();
|
||||
self.run("draw.erase", json!({"points": band, "size": 30}));
|
||||
self.run("draw.ellipse", json!({"x": 600, "y": 160, "w": 260, "h": 200, "fill": "#3d8bfd", "stroke": "#1b2a4a", "stroke_width": 6}));
|
||||
self.run("draw.erase", json!({"points": [[560, 260], [900, 260]], "size": 40, "mode": "lines"}));
|
||||
self.run("draw.rect", json!({"x": 940, "y": 160, "w": 200, "h": 200, "fill": "#e8553b", "stroke": "#1b2a4a", "stroke_width": 4}));
|
||||
self.run("draw.faucet", json!({"x": 1040, "y": 260}));
|
||||
self.run("draw.rect", json!({"x": 300, "y": 430, "w": 300, "h": 120, "fill": "#8a79c9", "stroke": null, "object": true}));
|
||||
self.run("draw.erase", json!({"points": [[260, 490], [640, 490]], "size": 30}));
|
||||
self.run("edit.deselect", json!({}));
|
||||
self.tool = Tool::Eraser;
|
||||
self.eraser = crate::erasertool::EraserOptions { size: 30.0, ..Default::default() };
|
||||
if which == "erasing" {
|
||||
self.brush_samples = (0..=40).map(|i| (anicraft_engine::geom::Vec2::new(700.0 + i as f32 * 9.0, 470.0 - (i as f32 * 0.2).sin() * 40.0), None)).collect();
|
||||
self.drag = Drag::Eraser;
|
||||
}
|
||||
}
|
||||
Some("eyedropper") => {
|
||||
// The sample's sky gradient picked with the Eyedropper: the fill swatch holds it.
|
||||
self.run("paint.pick", json!({"x": 640, "y": 40}));
|
||||
self.tool = Tool::Eyedropper;
|
||||
}
|
||||
Some("frames") => {
|
||||
// Frames 8–20 selected on the top three layers, with a keyframe drag in progress:
|
||||
// 6 frames later and one layer down.
|
||||
@@ -1055,6 +1097,10 @@ impl App {
|
||||
"edit.redo" => self.status_ok(format!("Redid {}", v["redone"].as_str().unwrap_or(""))),
|
||||
"edit.delete" => self.status_ok(format!("Deleted {} {} — Ctrl+Z to undo", selected, if selected == 1 { "element" } else { "elements" })),
|
||||
"layer.delete" => self.status_ok("Deleted layer — Ctrl+Z to undo"),
|
||||
"draw.erase_all" => {
|
||||
let n = v["erased"].as_u64().unwrap_or(0);
|
||||
self.status_ok(format!("Erased everything at frame {} ({n} {}). {} to undo.", self.s.frame + 1, if n == 1 { "element" } else { "elements" }, platform::shortcut_label("Ctrl+Z")));
|
||||
}
|
||||
"scene.delete" => {
|
||||
self.frame_sel = None;
|
||||
self.status_ok("Deleted scene — Ctrl+Z to undo");
|
||||
|
||||
+63
-36
@@ -39,7 +39,7 @@ pub const SIZE_MAX: f32 = 400.0;
|
||||
|
||||
impl BrushOptions {
|
||||
/// The tip mapped onto the stage, for previews: unit circle or square → the tip at `at`.
|
||||
fn tip_to_stage(&self, at: Vec2, factor: f32) -> Affine {
|
||||
pub fn tip_to_stage(&self, at: Vec2, factor: f32) -> Affine {
|
||||
let tip = anicraft_engine::geom::brush::Tip { shape: self.shape, size: self.size * factor, angle: self.angle, roundness: self.roundness / 100.0 };
|
||||
Affine::translate(at.x, at.y).mul(&tip.to_stage())
|
||||
}
|
||||
@@ -63,13 +63,19 @@ pub fn step_size(size: f32, larger: bool) -> f32 {
|
||||
((next / g).round() * g).clamp(SIZE_MIN, SIZE_MAX)
|
||||
}
|
||||
|
||||
/// Changes the size from the keyboard and says so.
|
||||
/// Changes the Brush's or the Eraser's size from the keyboard and says so.
|
||||
pub fn resize(app: &mut App, larger: bool) {
|
||||
if app.tool != Tool::Brush {
|
||||
return;
|
||||
match app.tool {
|
||||
Tool::Brush => {
|
||||
app.brush.size = step_size(app.brush.size, larger);
|
||||
app.status_ok(format!("Brush size {} px", app.brush.size));
|
||||
}
|
||||
Tool::Eraser => {
|
||||
app.eraser.size = step_size(app.eraser.size, larger);
|
||||
app.status_ok(format!("Eraser size {} px", app.eraser.size));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
app.brush.size = step_size(app.brush.size, larger);
|
||||
app.status_ok(format!("Brush size {} px", app.brush.size));
|
||||
}
|
||||
|
||||
/// The pen's pressure this frame, when a tablet reports it (egui gives it with touch events).
|
||||
@@ -89,6 +95,20 @@ pub fn start(app: &mut App, p: Vec2, pressure: Option<f32>) -> Drag {
|
||||
Drag::Brush
|
||||
}
|
||||
|
||||
/// The stroke's samples as command points (with pressure when a pen gave any).
|
||||
pub fn points(samples: &[(Vec2, Option<f32>)]) -> Vec<serde_json::Value> {
|
||||
let pen = samples.iter().any(|(_, p)| p.is_some());
|
||||
samples.iter().map(|(v, p)| if pen { json!([v.x, v.y, p.unwrap_or(1.0)]) } else { json!([v.x, v.y]) }).collect()
|
||||
}
|
||||
|
||||
/// A tip shape's name in commands.
|
||||
pub fn shape_key(s: TipShape) -> &'static str {
|
||||
match s {
|
||||
TipShape::Round => "round",
|
||||
TipShape::Square => "square",
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a sample (closer than half a screen point adds nothing unless the pressure moved).
|
||||
pub fn sample(app: &mut App, p: Vec2, pressure: Option<f32>, xf: Xf) {
|
||||
if pressure.is_some() {
|
||||
@@ -107,14 +127,9 @@ pub fn commit(app: &mut App, xf: Xf) {
|
||||
if samples.is_empty() {
|
||||
return;
|
||||
}
|
||||
let pen = samples.iter().any(|(_, p)| p.is_some());
|
||||
let points: Vec<serde_json::Value> = samples.iter().map(|(v, p)| if pen { json!([v.x, v.y, p.unwrap_or(1.0)]) } else { json!([v.x, v.y]) }).collect();
|
||||
let points = points(&samples);
|
||||
let o = app.brush;
|
||||
let shape = match o.shape {
|
||||
TipShape::Round => "round",
|
||||
TipShape::Square => "square",
|
||||
};
|
||||
let params = json!({"points": points, "size": o.size, "shape": shape, "angle": o.angle, "roundness": o.roundness, "smoothing": o.smoothing, "mode": o.mode.key(), "unit": xf.unit()});
|
||||
let params = json!({"points": points, "size": o.size, "shape": shape_key(o.shape), "angle": o.angle, "roundness": o.roundness, "smoothing": o.smoothing, "mode": o.mode.key(), "unit": xf.unit()});
|
||||
if let Some(v) = app.run("draw.brush", params)
|
||||
&& v["elements"].as_array().is_some_and(Vec::is_empty)
|
||||
{
|
||||
@@ -159,38 +174,50 @@ pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Po
|
||||
if app.tool != Tool::Brush {
|
||||
return;
|
||||
}
|
||||
let o = app.brush;
|
||||
if app.drag == Drag::Brush {
|
||||
// Opaque, so overlapping pieces don't darken each other.
|
||||
let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..app.s.style.fill });
|
||||
draw_sweep(painter, xf, &app.brush, &app.brush_samples, color);
|
||||
}
|
||||
if let Some(h) = hover {
|
||||
// The tip's size and shape at the pointer, as Animate shows it.
|
||||
draw_tip(painter, xf, &app.brush, xf.to_stage(h));
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
return;
|
||||
}
|
||||
let unit = o.unit_outline();
|
||||
let screen = |at: Vec2, pressure: Option<f32>| -> Vec<Pos2> {
|
||||
let m = o.tip_to_stage(at, size_factor(pressure.unwrap_or(1.0)));
|
||||
unit.iter().map(|u| xf.to_screen(m.apply(*u))).collect()
|
||||
};
|
||||
if app.drag == Drag::Brush && !app.brush_samples.is_empty() {
|
||||
// Opaque, so overlapping pieces don't darken each other.
|
||||
let color = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..app.s.style.fill });
|
||||
let step = app.brush_samples.len().div_ceil(MAX_PREVIEW).max(1);
|
||||
let picked: Vec<&(Vec2, Option<f32>)> = app.brush_samples.iter().step_by(step).chain(app.brush_samples.last()).collect();
|
||||
if let [only] = picked.as_slice() {
|
||||
painter.add(egui::Shape::convex_polygon(hull(screen(only.0, only.1)), color, Stroke::NONE));
|
||||
}
|
||||
for pair in picked.windows(2) {
|
||||
let &[a, b] = pair else { continue };
|
||||
let mut pts = screen(a.0, a.1);
|
||||
pts.extend(screen(b.0, b.1));
|
||||
painter.add(egui::Shape::convex_polygon(hull(pts), color, Stroke::NONE));
|
||||
}
|
||||
let step = samples.len().div_ceil(MAX_PREVIEW).max(1);
|
||||
let picked: Vec<&(Vec2, Option<f32>)> = samples.iter().step_by(step).chain(samples.last()).collect();
|
||||
if let [only] = picked.as_slice() {
|
||||
painter.add(egui::Shape::convex_polygon(hull(screen(only.0, only.1)), color, Stroke::NONE));
|
||||
}
|
||||
if let Some(h) = hover {
|
||||
// The tip's size and shape at the pointer, as Animate shows it.
|
||||
let at = xf.to_stage(h);
|
||||
let mut outline = screen(at, None);
|
||||
if let Some(first) = outline.first().copied() {
|
||||
outline.push(first);
|
||||
}
|
||||
painter.add(egui::Shape::line(outline, Stroke::new(1.0, T.selection)));
|
||||
for pair in picked.windows(2) {
|
||||
let &[a, b] = pair else { continue };
|
||||
let mut pts = screen(a.0, a.1);
|
||||
pts.extend(screen(b.0, b.1));
|
||||
painter.add(egui::Shape::convex_polygon(hull(pts), color, Stroke::NONE));
|
||||
}
|
||||
}
|
||||
|
||||
/// The tip's outline at stage point `at`.
|
||||
pub fn draw_tip(painter: &egui::Painter, xf: Xf, o: &BrushOptions, at: Vec2) {
|
||||
let m = o.tip_to_stage(at, 1.0);
|
||||
let mut outline: Vec<Pos2> = o.unit_outline().iter().map(|u| xf.to_screen(m.apply(*u))).collect();
|
||||
if let Some(first) = outline.first().copied() {
|
||||
outline.push(first);
|
||||
}
|
||||
painter.add(egui::Shape::line(outline, Stroke::new(1.0, T.selection)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! The Eraser (E) and the Eyedropper (I), ADR 0034: view state over `draw.erase`, `draw.faucet`
|
||||
//! and `paint.pick`. An eraser drag collects samples like the Brush, shows the stage colour
|
||||
//! where it goes and sends one command when the pointer lifts, so a stroke is one undo step.
|
||||
|
||||
use crate::app::{App, Drag, Tool};
|
||||
use crate::brushtool::{BrushOptions, draw_sweep, draw_tip, points, shape_key};
|
||||
use crate::pathtools::Xf;
|
||||
use crate::theme::to_color32;
|
||||
use anicraft_engine::cmds_erase::EraseMode;
|
||||
use anicraft_engine::doc::ElementKind;
|
||||
use anicraft_engine::geom::Vec2;
|
||||
use anicraft_engine::geom::brush::TipShape;
|
||||
use egui::Pos2;
|
||||
use serde_json::json;
|
||||
|
||||
/// The Eraser's options (view state: the tool's, not the document's).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EraserOptions {
|
||||
/// Diameter (or side), stage units.
|
||||
pub size: f32,
|
||||
pub shape: TipShape,
|
||||
pub mode: EraseMode,
|
||||
/// The Faucet: a click deletes a whole fill or line.
|
||||
pub faucet: bool,
|
||||
}
|
||||
|
||||
impl Default for EraserOptions {
|
||||
fn default() -> Self {
|
||||
EraserOptions { size: 16.0, shape: TipShape::Round, mode: EraseMode::Normal, faucet: false }
|
||||
}
|
||||
}
|
||||
|
||||
impl EraserOptions {
|
||||
/// The tip as the Brush draws it (for the shared previews).
|
||||
fn tip(&self) -> BrushOptions {
|
||||
BrushOptions { size: self.size, shape: self.shape, ..BrushOptions::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts an eraser stroke at stage point `p` (the eraser ignores pen pressure).
|
||||
pub fn start(app: &mut App, p: Vec2) -> Drag {
|
||||
app.pen_pressure = None;
|
||||
app.brush_samples = vec![(p, None)];
|
||||
Drag::Eraser
|
||||
}
|
||||
|
||||
/// Sends the stroke: one command, one undo step.
|
||||
pub fn commit(app: &mut App, xf: Xf) {
|
||||
let samples = std::mem::take(&mut app.brush_samples);
|
||||
if samples.is_empty() {
|
||||
return;
|
||||
}
|
||||
let o = app.eraser;
|
||||
let params = json!({"points": points(&samples), "size": o.size, "shape": shape_key(o.shape), "mode": o.mode.key(), "unit": xf.unit()});
|
||||
let undo = crate::platform::shortcut_label("Ctrl+Z");
|
||||
match app.run("draw.erase", params) {
|
||||
Some(v) if v["erased"] == true => app.status_ok(format!("Erased. {undo} to undo.")),
|
||||
Some(v) => {
|
||||
let why = v["reason"].as_str().unwrap_or("nothing to erase there");
|
||||
app.status_ok(format!("Nothing erased: {why}. The eraser works on lines and fills drawn with Object Drawing off; drawing objects and symbols are kept."));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Faucet: deletes the whole fill or line under the click.
|
||||
pub fn faucet(app: &mut App, p: Vec2, zoom: f32) {
|
||||
if let Some(v) = app.run("draw.faucet", json!({"x": p.x, "y": p.y, "slop": 4.0 / zoom.max(1e-3)})) {
|
||||
let what = if v["kind"] == "line" { "line" } else { "fill" };
|
||||
app.status_ok(format!("Deleted the {what}. {} to undo.", crate::platform::shortcut_label("Ctrl+Z")));
|
||||
}
|
||||
}
|
||||
|
||||
/// Double-clicking the Eraser tool: erase everything on the stage at this frame (asks first).
|
||||
pub fn erase_everything(app: &mut App) {
|
||||
// The engine asks only when there is something to erase.
|
||||
if app.s.confirmation("draw.erase_all", &json!({})).is_none() {
|
||||
app.status_ok("Nothing to erase: the visible, unlocked layers are empty at this frame.");
|
||||
return;
|
||||
}
|
||||
app.request("draw.erase_all", json!({}));
|
||||
}
|
||||
|
||||
/// The stroke as it goes (in the stage colour, as if erased) and the tip under the pointer.
|
||||
pub fn draw_overlay(app: &App, painter: &egui::Painter, xf: Xf, hover: Option<Pos2>) {
|
||||
if app.tool != Tool::Eraser {
|
||||
return;
|
||||
}
|
||||
let tip = app.eraser.tip();
|
||||
if app.drag == Drag::Eraser {
|
||||
let bg = to_color32(anicraft_engine::doc::Rgba { a: 1.0, ..app.s.doc.stage.background });
|
||||
draw_sweep(painter, xf, &tip, &app.brush_samples, bg);
|
||||
}
|
||||
if let Some(h) = hover
|
||||
&& !app.eraser.faucet
|
||||
{
|
||||
draw_tip(painter, xf, &tip, xf.to_stage(h));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eyedropper's click. It picks the fill or line under the point into the tool settings
|
||||
/// (Shift: into the other swatch only). As in Animate, it then becomes the Paint Bucket (a
|
||||
/// fill) or the Ink Bottle (a line), and with shapes selected it gives them the picked style.
|
||||
pub fn eyedropper(app: &mut App, p: Vec2, shift: bool, zoom: f32) {
|
||||
let Some(v) = app.run("paint.pick", json!({"x": p.x, "y": p.y, "other": shift, "slop": 3.0 / zoom.max(1e-3)})) else { return };
|
||||
let color = v["color"].as_str().unwrap_or("").to_string();
|
||||
let into_fill = v["into"] == "fill";
|
||||
if shift {
|
||||
app.status_ok(format!("Picked {color} into the {} colour.", if into_fill { "fill" } else { "stroke" }));
|
||||
return;
|
||||
}
|
||||
let what = match v["paint"].as_str() {
|
||||
Some("linear") => "linear gradient".to_string(),
|
||||
Some("radial") => "radial gradient".to_string(),
|
||||
Some("bitmap") => "bitmap fill".to_string(),
|
||||
_ if into_fill => format!("fill {color}"),
|
||||
_ => format!("line {color}, {} px", v["width"].as_f64().map_or(String::new(), |w| format!("{w:.1}"))),
|
||||
};
|
||||
let sel = &app.s.selection;
|
||||
let shapes = app.s.visible_elements().iter().filter(|e| sel.contains(&e.id) && matches!(e.kind, ElementKind::Shape(_))).count();
|
||||
if shapes > 0 {
|
||||
if let Some(r) = app.run("paint.apply_style", json!({"fill": into_fill, "stroke": !into_fill})) {
|
||||
let n = r["changed"].as_u64().unwrap_or(0);
|
||||
app.status_ok(format!("Applied the picked {what} to {n} {}. {} to undo.", if n == 1 { "shape" } else { "shapes" }, crate::platform::shortcut_label("Ctrl+Z")));
|
||||
}
|
||||
} else {
|
||||
let next = if into_fill { "Click a fill or an enclosed area to pour it" } else { "Click a shape to give it this line" };
|
||||
app.status_ok(format!("Picked the {what}. {next}."));
|
||||
}
|
||||
app.tool = if into_fill { Tool::PaintBucket } else { Tool::InkBottle };
|
||||
}
|
||||
+11
-1
@@ -20,6 +20,8 @@ pub enum Icon {
|
||||
Pen,
|
||||
Pencil,
|
||||
Brush,
|
||||
Eraser,
|
||||
Eyedropper,
|
||||
Rect,
|
||||
Oval,
|
||||
PolyStar,
|
||||
@@ -66,7 +68,7 @@ pub enum Icon {
|
||||
|
||||
impl Icon {
|
||||
#[cfg(test)]
|
||||
pub const ALL: [Icon; 48] = [
|
||||
pub const ALL: [Icon; 50] = [
|
||||
Icon::Camera,
|
||||
Icon::Width,
|
||||
Icon::Sound,
|
||||
@@ -93,6 +95,8 @@ impl Icon {
|
||||
Icon::Pen,
|
||||
Icon::Pencil,
|
||||
Icon::Brush,
|
||||
Icon::Eraser,
|
||||
Icon::Eyedropper,
|
||||
Icon::Rect,
|
||||
Icon::Oval,
|
||||
Icon::PolyStar,
|
||||
@@ -136,6 +140,10 @@ impl Icon {
|
||||
Icon::Pencil => ("pencil", false),
|
||||
// A round brush: handle, ferrule and a painted tip (AniCraft original, on Lucide's grid).
|
||||
Icon::Brush => ("anicraft-brush", false),
|
||||
// A block eraser on its edge, its sleeve marked off (AniCraft original).
|
||||
Icon::Eraser => ("anicraft-eraser", false),
|
||||
// A dropper: bulb, collar, glass tube and a drop (AniCraft original).
|
||||
Icon::Eyedropper => ("anicraft-eyedropper", false),
|
||||
Icon::Rect => ("rectangle-horizontal", false),
|
||||
Icon::Oval => ("circle", false),
|
||||
Icon::PolyStar => ("pentagon", false),
|
||||
@@ -228,6 +236,8 @@ static FILES: &[(&str, &str)] = &[
|
||||
("anicraft-mask", include_str!("../assets/icons/anicraft-mask.svg")),
|
||||
("anicraft-width", include_str!("../assets/icons/anicraft-width.svg")),
|
||||
("anicraft-brush", include_str!("../assets/icons/anicraft-brush.svg")),
|
||||
("anicraft-eraser", include_str!("../assets/icons/anicraft-eraser.svg")),
|
||||
("anicraft-eyedropper", include_str!("../assets/icons/anicraft-eyedropper.svg")),
|
||||
("anicraft-masked", include_str!("../assets/icons/anicraft-masked.svg")),
|
||||
("anicraft-camera", include_str!("../assets/icons/anicraft-camera.svg")),
|
||||
("folder", include_str!("../assets/icons/folder.svg")),
|
||||
|
||||
@@ -51,12 +51,14 @@ pub fn tool_id(t: Tool) -> &'static str {
|
||||
Tool::Text => "tool.text",
|
||||
Tool::Pencil => "tool.pencil",
|
||||
Tool::Brush => "tool.brush",
|
||||
Tool::Eraser => "tool.eraser",
|
||||
Tool::Rect => "tool.rectangle",
|
||||
Tool::Oval => "tool.oval",
|
||||
Tool::Star => "tool.polystar",
|
||||
Tool::Line => "tool.line",
|
||||
Tool::PaintBucket => "tool.paint_bucket",
|
||||
Tool::InkBottle => "tool.ink_bottle",
|
||||
Tool::Eyedropper => "tool.eyedropper",
|
||||
Tool::Camera => "tool.camera",
|
||||
Tool::Hand => "tool.hand",
|
||||
Tool::Zoom => "tool.zoom",
|
||||
@@ -360,6 +362,8 @@ mod tests {
|
||||
assert_eq!(m.keys("edit.delete"), ["Delete", "Backspace"], "aliases are second keys");
|
||||
assert_eq!(m.primary("tool.pen"), Some("P"));
|
||||
assert_eq!(m.primary("tool.brush"), Some("B"));
|
||||
assert_eq!(m.primary("tool.eraser"), Some("E"));
|
||||
assert_eq!(m.primary("tool.eyedropper"), Some("I"));
|
||||
assert_eq!(m.keys("view.brush_smaller"), ["["]);
|
||||
assert_eq!(m.keys("view.brush_larger"), ["]"]);
|
||||
assert_eq!(m.primary("view.onion"), Some("Alt+Shift+O"));
|
||||
|
||||
+2
-1
@@ -17,6 +17,7 @@ mod actions_panel;
|
||||
mod app;
|
||||
mod autosave;
|
||||
mod brushtool;
|
||||
mod erasertool;
|
||||
mod camera_tool;
|
||||
mod dialogs;
|
||||
mod gpu_stage;
|
||||
@@ -136,7 +137,7 @@ fn main() -> eframe::Result {
|
||||
}
|
||||
"--help" | "-h" => {
|
||||
println!(
|
||||
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|brush|brushing|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|testmovie|exporthtml]\n\
|
||||
"anicraft [file.anicraft|file.fla|file.xfl] [--version] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale <percent>] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|merge|brush|brushing|eraser|erasing|eyedropper|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|motionpath|motionpoints|hints|hintsend|camera|cameraview|filters|prefs|licenses|zoom|recovery|plugins|actions|testmovie|exporthtml]\n\
|
||||
--renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\
|
||||
--open shows a panel at start (handy with --screenshot for visual checks)\n\
|
||||
ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer (default gpu, falling back to cpu; ADR 0032)\n\
|
||||
|
||||
+69
-8
@@ -22,12 +22,14 @@ fn tool_icon(tool: Tool) -> Icon {
|
||||
Tool::Text => Icon::Type,
|
||||
Tool::Pencil => Icon::Pencil,
|
||||
Tool::Brush => Icon::Brush,
|
||||
Tool::Eraser => Icon::Eraser,
|
||||
Tool::Rect => Icon::Rect,
|
||||
Tool::Oval => Icon::Oval,
|
||||
Tool::Star => Icon::PolyStar,
|
||||
Tool::Line => Icon::Line,
|
||||
Tool::PaintBucket => Icon::Bucket,
|
||||
Tool::InkBottle => Icon::Ink,
|
||||
Tool::Eyedropper => Icon::Eyedropper,
|
||||
Tool::Camera => Icon::Camera,
|
||||
Tool::Hand => Icon::Hand,
|
||||
Tool::Zoom => Icon::Zoom,
|
||||
@@ -66,10 +68,15 @@ fn tool_column(app: &mut App, ui: &mut egui::Ui, area: Rect) {
|
||||
if active {
|
||||
a11y::anchor(ui, a11y::Region::Tools, area, &resp);
|
||||
}
|
||||
if resp.on_hover_text(format!("{name}\n{}", tool.hint())).clicked() {
|
||||
let resp = resp.on_hover_text(format!("{name}\n{}", tool.hint()));
|
||||
if resp.clicked() {
|
||||
app.tool = tool;
|
||||
}
|
||||
if matches!(tool, Tool::Width | Tool::Brush | Tool::Line | Tool::InkBottle) {
|
||||
// Animate: double-clicking the Eraser erases everything on the stage (it asks first).
|
||||
if tool == Tool::Eraser && resp.double_clicked() {
|
||||
crate::erasertool::erase_everything(app);
|
||||
}
|
||||
if matches!(tool, Tool::Width | Tool::Eraser | Tool::Line | Tool::Eyedropper) {
|
||||
// Tool groups: select, draw by hand, shapes, view.
|
||||
ui.add_space(3.0);
|
||||
let y = ui.cursor().top();
|
||||
@@ -79,7 +86,7 @@ fn tool_column(app: &mut App, ui: &mut egui::Ui, area: Rect) {
|
||||
}
|
||||
ui.add_space(10.0);
|
||||
// fill / stroke swatches
|
||||
let st = app.s.style;
|
||||
let st = &app.s.style;
|
||||
let (r, _) = ui.allocate_exact_size(vec2(TOOL_BUTTON, TOOL_BUTTON), Sense::hover());
|
||||
let back = Rect::from_min_size(r.left_top() + vec2(14.0, 14.0), vec2(24.0, 24.0));
|
||||
let front = Rect::from_min_size(r.left_top() + vec2(2.0, 2.0), vec2(24.0, 24.0));
|
||||
@@ -334,7 +341,7 @@ fn properties(app: &mut App, ui: &mut egui::Ui) {
|
||||
let sel: Vec<_> = elements.iter().filter(|e| app.s.selection.contains(&e.id)).cloned().collect();
|
||||
|
||||
// ---- tool options first while a drawing tool is in hand: they're what you reach for ----
|
||||
if matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Text | Tool::Pencil | Tool::Brush | Tool::PaintBucket | Tool::InkBottle) {
|
||||
if matches!(app.tool, Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Text | Tool::Pencil | Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper) {
|
||||
let title = format!("{} tool", app.tool.label());
|
||||
section(ui, "prop_tool", Section::Rule, &title, None, |ui| tool_props(app, ui));
|
||||
}
|
||||
@@ -1230,6 +1237,10 @@ fn sound_rows(app: &mut App, ui: &mut egui::Ui, current: Option<anicraft_engine:
|
||||
}
|
||||
|
||||
fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
if app.tool == Tool::Eraser {
|
||||
eraser_props(app, ui);
|
||||
return;
|
||||
}
|
||||
if app.tool == Tool::Text {
|
||||
// What new text gets (the last style used, as in Animate).
|
||||
let mut st = app.s.text_style.clone();
|
||||
@@ -1238,7 +1249,7 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut st = app.s.style;
|
||||
let mut st = app.s.style.clone();
|
||||
// Each tool shows only what it uses: the bucket and the brush always fill, the ink bottle
|
||||
// always strokes.
|
||||
let (fills, ink) = (matches!(app.tool, Tool::PaintBucket | Tool::Brush), app.tool == Tool::InkBottle);
|
||||
@@ -1246,7 +1257,18 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
row(ui, "Fill", |ui| {
|
||||
let mut c = rgb(st.fill);
|
||||
if ui.color_edit_button_srgb(&mut c).named("Fill colour").changed() {
|
||||
st.fill = Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0);
|
||||
st.set_fill_color(Rgba::new(c[0] as f32 / 255.0, c[1] as f32 / 255.0, c[2] as f32 / 255.0, 1.0));
|
||||
}
|
||||
// A gradient or bitmap picked with the Eyedropper (ADR 0034): the swatch shows its
|
||||
// first colour, and says what it holds.
|
||||
if let Some(p) = &st.fill_paint {
|
||||
let what = match p {
|
||||
Paint::Linear { .. } => "Linear gradient",
|
||||
Paint::Radial { .. } => "Radial gradient",
|
||||
Paint::Bitmap { .. } => "Bitmap fill",
|
||||
Paint::Solid(_) => "Solid",
|
||||
};
|
||||
ui.label(text(Type::Caption, what)).on_hover_text("Picked with the Eyedropper. It stays where it was on the stage (lock fill). Pick a colour to fill with a solid colour again.");
|
||||
}
|
||||
if !fills {
|
||||
crate::theme::checkbox(ui, &mut st.use_fill, "").named("Fill").on_hover_text("Fill on/off");
|
||||
@@ -1265,9 +1287,9 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
ui.add(egui::DragValue::new(&mut st.stroke_width).suffix(" px").speed(0.1).range(0.0..=100.0).max_decimals(1)).set_name("Stroke width");
|
||||
});
|
||||
// The width profile new strokes get.
|
||||
let current = st.stroke_profile.profile();
|
||||
let current = st.profile();
|
||||
if let Some(pick) = profile_picker(ui, ProfileRow::Tool, current.as_ref()) {
|
||||
st.stroke_profile = pick;
|
||||
st.set_profile(pick);
|
||||
}
|
||||
}
|
||||
// Merge drawing (ADR 0031) or drawing objects, for the tools that draw shapes.
|
||||
@@ -1306,6 +1328,45 @@ fn tool_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eraser's options (ADR 0034): the Faucet, size, shape and erase mode, as in Animate.
|
||||
fn eraser_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
use crate::brushtool::{SIZE_MAX, SIZE_MIN};
|
||||
use anicraft_engine::cmds_erase::EraseMode;
|
||||
use anicraft_engine::geom::brush::TipShape;
|
||||
let keys = [app.keymap.primary("view.brush_smaller"), app.keymap.primary("view.brush_larger")].into_iter().flatten().map(crate::platform::shortcut_label).collect::<Vec<_>>().join(" / ");
|
||||
let o = &mut app.eraser;
|
||||
row_prose(ui, "Faucet", |ui| {
|
||||
crate::theme::checkbox(ui, &mut o.faucet, "Delete whole fills and lines").on_hover_text("On: a click deletes the whole fill or line under it. Off: drag to erase");
|
||||
});
|
||||
ui.add_enabled_ui(!o.faucet, |ui| {
|
||||
row(ui, "Size", |ui| {
|
||||
let r = ui.add(egui::DragValue::new(&mut o.size).suffix(" px").speed(0.25).range(SIZE_MIN..=SIZE_MAX).max_decimals(1)).named("Eraser size");
|
||||
if !keys.is_empty() {
|
||||
r.on_hover_text(format!("Eraser size ({keys})"));
|
||||
}
|
||||
});
|
||||
row(ui, "Shape", |ui| {
|
||||
for (shape, label, hint) in [(TipShape::Round, "Round", "A round eraser"), (TipShape::Square, "Square", "A square eraser")] {
|
||||
ui.selectable_value(&mut o.shape, shape, label).on_hover_text(hint);
|
||||
}
|
||||
});
|
||||
row_prose(ui, "Mode", |ui| {
|
||||
egui::ComboBox::from_id_salt("erase_mode").width(170.0).selected_text(o.mode.label()).show_ui(ui, |ui| {
|
||||
for m in EraseMode::ALL {
|
||||
ui.selectable_value(&mut o.mode, m, m.label()).on_hover_text(m.hint());
|
||||
}
|
||||
})
|
||||
.response
|
||||
.set_name("Erase mode");
|
||||
});
|
||||
});
|
||||
row_prose(ui, "Stage", |ui| {
|
||||
if ui.button("Erase Everything…").on_hover_text("Clears every visible, unlocked layer at this frame, as double-clicking the Eraser tool does. You can undo it").clicked() {
|
||||
crate::erasertool::erase_everything(app);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The Brush tool's options (ADR 0033): what Animate's brush offers in its options.
|
||||
fn brush_props(app: &mut App, ui: &mut egui::Ui) {
|
||||
use crate::brushtool::{SIZE_MAX, SIZE_MIN};
|
||||
|
||||
+18
-3
@@ -310,7 +310,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
None => CursorIcon::Default,
|
||||
}
|
||||
}
|
||||
Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush | Tool::PaintBucket | Tool::InkBottle => CursorIcon::Crosshair,
|
||||
Tool::Rect | Tool::Oval | Tool::Star | Tool::Line | Tool::Pen | Tool::Pencil | Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper => CursorIcon::Crosshair,
|
||||
Tool::Text => CursorIcon::Text,
|
||||
Tool::Zoom => {
|
||||
if alt {
|
||||
@@ -386,7 +386,9 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Drag::Pencil
|
||||
}
|
||||
Tool::Brush => crate::brushtool::start(app, to_v(sp), pressure),
|
||||
Tool::Pen | Tool::Text | Tool::PaintBucket | Tool::InkBottle => Drag::None,
|
||||
// With the Faucet on, the eraser deletes on a click instead.
|
||||
Tool::Eraser if !app.eraser.faucet => crate::erasertool::start(app, to_v(sp)),
|
||||
Tool::Pen | Tool::Text | Tool::PaintBucket | Tool::InkBottle | Tool::Eyedropper | Tool::Eraser => Drag::None,
|
||||
Tool::Rect | Tool::Oval | Tool::Star | Tool::Line => Drag::Shape { start: sp, cur: sp },
|
||||
Tool::Camera => crate::camera_tool::drag_start(app, &cam_geo, press),
|
||||
Tool::Hand => Drag::Pan,
|
||||
@@ -451,6 +453,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
}
|
||||
(Drag::Pencil, Some(c)) => crate::pathtools::pencil_sample(app, to_v(c), xf),
|
||||
(Drag::Brush, Some(c)) => crate::brushtool::sample(app, to_v(c), pressure, xf),
|
||||
(Drag::Eraser, Some(c)) => crate::brushtool::sample(app, to_v(c), None, xf),
|
||||
(Drag::Marquee { cur: m, .. }, Some(c)) => *m = c,
|
||||
(Drag::Shape { start, cur: m }, Some(c)) => *m = constrain(app.tool, *start, c, shift),
|
||||
_ => {}
|
||||
@@ -469,6 +472,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
Drag::PointMarquee { start, cur } => crate::pathtools::marquee_points(app, start, cur, shift),
|
||||
Drag::Pencil => crate::pathtools::commit_pencil(app, xf),
|
||||
Drag::Brush => crate::brushtool::commit(app, xf),
|
||||
Drag::Eraser => crate::erasertool::commit(app, xf),
|
||||
Drag::Marquee { start, cur } => {
|
||||
let r = Rect::from_two_pos(start, cur);
|
||||
let ids: Vec<u64> = app
|
||||
@@ -515,6 +519,16 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
crate::brushtool::start(app, to_v(sp), pressure);
|
||||
crate::brushtool::commit(app, xf);
|
||||
}
|
||||
Tool::Eraser if !panning => {
|
||||
if app.eraser.faucet {
|
||||
crate::erasertool::faucet(app, to_v(sp), zoom);
|
||||
} else {
|
||||
// A click erases a dab.
|
||||
crate::erasertool::start(app, to_v(sp));
|
||||
crate::erasertool::commit(app, xf);
|
||||
}
|
||||
}
|
||||
Tool::Eyedropper if !panning => crate::erasertool::eyedropper(app, to_v(sp), shift, zoom),
|
||||
Tool::InkBottle if !panning => {
|
||||
app.run("paint.ink", json!({"x": sp.x, "y": sp.y, "slop": 4.0 / zoom.max(1e-3)}));
|
||||
}
|
||||
@@ -851,6 +865,7 @@ pub fn show(app: &mut App, ui: &mut egui::Ui) {
|
||||
crate::pathtools::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p)));
|
||||
crate::widthtool::draw_overlay(app, &painter, xf, pointer.filter(|p| canvas.contains(*p)));
|
||||
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.
|
||||
if !preview
|
||||
&& let Some(shown) = crate::motion_path::shown(app)
|
||||
@@ -1178,7 +1193,7 @@ fn create_shape(app: &mut App, start: Pos2, cur: Pos2) {
|
||||
}
|
||||
|
||||
fn draw_preview(app: &App, painter: &egui::Painter, a: Pos2, b: Pos2, zoom: f32) {
|
||||
let st = app.s.style;
|
||||
let st = &app.s.style;
|
||||
let fill = if st.use_fill { crate::theme::to_color32(st.fill).gamma_multiply(0.6) } else { Color32::TRANSPARENT };
|
||||
let stroke = Stroke::new((st.stroke_width * zoom).max(1.0), if st.use_stroke { crate::theme::to_color32(st.stroke) } else { T.selection });
|
||||
match app.tool {
|
||||
|
||||
Reference in new issue
Block a user