mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-28 00:59:30 +01:00
feat(engine): Subselection on raw shapes, Snap to Objects, merging bucket fills, pastes, XFL raw shapes and gradients (M1)
* raw.subselect / raw.subselect_rect / raw.points / raw.move_handle: the connected raw shapes' anchors (once per position) and curve handles; a handle drag changes the edge in every raw shape that has it. * raw.move_point takes 'with': other selected anchors move along. * draw.snap_to_objects (View > Snapping), on by default, gates every 'snap' param. * paint.bucket: raw fills merge (behind), filled exactly up to raw lines and fill edges (a local probe merge); recolouring a raw fill re-merges. * Pasted raw shapes merge where they land (Paste in Place too). * XFL: loose DOMShapes (not isDrawingObject, not in groups) import raw; file.open merges each keyframe's raw shapes (tweened keyframes kept). * Gradient and bitmap fills take part in the merge; width profiles stay objects. Measured (748 raw shapes, debug-opt build): click 0.9 ms, anchor list 0.1 ms, handle frame 0.1 ms, merge on release 0.2 ms, exact bucket fill 0.3 ms (20 ms before the probe was made local). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
1864ad1b85
commit
ae16caf5d9
15 files changed
+1178
-45
No files matched your search
@@ -15,6 +15,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
c("draw.star", "PolyStar", "", None, "{cx, cy, outer, inner?, points?, fill?, stroke?, profile?, object?}", true, draw_star),
|
||||
c("draw.line", "Line", "", None, "{x0, y0, x1, y1, stroke?, stroke_width?, profile? (a width profile name or [[t, left, right], ..]), object? (true: a drawing object; default: Object Drawing, off: it merges with the raw shapes it touches)}", true, draw_line),
|
||||
c("draw.object_drawing", "Object Drawing", "", Some("J"), "{on?: bool} (default: toggle)", false, object_drawing),
|
||||
c("draw.snap_to_objects", "Snap to Objects", "View/Snapping", None, "{on?: bool} (default: toggle) dragged points and selections snap to points, lines and fill edges (the `snap` params of element.translate, raw.move_point and raw.move_handle do nothing while it is off)", false, snap_to_objects),
|
||||
c("edit.select_all", "Select All", "Edit", Some("Ctrl+A"), "{}", false, select_all),
|
||||
c("edit.deselect", "Deselect All", "Edit", Some("Ctrl+Shift+A"), "{}", false, |s, _| {
|
||||
s.selection.clear();
|
||||
@@ -99,7 +100,7 @@ pub(crate) fn add_shape(s: &mut Session, name: &str, local: Path, origin: Vec2,
|
||||
// A gradient or bitmap from the fill swatch is in stage space: 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 merge = !object && crate::merge::can_merge(stroke.as_ref());
|
||||
let id = ElementId(s.doc.alloc_id());
|
||||
let el = Element {
|
||||
id,
|
||||
@@ -165,6 +166,11 @@ fn draw_line(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
add_shape(s, "line", Path::line(a - c, b - c), c, None, stroke, object_param(s, p)?)
|
||||
}
|
||||
|
||||
fn snap_to_objects(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.style.snap_objects = opt_bool(p, "on")?.unwrap_or(!s.style.snap_objects);
|
||||
Ok(json!({"snap_to_objects": s.style.snap_objects}))
|
||||
}
|
||||
|
||||
fn object_drawing(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.style.object_drawing = opt_bool(p, "on")?.unwrap_or(!s.style.object_drawing);
|
||||
Ok(json!({"object_drawing": s.style.object_drawing}))
|
||||
@@ -228,7 +234,7 @@ fn pick(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn translate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (mut dx, mut dy) = (f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let snap = opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0);
|
||||
let snap = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0));
|
||||
let from = match p.get("from").filter(|v| !v.is_null()) {
|
||||
None => None,
|
||||
Some(v) => {
|
||||
|
||||
@@ -168,7 +168,10 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
} else {
|
||||
anicraft_xfl::import_path(&path)
|
||||
};
|
||||
let (doc, report) = imported.map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?;
|
||||
let (mut doc, report) = imported.map_err(|e| EngineError::Format(format!("{}: {e}", path.display())))?;
|
||||
// Raw artwork arrives one shape per style: each keyframe's becomes one merged drawing,
|
||||
// as it was in Animate (ADR 0042).
|
||||
let merged = crate::merge::merge_document(&mut doc);
|
||||
s.replace_document(doc, None);
|
||||
let mut info = s.info();
|
||||
info["imported"] = json!(path.display().to_string());
|
||||
@@ -176,6 +179,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
info["skipped"] = json!(report.skipped);
|
||||
info["kept"] = json!(report.kept);
|
||||
info["missing_fonts"] = json!(report.missing_fonts);
|
||||
info["merged_keyframes"] = json!(merged);
|
||||
return Ok(info);
|
||||
}
|
||||
let doc = format::load(&path)?;
|
||||
|
||||
@@ -116,20 +116,31 @@ fn paste_with(s: &mut Session, offset: Vec2) -> Result<Value> {
|
||||
import_symbols(s, &s.clipboard.symbols.clone());
|
||||
let mut fresh = Vec::new();
|
||||
let mut out = Vec::new();
|
||||
let mut raw = Vec::new();
|
||||
for e in s.clipboard.elements.clone() {
|
||||
let mut e = e;
|
||||
e.id = ElementId(s.doc.alloc_id());
|
||||
e.transform = Affine::translate(offset.x, offset.y).mul(&e.transform);
|
||||
fresh.push(e.id);
|
||||
out.push(Arc::new(e));
|
||||
// Raw shapes go into the drawing where they land, cutting and joining what they touch
|
||||
// (ADR 0042); objects go on top.
|
||||
if crate::merge::mergeable(&e).is_some() {
|
||||
raw.push(e);
|
||||
} else {
|
||||
fresh.push(e.id);
|
||||
out.push(Arc::new(e));
|
||||
}
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() + out.len() > 100_000 {
|
||||
if kf.elements.len() + out.len() + raw.len() > 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
}
|
||||
kf.elements.extend(out);
|
||||
let merged = !raw.is_empty();
|
||||
if merged {
|
||||
fresh.extend(crate::merge::merge_in(s, raw)?);
|
||||
}
|
||||
s.selection = fresh.clone();
|
||||
Ok(json!({"pasted": fresh.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
Ok(json!({"pasted": fresh.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": merged}))
|
||||
}
|
||||
|
||||
/// Adds the symbols this document lacks (from a clipboard, maybe another document's) and
|
||||
|
||||
@@ -30,7 +30,15 @@ use std::sync::Arc;
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
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.bucket",
|
||||
"Paint Bucket",
|
||||
"",
|
||||
None,
|
||||
"{x, y, color?, gap? (stage units: how wide an opening still counts as closed), object?: bool} fills the closed area under the point, or recolours the fill there; unless `object` (default: the Object Drawing setting), the fill is raw and merges with the drawing (an area closed by raw lines and fills is filled exactly up to them)",
|
||||
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),
|
||||
@@ -76,16 +84,26 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !(0.0..=1000.0).contains(&gap) {
|
||||
return Err(EngineError::Param("param 'gap' must be between 0 and 1000".into()));
|
||||
}
|
||||
let object = crate::cmds_draw::object_param(s, p)?;
|
||||
let items = layer_items(s);
|
||||
// 1. On a fill: recolour it.
|
||||
// 1. On a fill: recolour it. A raw fill then joins the fills of its new colour it touches.
|
||||
if let Some((id, true)) = pick(&items, at, 0.0) {
|
||||
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));
|
||||
let sh = element_shape_mut(s, id)?;
|
||||
sh.fill = Some(paint.transformed(&to_local));
|
||||
if sh.merge {
|
||||
crate::cmds_raw::remerge_in_place(s, &[id])?;
|
||||
return Ok(json!({"recolored": id.0, "merged": true}));
|
||||
}
|
||||
return Ok(json!({"recolored": id.0}));
|
||||
}
|
||||
// 2. Find the enclosed area.
|
||||
let Some(path) = enclosed_region(&items, at, gap)? else {
|
||||
return Err(EngineError::State("this area isn't closed. Close the outline, or choose a larger gap size".into()));
|
||||
// 2. Find the enclosed area: exactly, when raw lines and fills close it off (ADR 0042),
|
||||
// else from the rasterized layer.
|
||||
let exact = if object { None } else { crate::merge::enclosed_area(&s.visible_elements(), at) };
|
||||
let was_exact = exact.is_some();
|
||||
let path = match exact {
|
||||
Some(p) => p,
|
||||
None => enclosed_region(&items, at, gap)?.ok_or_else(|| EngineError::State("this area isn't closed. Close the outline, or choose a larger gap size".into()))?,
|
||||
};
|
||||
let c = path.bounds().center();
|
||||
let local = path.transformed(&Affine::translate(-c.x, -c.y));
|
||||
@@ -95,8 +113,15 @@ 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.transformed(&Affine::translate(-c.x, -c.y))), 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: !object }),
|
||||
};
|
||||
if !object {
|
||||
// Raw: behind the drawing, so it takes only what is empty and joins the fills of its
|
||||
// colour it meets; the lines that bound it stay on top.
|
||||
let ids = crate::merge::merge_in_order(s, vec![el], crate::merge::Order::Behind)?;
|
||||
s.selection.clear();
|
||||
return Ok(json!({"element": ids.first().map(|e| e.0), "elements": ids.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": true, "exact": was_exact}));
|
||||
}
|
||||
let kf = s.editable_keyframe()?;
|
||||
if kf.elements.len() >= 100_000 {
|
||||
return Err(EngineError::State("too many elements on this keyframe".into()));
|
||||
|
||||
@@ -37,7 +37,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move Point",
|
||||
"",
|
||||
None,
|
||||
"{x, y, to_x, to_y, points?: [[id, cmd], ..], snap?, slop?, merge?: bool} moves the corner or end at (x, y), with every raw shape that shares it, to (to_x, to_y), snapped within `snap` to points, lines and fill edges; returns the points to pass on while a drag goes on",
|
||||
"{x, y, to_x, to_y, with?: [[x, y], ..], points?: [[id, cmd], ..], snap?, slop?, merge?: bool} moves the corner or end at (x, y), with every raw shape that shares it, to (to_x, to_y), snapped within `snap` to points, lines and fill edges (while Snap to Objects is on); the anchors at `with` move by as much; returns the points to pass on while a drag goes on",
|
||||
true,
|
||||
move_point,
|
||||
),
|
||||
@@ -172,7 +172,7 @@ fn activate_layer_at(s: &mut Session, at: Vec2, slop: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_extent(path: &Path) -> Result<()> {
|
||||
pub(crate) fn check_extent(path: &Path) -> Result<()> {
|
||||
let b = path.bounds();
|
||||
if b.is_empty() {
|
||||
return Ok(());
|
||||
@@ -217,9 +217,19 @@ fn bend_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let old = rawgeom::segment_cubic(&path, cmd).map(|c| rawgeom::transform(&c, &m)).ok_or_else(|| EngineError::Param(format!("no segment {cmd} on this shape")))?;
|
||||
let new = rawgeom::bend(&old, t, d).ok_or_else(|| EngineError::Param("cannot bend that segment".into()))?;
|
||||
let raw = mergeable(el).is_some();
|
||||
// Every raw shape's copy of the edge bends alike (a fill and its outline, two fills that
|
||||
// meet there); an object only bends itself.
|
||||
let area = new.iter().chain(&old).fold(Rect::EMPTY, |mut r, q| {
|
||||
let changed = edit_edge(s, id, cmd, &old, &new, raw)?;
|
||||
let point = cubic_point(&new, t.clamp(0.02, 0.98));
|
||||
if raw && merge_after {
|
||||
remerge_in_place(s, &changed)?;
|
||||
}
|
||||
Ok(json!({"id": id.0, "cmd": cmd, "t": t, "x": point.x, "y": point.y, "changed": changed.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": raw && merge_after}))
|
||||
}
|
||||
|
||||
/// Replaces segment `cmd` of shape `id` (stage space: `old`) with `new` (same ends). When `raw`,
|
||||
/// every raw shape's copy of the edge changes alike (a fill and its outline, two fills that
|
||||
/// meet there); an object only changes itself. Returns the shapes that changed.
|
||||
pub(crate) fn edit_edge(s: &mut Session, id: ElementId, cmd: usize, old: &Cubic, new: &Cubic, raw: bool) -> Result<Vec<ElementId>> {
|
||||
let area = new.iter().chain(old).fold(Rect::EMPTY, |mut r, q| {
|
||||
r.include(*q);
|
||||
r
|
||||
});
|
||||
@@ -231,7 +241,7 @@ fn bend_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let (Some(inv), ElementKind::Shape(x)) = (e.transform.inverse(), &e.kind) else { continue };
|
||||
let (ol, nl) = (rawgeom::transform(&old, &inv), rawgeom::transform(&new, &inv));
|
||||
let (ol, nl) = (rawgeom::transform(old, &inv), rawgeom::transform(new, &inv));
|
||||
let mut edited = (*x.path).clone();
|
||||
let n = if target {
|
||||
edited.close_explicitly();
|
||||
@@ -255,11 +265,7 @@ fn bend_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
changed.push(e.id);
|
||||
}
|
||||
let point = cubic_point(&new, t.clamp(0.02, 0.98));
|
||||
if raw && merge_after {
|
||||
remerge_in_place(s, &changed)?;
|
||||
}
|
||||
Ok(json!({"id": id.0, "cmd": cmd, "t": t, "x": point.x, "y": point.y, "changed": changed.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": raw && merge_after}))
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
// ----- moving shared points ---------------------------------------------------------------------
|
||||
@@ -284,6 +290,23 @@ fn points_param(p: &Value) -> Result<Option<Vec<(ElementId, usize)>>> {
|
||||
Ok(Some(out))
|
||||
}
|
||||
|
||||
/// A list of `[x, y]` stage positions (empty when absent).
|
||||
pub(crate) fn positions_param(p: &Value, key: &str) -> Result<Vec<Vec2>> {
|
||||
let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(Vec::new()) };
|
||||
let bad = || EngineError::Param(format!("param '{key}' must be a list of [x, y] pairs"));
|
||||
let list = v.as_array().ok_or_else(bad)?;
|
||||
if list.len() > MAX_POINTS {
|
||||
return Err(EngineError::Param(format!("param '{key}' has more than {MAX_POINTS} points")));
|
||||
}
|
||||
list.iter()
|
||||
.map(|xy| {
|
||||
let xy = xy.as_array().filter(|a| a.len() == 2).ok_or_else(bad)?;
|
||||
let n = |i: usize| xy.get(i).and_then(Value::as_f64).map(|f| f as f32).filter(|f| f.is_finite()).ok_or_else(bad);
|
||||
Ok(Vec2::new(n(0)?, n(1)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every raw shape's anchor at `at` (within [`SNAP`]) on the editable keyframe; shapes whose edge
|
||||
/// passes there get an anchor there first.
|
||||
fn shared_points(s: &mut Session, at: Vec2) -> Result<Vec<(ElementId, usize)>> {
|
||||
@@ -314,7 +337,7 @@ fn shared_points(s: &mut Session, at: Vec2) -> Result<Vec<(ElementId, usize)>> {
|
||||
fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let from = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let to = Vec2::new(f32_req(p, "to_x")?, f32_req(p, "to_y")?);
|
||||
let radius = opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0);
|
||||
let radius = s.style.snap_radius(opt_f32(p, "snap")?.unwrap_or(0.0).clamp(0.0, 1000.0));
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let merge_after = opt_bool(p, "merge")?.unwrap_or(true);
|
||||
let points = match points_param(p)? {
|
||||
@@ -325,7 +348,19 @@ fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let els = s.visible_elements();
|
||||
let at = els.iter().flat_map(|e| stage_anchors(e)).map(|(_, q)| q).filter(|q| q.distance(from) <= slop).min_by(|a, b| a.distance(from).total_cmp(&b.distance(from)));
|
||||
let at = at.ok_or_else(|| EngineError::State("no corner or end of a raw shape there".into()))?;
|
||||
shared_points(s, at)?
|
||||
let mut points = shared_points(s, at)?;
|
||||
// Other selected anchors (the Subselection tool) move by as much.
|
||||
for w in positions_param(p, "with")? {
|
||||
for pt in shared_points(s, w)? {
|
||||
if !points.contains(&pt) {
|
||||
points.push(pt);
|
||||
}
|
||||
}
|
||||
if points.len() > MAX_POINTS {
|
||||
return Err(EngineError::State("too many points to move at once".into()));
|
||||
}
|
||||
}
|
||||
points
|
||||
}
|
||||
};
|
||||
let els = s.visible_elements();
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
//! The Subselection tool on raw shapes (ADR 0042; issue #42 §3).
|
||||
//!
|
||||
//! Clicking a raw stroke or fill shows the anchors of every raw shape **connected** to it: the
|
||||
//! strokes and fills that meet it at a point or along an edge, and the ones those meet, and so
|
||||
//! on. A layer's merged drawing stores a shared corner once in each shape that has it (ADR 0031),
|
||||
//! so the anchors are listed once per position. Moving one moves every shape that shares it
|
||||
//! (`raw.move_point`); dragging a handle changes the curve in every shape that has that edge
|
||||
//! (`raw.move_handle`).
|
||||
//!
|
||||
//! Which anchors are selected is view state, kept by the editor (as for drawing objects): the
|
||||
//! commands here report anchors and handles by stage position, and take positions back.
|
||||
|
||||
use crate::cmds_raw::{check_extent, edit_edge, remerge_in_place};
|
||||
use crate::merge::mergeable;
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, EngineError, Result, Session};
|
||||
use anicraft_doc::{Element, ElementId, ElementKind};
|
||||
use anicraft_geom::planar::SNAP;
|
||||
use anicraft_geom::raw::{self as rawgeom, Cubic};
|
||||
use anicraft_geom::{Path, PathCmd, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run };
|
||||
vec![
|
||||
c(
|
||||
"raw.subselect",
|
||||
"Subselect",
|
||||
"",
|
||||
None,
|
||||
"{x, y, add?: bool, slop?} the Subselection tool's click: the raw stroke or fill at (x, y) and every raw shape connected to it are selected, to show their anchors (an object there is selected alone); returns the anchors and, on an edge, its ends",
|
||||
false,
|
||||
subselect as crate::RunFn,
|
||||
),
|
||||
c(
|
||||
"raw.subselect_rect",
|
||||
"Subselect Rectangle",
|
||||
"",
|
||||
None,
|
||||
"{x0, y0, x1, y1, add?: bool} the Subselection tool's marquee, on the active layer only: the shapes it touches are selected whole (raw ones with every raw shape connected to them); returns the raw anchors inside it",
|
||||
false,
|
||||
subselect_rect,
|
||||
),
|
||||
c("raw.points", "Raw Points", "", None, "{ids?: [..]} the anchors of raw shapes (default: the selection), once per position, and the handles of their curved segments", false, points_cmd),
|
||||
c(
|
||||
"raw.move_handle",
|
||||
"Move Handle",
|
||||
"",
|
||||
None,
|
||||
"{id, cmd, slot: 1|2, dx, dy, merge?: bool} moves a handle (control point `slot` of segment `cmd` of shape `id`, as `raw.points` lists it) by (dx, dy): the curve changes in every raw shape that has that edge, and they merge again (unless merge is false)",
|
||||
true,
|
||||
move_handle,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most raw shapes one connected set takes in (keeps a click's cost bounded).
|
||||
const MAX_SHAPES: usize = 20_000;
|
||||
/// Most anchors listed.
|
||||
const MAX_ANCHORS: usize = 50_000;
|
||||
/// Raw shapes are connected where a point of one lies this near the other.
|
||||
const TOUCH: f32 = 2.0 * SNAP;
|
||||
/// Flattening tolerance for the connection test.
|
||||
const FLAT: f32 = 0.05;
|
||||
|
||||
// ----- connected raw shapes ----------------------------------------------------------------------
|
||||
|
||||
/// A raw shape's stage-space geometry for the connection test.
|
||||
struct Geo {
|
||||
id: ElementId,
|
||||
bounds: Rect,
|
||||
anchors: Vec<Vec2>,
|
||||
lines: Vec<(Vec2, Vec2)>,
|
||||
}
|
||||
|
||||
fn geo(e: &Element) -> Option<Geo> {
|
||||
let sh = mergeable(e)?;
|
||||
let m = e.transform;
|
||||
let anchors = sh.path.editable_anchors().into_iter().map(|(_, p)| m.apply(p)).collect();
|
||||
let mut lines = Vec::new();
|
||||
for pl in sh.path.flatten(&m, FLAT) {
|
||||
lines.extend(pl.points.windows(2).filter_map(|w| Some((*w.first()?, *w.get(1)?))));
|
||||
if pl.closed
|
||||
&& let (Some(a), Some(b)) = (pl.points.last(), pl.points.first())
|
||||
{
|
||||
lines.push((*a, *b));
|
||||
}
|
||||
}
|
||||
Some(Geo { id: e.id, bounds: sh.path.bounds().transformed(&m).inflate(TOUCH), anchors, lines })
|
||||
}
|
||||
|
||||
/// Whether a point of `a` lies on `b`, within [`TOUCH`].
|
||||
fn lands_on(a: &Geo, b: &Geo) -> bool {
|
||||
a.anchors.iter().filter(|p| b.bounds.contains(**p)).any(|p| b.lines.iter().any(|(u, v)| anicraft_geom::segment_distance(*p, *u, *v) <= TOUCH))
|
||||
}
|
||||
|
||||
fn touch(a: &Geo, b: &Geo) -> bool {
|
||||
!a.bounds.intersect(&b.bounds).is_empty() && (lands_on(a, b) || lands_on(b, a))
|
||||
}
|
||||
|
||||
/// A grid over the shapes' bounds, so each shape is only tested against its neighbours.
|
||||
struct Grid {
|
||||
cell: f32,
|
||||
cells: HashMap<(i64, i64), Vec<usize>>,
|
||||
/// Shapes too large for the grid: tested against everything.
|
||||
big: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Most cells one shape is put in before it counts as big.
|
||||
const MAX_CELLS: i64 = 256;
|
||||
|
||||
impl Grid {
|
||||
fn new(geos: &[Geo]) -> Grid {
|
||||
let sum: f32 = geos.iter().map(|g| g.bounds.width().max(g.bounds.height())).sum();
|
||||
let cell = (sum / geos.len().max(1) as f32).clamp(1.0, 1.0e6);
|
||||
let mut grid = Grid { cell, cells: HashMap::new(), big: Vec::new() };
|
||||
for (i, g) in geos.iter().enumerate() {
|
||||
match grid.span(&g.bounds) {
|
||||
Some(cells) => {
|
||||
for k in cells {
|
||||
grid.cells.entry(k).or_default().push(i);
|
||||
}
|
||||
}
|
||||
None => grid.big.push(i),
|
||||
}
|
||||
}
|
||||
grid
|
||||
}
|
||||
|
||||
/// The cells `r` covers, unless that is too many.
|
||||
fn span(&self, r: &Rect) -> Option<Vec<(i64, i64)>> {
|
||||
let k = |v: f32| (v / self.cell).floor() as i64;
|
||||
let (x0, y0, x1, y1) = (k(r.min.x), k(r.min.y), k(r.max.x), k(r.max.y));
|
||||
if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_CELLS {
|
||||
return None;
|
||||
}
|
||||
Some((x0..=x1).flat_map(|x| (y0..=y1).map(move |y| (x, y))).collect())
|
||||
}
|
||||
|
||||
/// The shapes that may touch `r` (every shape when `r` is too large).
|
||||
fn near(&self, r: &Rect, n: usize) -> Vec<usize> {
|
||||
let mut out: Vec<usize> = match self.span(r) {
|
||||
Some(cells) => cells.iter().filter_map(|k| self.cells.get(k)).flatten().copied().chain(self.big.iter().copied()).collect(),
|
||||
None => (0..n).collect(),
|
||||
};
|
||||
out.sort_unstable();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw shapes among `els` connected to the `seeds` (themselves included): sharing a point
|
||||
/// or an edge, directly or through others. Objects among the seeds are left out.
|
||||
pub fn connected(els: &[Arc<Element>], seeds: &[ElementId]) -> Vec<ElementId> {
|
||||
let geos: Vec<Geo> = els.iter().filter_map(|e| geo(e)).take(MAX_SHAPES).collect();
|
||||
let grid = Grid::new(&geos);
|
||||
let mut seen = vec![false; geos.len()];
|
||||
let mut todo: Vec<usize> = geos.iter().enumerate().filter(|(_, g)| seeds.contains(&g.id)).map(|(i, _)| i).collect();
|
||||
for &i in &todo {
|
||||
if let Some(s) = seen.get_mut(i) {
|
||||
*s = true;
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
while let Some(i) = todo.pop() {
|
||||
let Some(g) = geos.get(i) else { continue };
|
||||
out.push(g.id);
|
||||
for j in grid.near(&g.bounds, geos.len()) {
|
||||
if seen.get(j).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
if geos.get(j).is_some_and(|h| touch(g, h)) {
|
||||
if let Some(s) = seen.get_mut(j) {
|
||||
*s = true;
|
||||
}
|
||||
todo.push(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
// In stacking order, as the layer has them.
|
||||
els.iter().map(|e| e.id).filter(|id| out.contains(id)).collect()
|
||||
}
|
||||
|
||||
// ----- anchors and handles -----------------------------------------------------------------------
|
||||
|
||||
/// A handle of a curved segment, as the Subselection tool shows it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Handle {
|
||||
/// Where the handle is, and the anchor its direction line starts from (stage space).
|
||||
pub at: Vec2,
|
||||
pub anchor: Vec2,
|
||||
/// The shape, segment and control point (1: the segment's first, 2: its second) that
|
||||
/// `raw.move_handle` takes.
|
||||
pub id: ElementId,
|
||||
pub cmd: usize,
|
||||
pub slot: u8,
|
||||
}
|
||||
|
||||
/// The anchors and handles of a set of raw shapes.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct RawPoints {
|
||||
/// Every anchor once (shapes share corners), in stage space.
|
||||
pub anchors: Vec<Vec2>,
|
||||
/// The handles of curved segments, once per position.
|
||||
pub handles: Vec<Handle>,
|
||||
}
|
||||
|
||||
/// Positions seen so far, within [`SNAP`] of each other counting as one.
|
||||
#[derive(Default)]
|
||||
struct Seen(HashMap<(i64, i64), Vec<Vec2>>);
|
||||
|
||||
impl Seen {
|
||||
fn key(p: Vec2) -> (i64, i64) {
|
||||
((p.x / SNAP).floor() as i64, (p.y / SNAP).floor() as i64)
|
||||
}
|
||||
/// Whether `p` is new (and remembers it).
|
||||
fn insert(&mut self, p: Vec2) -> bool {
|
||||
let (kx, ky) = Seen::key(p);
|
||||
let near = (-1..=1).any(|dx| (-1..=1).any(|dy| self.0.get(&(kx + dx, ky + dy)).is_some_and(|v| v.iter().any(|q| q.distance(p) <= SNAP))));
|
||||
if !near {
|
||||
self.0.entry((kx, ky)).or_default().push(p);
|
||||
}
|
||||
!near
|
||||
}
|
||||
}
|
||||
|
||||
/// The path as the raw commands address it (a closed subpath's last side written out).
|
||||
fn explicit(path: &Path) -> Path {
|
||||
let mut p = path.clone();
|
||||
p.close_explicitly();
|
||||
p
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The raw shapes on the active layer connected to `ids` (themselves included).
|
||||
pub fn raw_connected(&self, ids: &[ElementId]) -> Vec<ElementId> {
|
||||
connected(&self.visible_elements(), ids)
|
||||
}
|
||||
|
||||
/// The anchors (once per position) and curve handles of the raw shapes `ids` on the active
|
||||
/// layer.
|
||||
pub fn raw_points(&self, ids: &[ElementId]) -> RawPoints {
|
||||
let mut out = RawPoints::default();
|
||||
let (mut anchors, mut handles) = (Seen::default(), HashMap::<((i64, i64), (i64, i64)), Vec<(Vec2, Vec2)>>::new());
|
||||
for e in self.visible_elements().iter().filter(|e| ids.contains(&e.id)) {
|
||||
let Some(sh) = mergeable(e) else { continue };
|
||||
let m = e.transform;
|
||||
let path = explicit(&sh.path);
|
||||
for (_, q) in path.editable_anchors() {
|
||||
let q = m.apply(q);
|
||||
if out.anchors.len() < MAX_ANCHORS && anchors.insert(q) {
|
||||
out.anchors.push(q);
|
||||
}
|
||||
}
|
||||
for k in 0..path.cmds.len().min(MAX_ANCHORS) {
|
||||
if !matches!(path.cmds.get(k), Some(PathCmd::CubicTo(..) | PathCmd::QuadTo(..))) {
|
||||
continue;
|
||||
}
|
||||
let Some(c) = rawgeom::segment_cubic(&path, k).map(|c| rawgeom::transform(&c, &m)) else { continue };
|
||||
for (slot, at, anchor) in [(1u8, c[1], c[0]), (2u8, c[2], c[3])] {
|
||||
// A handle on its anchor has no direction to show.
|
||||
if at.distance(anchor) <= SNAP || out.handles.len() >= MAX_ANCHORS {
|
||||
continue;
|
||||
}
|
||||
// One edge shared by two shapes has its handles in both: show them once.
|
||||
let key = (Seen::key(anchor), Seen::key(at));
|
||||
let list = handles.entry(key).or_default();
|
||||
if list.iter().any(|(a, h)| a.distance(anchor) <= SNAP && h.distance(at) <= SNAP) {
|
||||
continue;
|
||||
}
|
||||
list.push((anchor, at));
|
||||
out.handles.push(Handle { at, anchor, id: e.id, cmd: k, slot });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn points_json(pts: &RawPoints) -> Value {
|
||||
json!({
|
||||
"anchors": pts.anchors.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(),
|
||||
"handles": pts.handles.iter().map(|h| json!({"x": h.at.x, "y": h.at.y, "ax": h.anchor.x, "ay": h.anchor.y, "id": h.id.0, "cmd": h.cmd, "slot": h.slot})).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
fn points_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids: Vec<ElementId> = match opt_u64_list(p, "ids")? {
|
||||
Some(v) => v.into_iter().map(ElementId).collect(),
|
||||
None => s.selection.clone(),
|
||||
};
|
||||
Ok(points_json(&s.raw_points(&ids)))
|
||||
}
|
||||
|
||||
// ----- clicking and the marquee ------------------------------------------------------------------
|
||||
|
||||
fn subselect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let at = Vec2::new(f32_req(p, "x")?, f32_req(p, "y")?);
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
let slop = opt_f32(p, "slop")?.unwrap_or(2.0).clamp(0.0, 100.0);
|
||||
let Some((layer, hit)) = s.hit_test(at, slop) else {
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
return Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>(), "raw": false, "ends": []}));
|
||||
};
|
||||
if layer != s.layer {
|
||||
s.layer = layer;
|
||||
s.selection.clear();
|
||||
}
|
||||
let els = s.visible_elements();
|
||||
let el = els.iter().find(|e| e.id == hit);
|
||||
let raw = el.is_some_and(|e| mergeable(e).is_some());
|
||||
let picked = if raw { connected(&els, &[hit]) } else { vec![hit] };
|
||||
// On an edge (not inside a fill): its ends, whose handles show.
|
||||
let mut ends = Vec::new();
|
||||
if let Some(e) = el.filter(|_| raw)
|
||||
&& let Some(sh) = mergeable(e)
|
||||
{
|
||||
let path = explicit(&sh.path);
|
||||
if let Some((cmd, _, d)) = path.nearest_segment(at, &e.transform)
|
||||
&& d <= slop + sh.stroke.as_ref().map_or(0.0, |st| st.width * 0.5 * e.transform.mean_scale())
|
||||
&& let Some(c) = rawgeom::segment_cubic(&path, cmd)
|
||||
{
|
||||
ends = vec![e.transform.apply(c[0]), e.transform.apply(c[3])];
|
||||
}
|
||||
}
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
for id in picked {
|
||||
if !s.selection.contains(&id) {
|
||||
s.selection.push(id);
|
||||
}
|
||||
}
|
||||
let mut v = if raw { points_json(&s.raw_points(&s.selection.clone())) } else { json!({}) };
|
||||
v["selected"] = json!(s.selection.iter().map(|e| e.0).collect::<Vec<_>>());
|
||||
v["raw"] = json!(raw);
|
||||
v["ends"] = json!(ends.iter().map(|q| [q.x, q.y]).collect::<Vec<_>>());
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Whether the shape `e` (stage space) has a part in `r`: a point, a line through it, or a fill
|
||||
/// around it. Anything else counts by its bounds.
|
||||
fn touches_rect(e: &Element, r: &Rect, bounds: &Rect) -> bool {
|
||||
if bounds.intersect(r).is_empty() {
|
||||
return false;
|
||||
}
|
||||
let ElementKind::Shape(sh) = &e.kind else { return true };
|
||||
let m = e.transform;
|
||||
let crosses = |a: Vec2, b: Vec2| {
|
||||
if r.contains(a) || r.contains(b) {
|
||||
return true;
|
||||
}
|
||||
let (p, q, u, v) = (r.min, Vec2::new(r.max.x, r.min.y), r.max, Vec2::new(r.min.x, r.max.y));
|
||||
[(p, q), (q, u), (u, v), (v, p)].into_iter().any(|(c, d)| segments_cross(a, b, c, d))
|
||||
};
|
||||
for pl in sh.path.flatten(&m, 0.25) {
|
||||
if pl.points.windows(2).any(|w| matches!(w, [a, b] if crosses(*a, *b))) || pl.points.first().is_some_and(|p| r.contains(*p)) {
|
||||
return true;
|
||||
}
|
||||
if pl.closed && matches!((pl.points.last(), pl.points.first()), (Some(a), Some(b)) if crosses(*a, *b)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
sh.fill.is_some() && sh.path.contains(r.center(), &m, sh.fill_rule)
|
||||
}
|
||||
|
||||
fn segments_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> bool {
|
||||
let side = |p: Vec2, q: Vec2, x: Vec2| (q - p).cross(x - p);
|
||||
let (d1, d2, d3, d4) = (side(c, d, a), side(c, d, b), side(a, b, c), side(a, b, d));
|
||||
(d1 * d2 <= 0.0) && (d3 * d4 <= 0.0)
|
||||
}
|
||||
|
||||
fn subselect_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let a = Vec2::new(f32_req(p, "x0")?, f32_req(p, "y0")?);
|
||||
let b = Vec2::new(f32_req(p, "x1")?, f32_req(p, "y1")?);
|
||||
let add = opt_bool(p, "add")?.unwrap_or(false);
|
||||
let r = Rect::from_points(a, b);
|
||||
if !add {
|
||||
s.selection.clear();
|
||||
}
|
||||
let usable = s.active_layer().is_some_and(|l| l.visible && !l.locked) && !s.doc.timeline(s.scene).locked_by_folder(s.layer);
|
||||
let empty = json!({"selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>(), "anchors": []});
|
||||
if !usable || !(r.width() > 0.0 || r.height() > 0.0) {
|
||||
return Ok(empty);
|
||||
}
|
||||
let els = s.visible_elements();
|
||||
let (mut seeds, mut objects) = (Vec::new(), Vec::new());
|
||||
for e in &els {
|
||||
if !touches_rect(e, &r, &s.element_bounds(e.id)) {
|
||||
continue;
|
||||
}
|
||||
if mergeable(e).is_some() { seeds.push(e.id) } else { objects.push(e.id) }
|
||||
}
|
||||
let raw = connected(&els, &seeds);
|
||||
for id in raw.iter().chain(&objects) {
|
||||
if !s.selection.contains(id) {
|
||||
s.selection.push(*id);
|
||||
}
|
||||
}
|
||||
let inside: Vec<[f32; 2]> = s.raw_points(&raw).anchors.into_iter().filter(|q| r.contains(*q)).map(|q| [q.x, q.y]).collect();
|
||||
Ok(json!({"selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>(), "anchors": inside}))
|
||||
}
|
||||
|
||||
// ----- handles -----------------------------------------------------------------------------------
|
||||
|
||||
fn move_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = ElementId(opt_u64(p, "id")?.ok_or_else(|| EngineError::Param("param 'id' is required".into()))?);
|
||||
let cmd = opt_u64(p, "cmd")?.ok_or_else(|| EngineError::Param("param 'cmd' is required".into()))?;
|
||||
let cmd = usize::try_from(cmd).unwrap_or(usize::MAX);
|
||||
let slot = opt_u64(p, "slot")?.filter(|k| matches!(k, 1 | 2)).ok_or_else(|| EngineError::Param("param 'slot' must be 1 or 2".into()))? as usize;
|
||||
let d = Vec2::new(f32_req(p, "dx")?, f32_req(p, "dy")?);
|
||||
let merge_after = opt_bool(p, "merge")?.unwrap_or(true);
|
||||
let els = s.visible_elements();
|
||||
let el = els.iter().find(|e| e.id == id).ok_or_else(|| EngineError::State(format!("element {} is not on the active layer at this frame", id.0)))?;
|
||||
let ElementKind::Shape(sh) = &el.kind else { return Err(EngineError::State("only shapes have handles".into())) };
|
||||
let path = explicit(&sh.path);
|
||||
if !matches!(path.cmds.get(cmd), Some(PathCmd::CubicTo(..) | PathCmd::QuadTo(..))) {
|
||||
return Err(EngineError::Param(format!("segment {cmd} of this shape is not a curve (it has no handles)")));
|
||||
}
|
||||
let old: Cubic = rawgeom::segment_cubic(&path, cmd).map(|c| rawgeom::transform(&c, &el.transform)).ok_or_else(|| EngineError::Param(format!("no segment {cmd} on this shape")))?;
|
||||
let mut new = old;
|
||||
if let Some(h) = new.get_mut(slot) {
|
||||
*h = *h + d;
|
||||
}
|
||||
if !new.iter().all(|q| q.is_finite()) {
|
||||
return Err(EngineError::Param("the move is too large".into()));
|
||||
}
|
||||
let mut bounds = Path::new();
|
||||
bounds.move_to(new[0]).cubic_to(new[1], new[2], new[3]);
|
||||
check_extent(&bounds)?;
|
||||
let raw = mergeable(el).is_some();
|
||||
let changed = edit_edge(s, id, cmd, &old, &new, raw)?;
|
||||
if raw && merge_after {
|
||||
remerge_in_place(s, &changed)?;
|
||||
}
|
||||
let at = new.get(slot).copied().unwrap_or(new[0]);
|
||||
Ok(json!({"x": at.x, "y": at.y, "changed": changed.iter().map(|e| e.0).collect::<Vec<_>>(), "merged": raw && merge_after}))
|
||||
}
|
||||
@@ -18,6 +18,7 @@ mod cmds_hints;
|
||||
mod cmds_paint;
|
||||
mod cmds_path;
|
||||
pub mod cmds_raw;
|
||||
pub mod cmds_rawsub;
|
||||
mod cmds_recovery;
|
||||
mod cmds_script;
|
||||
pub mod cmds_plugin;
|
||||
@@ -111,6 +112,7 @@ pub fn commands() -> Vec<CommandSpec> {
|
||||
v.extend(cmds_modify::specs());
|
||||
v.extend(cmds_path::specs());
|
||||
v.extend(cmds_raw::specs());
|
||||
v.extend(cmds_rawsub::specs());
|
||||
v.extend(cmds_brush::specs());
|
||||
v.extend(cmds_erase::specs());
|
||||
v.extend(cmds_paint::specs());
|
||||
@@ -159,11 +161,14 @@ pub struct ToolStyle {
|
||||
/// touch (ADR 0031). On by default, so a script's draw command makes one element; the editor
|
||||
/// starts with it off, as Animate does.
|
||||
pub object_drawing: bool,
|
||||
/// Snap to Objects (Animate's magnet, ADR 0042): dragged points and selections snap to
|
||||
/// points, lines and fill edges nearby. On by default; off, the `snap` params do nothing.
|
||||
pub snap_objects: bool,
|
||||
}
|
||||
|
||||
impl Default for ToolStyle {
|
||||
fn default() -> Self {
|
||||
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 }
|
||||
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, snap_objects: true }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +186,10 @@ impl ToolStyle {
|
||||
pub fn profile(&self) -> Option<anicraft_doc::WidthProfile> {
|
||||
self.custom_profile.clone().or_else(|| self.stroke_profile.profile())
|
||||
}
|
||||
/// The snapping radius a command asked for (`snap`), or none when Snap to Objects is off.
|
||||
pub fn snap_radius(&self, asked: f32) -> f32 {
|
||||
if self.snap_objects { asked } else { 0.0 }
|
||||
}
|
||||
/// 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;
|
||||
@@ -889,6 +898,8 @@ mod merge_tests;
|
||||
#[cfg(test)]
|
||||
mod raw_tests;
|
||||
#[cfg(test)]
|
||||
mod rawsub_tests;
|
||||
#[cfg(test)]
|
||||
mod brush_tests;
|
||||
#[cfg(test)]
|
||||
mod web_tests;
|
||||
|
||||
+166
-9
@@ -4,7 +4,7 @@
|
||||
|
||||
use crate::params::*;
|
||||
use crate::{CommandSpec, Result, Session};
|
||||
use anicraft_doc::{ColorEffect, Element, ElementId, ElementKind, Paint, Shape, Stroke};
|
||||
use anicraft_doc::{ColorEffect, Document, Element, ElementId, ElementKind, Paint, Shape, Stroke, Timeline};
|
||||
use anicraft_geom::planar::{self, Item, SNAP};
|
||||
use anicraft_geom::{Affine, Path, PathCmd, Rect, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
@@ -18,18 +18,21 @@ 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).
|
||||
/// A raw shape the merge can take: any fill (solid, gradient or bitmap: the paint is carried
|
||||
/// into each piece, ADR 0042) or none, and a stroke of one width or none. A width profile runs
|
||||
/// along the whole stroke, so cutting it would need its length carried through the merge; those
|
||||
/// strokes stay whole, as objects, for now.
|
||||
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),
|
||||
ElementKind::Shape(s) if s.merge && s.stroke.as_ref().is_none_or(|st| st.profile.is_none()) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a new shape with this style can join the drawing (other paints and width profiles are
|
||||
/// Whether a new shape with this style can join the drawing (strokes with a width profile are
|
||||
/// drawn as objects for now).
|
||||
pub(crate) fn can_merge(fill: Option<&Paint>, stroke: Option<&Stroke>) -> bool {
|
||||
matches!(fill, None | Some(Paint::Solid(_))) && stroke.is_none_or(|st| st.profile.is_none())
|
||||
pub(crate) fn can_merge(stroke: Option<&Stroke>) -> bool {
|
||||
stroke.is_none_or(|st| st.profile.is_none())
|
||||
}
|
||||
|
||||
pub(crate) fn reach(s: &Shape, m: &Affine) -> Rect {
|
||||
@@ -129,6 +132,11 @@ pub(crate) struct Remerged {
|
||||
|
||||
/// [`remerge`], cutting along `cutter` too when there is one ([`planar::merge_cut`]).
|
||||
pub(crate) fn remerge_with(s: &mut Session, parts: &[Part], cutter: Option<&Path>) -> Option<Remerged> {
|
||||
remerge_doc(&mut s.doc, parts, cutter)
|
||||
}
|
||||
|
||||
/// [`remerge_with`] for any document (new pieces take ids from `doc`).
|
||||
fn remerge_doc(doc: &mut Document, parts: &[Part], cutter: Option<&Path>) -> Option<Remerged> {
|
||||
// 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();
|
||||
@@ -140,7 +148,9 @@ pub(crate) fn remerge_with(s: &mut Session, parts: &[Part], cutter: Option<&Path
|
||||
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)));
|
||||
// Gradients and bitmaps are placed in keyframe space, so every piece shows its
|
||||
// part of the paint where it was.
|
||||
let fill = sh.fill.as_ref().map(|f| fill_index(&mut fills, (f.transformed(&e.transform), e.color)));
|
||||
let stroke = sh.stroke.clone().map(|st| index_of(&mut strokes, (Stroke { width: st.width * e.transform.mean_scale(), ..st }, e.color)));
|
||||
styles.push((fill, stroke, sh.fill_rule));
|
||||
marked.push(*mark);
|
||||
@@ -172,7 +182,7 @@ pub(crate) fn remerge_with(s: &mut Session, parts: &[Part], cutter: Option<&Path
|
||||
};
|
||||
// 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());
|
||||
let id = ElementId(doc.alloc_id());
|
||||
if marked.get(piece.item).copied().unwrap_or(false) {
|
||||
picked.push(id);
|
||||
}
|
||||
@@ -187,7 +197,7 @@ pub(crate) fn remerge_with(s: &mut Session, parts: &[Part], cutter: Option<&Path
|
||||
name: String::new(),
|
||||
transform: Affine::translate(c.x, c.y),
|
||||
color,
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill, stroke, fill_rule: Default::default(), merge: true }),
|
||||
kind: ElementKind::Shape(Shape { path: Arc::new(piece.path.transformed(&Affine::translate(-c.x, -c.y))), fill: fill.map(|f| f.transformed(&Affine::translate(-c.x, -c.y))), stroke, fill_rule: Default::default(), merge: true }),
|
||||
}));
|
||||
}
|
||||
Some(Remerged { out, picked, inside, from })
|
||||
@@ -222,6 +232,33 @@ fn add_whole(kf: &mut anicraft_doc::Keyframe, els: Vec<Element>, order: Order) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fill table's entry for `v`: paints that differ only by rounding (a gradient carried into a
|
||||
/// piece and back) are one style, so pieces of one fill join again.
|
||||
fn fill_index(table: &mut Vec<(Paint, ColorEffect)>, v: (Paint, ColorEffect)) -> u32 {
|
||||
match table.iter().position(|x| x.1 == v.1 && same_paint(&x.0, &v.0)) {
|
||||
Some(i) => i as u32,
|
||||
None => {
|
||||
table.push(v);
|
||||
(table.len() - 1) as u32
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two paints look the same (positions within a thousandth of a unit).
|
||||
pub(crate) fn same_paint(a: &Paint, b: &Paint) -> bool {
|
||||
const EPS: f32 = 1e-3;
|
||||
let near = |p: Vec2, q: Vec2| p.distance(q) <= EPS;
|
||||
match (a, b) {
|
||||
(Paint::Solid(x), Paint::Solid(y)) => x == y,
|
||||
(Paint::Linear { start: s0, end: e0, stops: a }, Paint::Linear { start: s1, end: e1, stops: b }) => near(*s0, *s1) && near(*e0, *e1) && a == b,
|
||||
(Paint::Radial { center: c0, radius: r0, stops: a }, Paint::Radial { center: c1, radius: r1, stops: b }) => near(*c0, *c1) && (r0 - r1).abs() <= EPS && a == b,
|
||||
(Paint::Bitmap { bitmap: b0, repeat: r0, matrix: m0 }, Paint::Bitmap { bitmap: b1, repeat: r1, matrix: m1 }) => {
|
||||
b0 == b1 && r0 == r1 && m0.m.iter().zip(m1.m).all(|(x, y)| (x - y).abs() <= EPS * x.abs().max(y.abs()).max(1.0))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn index_of<T: PartialEq>(table: &mut Vec<T>, v: T) -> u32 {
|
||||
match table.iter().position(|x| *x == v) {
|
||||
Some(i) => i as u32,
|
||||
@@ -255,6 +292,126 @@ fn drop(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"dropped": n, "selected": s.selection.iter().map(|e| e.0).collect::<Vec<_>>()}))
|
||||
}
|
||||
|
||||
// ----- the Paint Bucket and imported drawings (ADR 0042) ---------------------------------------
|
||||
|
||||
/// The probe's fill style: what is left of it after the merge is empty area.
|
||||
const PROBE: u32 = u32::MAX - 1;
|
||||
|
||||
/// The empty area around `at` that the raw strokes and fills of `els` close off, as Animate's
|
||||
/// Paint Bucket fills it: exactly up to the lines and fill edges, holes and all. `None` when the
|
||||
/// raw shapes leave it open (it reaches past them), when `at` is on a fill, or when there is too
|
||||
/// much to merge at once.
|
||||
///
|
||||
/// A fill under everything (the probe) is merged with the raw shapes: what remains of it are the
|
||||
/// empty areas, divided by every line and fill edge, and the one under `at` is the answer unless
|
||||
/// it reaches the probe's border. The probe starts as a small window around `at`, with only the
|
||||
/// shapes that reach into it, and grows while the area reaches its border, so a fill costs what
|
||||
/// is near it rather than the whole drawing (shapes wholly outside a window cannot touch an area
|
||||
/// inside it).
|
||||
pub(crate) fn enclosed_area(els: &[Arc<Element>], at: Vec2) -> Option<Path> {
|
||||
let raw: Vec<(&Element, &Shape, Rect)> = els.iter().filter_map(|e| mergeable(e).map(|sh| (e.as_ref(), sh, reach(sh, &e.transform)))).collect();
|
||||
let area = raw.iter().fold(Rect::EMPTY, |r, (_, _, b)| r.union(b));
|
||||
if area.is_empty() || !area.contains(at) {
|
||||
return None;
|
||||
}
|
||||
let all = area.inflate(8.0);
|
||||
let mut half = 64.0f32;
|
||||
loop {
|
||||
let window = Rect::new(at.x - half, at.y - half, at.x + half, at.y + half);
|
||||
let last = window.min.x <= all.min.x && window.min.y <= all.min.y && window.max.x >= all.max.x && window.max.y >= all.max.y;
|
||||
let outer = if last { all } else { window };
|
||||
let near: Vec<&(&Element, &Shape, Rect)> = raw.iter().filter(|(_, _, b)| !b.intersect(&outer).is_empty()).collect();
|
||||
match probe(&near, &outer, at)? {
|
||||
Some(path) => return Some(path),
|
||||
None if last => return None,
|
||||
// It reaches the window's border: look wider.
|
||||
None => half *= 4.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One probe merge over `outer`: `Some(Some(area))` when the empty area at `at` is closed off
|
||||
/// inside it, `Some(None)` when it reaches the border, `None` when `at` is not in an empty area
|
||||
/// or the merge declines.
|
||||
fn probe(raw: &[&(&Element, &Shape, Rect)], outer: &Rect, at: Vec2) -> Option<Option<Path>> {
|
||||
let rect = Path::rect(outer.min.x, outer.min.y, outer.width(), outer.height());
|
||||
let paths: Vec<Path> = raw.iter().map(|(e, sh, _)| sh.path.transformed(&e.transform)).collect();
|
||||
let mut items = vec![Item { path: &rect, fill: Some(PROBE), fill_rule: anicraft_geom::FillRule::NonZero, stroke: None }];
|
||||
for (i, ((_, sh, _), path)) in raw.iter().map(|x| **x).zip(&paths).enumerate() {
|
||||
let n = u32::try_from(i).ok()?;
|
||||
items.push(Item { path, fill: sh.fill.as_ref().map(|_| n), fill_rule: sh.fill_rule, stroke: sh.stroke.as_ref().map(|_| n) });
|
||||
}
|
||||
let merged = planar::merge(&items)?;
|
||||
let piece = merged.fills.into_iter().find(|p| p.style == PROBE && p.path.contains(at, &Affine::IDENTITY, anicraft_geom::FillRule::default()))?;
|
||||
let b = piece.path.bounds();
|
||||
let open = b.min.x <= outer.min.x + 1.0 || b.min.y <= outer.min.y + 1.0 || b.max.x >= outer.max.x - 1.0 || b.max.y >= outer.max.y - 1.0;
|
||||
Some((!open).then_some(piece.path))
|
||||
}
|
||||
|
||||
/// Merges every keyframe's raw shapes in `doc` into one merged drawing each (scenes and
|
||||
/// symbols): what an imported Animate file's raw shapes need, as their styles arrive one shape
|
||||
/// per style. Keyframes with too much to merge at once keep their shapes as they are. Returns
|
||||
/// how many keyframes changed.
|
||||
pub(crate) fn merge_document(doc: &mut Document) -> usize {
|
||||
let mut n = 0;
|
||||
let mut scenes = doc.scenes.clone();
|
||||
for sc in scenes.iter_mut() {
|
||||
let mut tl = sc.timeline.clone();
|
||||
let k = merge_timeline(doc, &mut tl);
|
||||
if k > 0 {
|
||||
Arc::make_mut(sc).timeline = tl;
|
||||
n += k;
|
||||
}
|
||||
}
|
||||
let mut library = doc.library.clone();
|
||||
for sym in library.iter_mut() {
|
||||
let mut tl = sym.timeline.clone();
|
||||
let k = merge_timeline(doc, &mut tl);
|
||||
if k > 0 {
|
||||
Arc::make_mut(sym).timeline = tl;
|
||||
n += k;
|
||||
}
|
||||
}
|
||||
if n > 0 {
|
||||
doc.scenes = scenes;
|
||||
doc.library = library;
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
fn merge_timeline(doc: &mut Document, tl: &mut Timeline) -> usize {
|
||||
let mut n = 0;
|
||||
for layer in tl.layers.iter_mut() {
|
||||
if !layer.keyframes.iter().any(|k| k.elements.iter().any(|e| mergeable(e).is_some())) {
|
||||
continue;
|
||||
}
|
||||
let layer = Arc::make_mut(layer);
|
||||
// A tween pairs its keyframes' shapes in order, so the keyframes it joins keep theirs.
|
||||
let shape_tween = |k: &anicraft_doc::Keyframe| k.tween.is_some() || k.motion.is_some();
|
||||
let morphing: Vec<bool> = (0..layer.keyframes.len()).map(|i| layer.keyframes.get(i).is_some_and(|k| shape_tween(k)) || i.checked_sub(1).and_then(|j| layer.keyframes.get(j)).is_some_and(|k| shape_tween(k))).collect();
|
||||
for (kf, morph) in layer.keyframes.iter_mut().zip(morphing) {
|
||||
let idx: Vec<usize> = kf.elements.iter().enumerate().filter(|(_, e)| mergeable(e).is_some()).map(|(i, _)| i).collect();
|
||||
if idx.is_empty() || morph {
|
||||
continue;
|
||||
}
|
||||
let kf = Arc::make_mut(kf);
|
||||
let existing = kf.elements.clone();
|
||||
let parts: Vec<Part> = idx.iter().filter_map(|&i| existing.get(i)).map(|e| Part::Shape(e.as_ref(), false)).collect();
|
||||
let Some(rm) = remerge_doc(doc, &parts, None) else { continue };
|
||||
let at = idx.first().copied().unwrap_or(0);
|
||||
for &i in idx.iter().rev() {
|
||||
if i < kf.elements.len() {
|
||||
kf.elements.remove(i);
|
||||
}
|
||||
}
|
||||
let at = at.min(kf.elements.len());
|
||||
kf.elements.splice(at..at, rm.out);
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// The ends of every open subpath (where raw strokes join), in keyframe space.
|
||||
fn ends(path: &Path, m: &Affine) -> Vec<Vec2> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
//! Subselection on raw shapes and merging everywhere (ADR 0042), through the commands.
|
||||
|
||||
use crate::Session;
|
||||
use anicraft_doc::{Element, ElementKind, GradientStop, Paint, Rgba};
|
||||
use anicraft_geom::{Affine, Vec2};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id}: {e}"))
|
||||
}
|
||||
|
||||
fn raw_session() -> Session {
|
||||
let mut s = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut s, "draw.object_drawing", json!({"on": false}));
|
||||
s
|
||||
}
|
||||
|
||||
fn raw(s: &Session) -> Vec<Arc<Element>> {
|
||||
s.visible_elements().into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.merge)).collect()
|
||||
}
|
||||
|
||||
fn fills(s: &Session) -> Vec<Arc<Element>> {
|
||||
raw(s).into_iter().filter(|e| matches!(&e.kind, ElementKind::Shape(sh) if sh.fill.is_some())).collect()
|
||||
}
|
||||
|
||||
fn area(e: &Element) -> f32 {
|
||||
let ElementKind::Shape(sh) = &e.kind else { return 0.0 };
|
||||
sh.path
|
||||
.flatten(&e.transform, 0.01)
|
||||
.iter()
|
||||
.map(|pl| {
|
||||
let n = pl.points.len();
|
||||
(0..n).map(|i| pl.points[i].cross(pl.points[(i + 1) % n])).sum::<f32>() * 0.5
|
||||
})
|
||||
.sum::<f32>()
|
||||
.abs()
|
||||
}
|
||||
|
||||
fn fill_color(e: &Element) -> Option<Rgba> {
|
||||
match &e.kind {
|
||||
ElementKind::Shape(sh) => match &sh.fill {
|
||||
Some(Paint::Solid(c)) => Some(*c),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ids(v: &Value, key: &str) -> Vec<u64> {
|
||||
v[key].as_array().into_iter().flatten().filter_map(Value::as_u64).collect()
|
||||
}
|
||||
|
||||
fn xy(v: &Value) -> Vec<Vec2> {
|
||||
v.as_array().into_iter().flatten().filter_map(|p| Some(Vec2::new(p.get(0)?.as_f64()? as f32, p.get(1)?.as_f64()? as f32))).collect()
|
||||
}
|
||||
|
||||
fn has(points: &[Vec2], p: (f32, f32)) -> bool {
|
||||
points.iter().any(|q| q.distance(Vec2::new(p.0, p.1)) < 1e-2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_shows_the_anchors_of_everything_connected_once_each() {
|
||||
let mut s = raw_session();
|
||||
// An outlined rectangle, a line from its corner, and a line far away.
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
run(&mut s, "draw.line", json!({"x0": 100, "y0": 80, "x1": 160, "y1": 140, "stroke": "#000000"}));
|
||||
run(&mut s, "draw.line", json!({"x0": 300, "y0": 0, "x1": 400, "y1": 0, "stroke": "#000000"}));
|
||||
// Fill, four sides, the joined line: six shapes. The far line is not connected.
|
||||
assert_eq!(raw(&s).len(), 7);
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 0}));
|
||||
assert_eq!(v["raw"], json!(true));
|
||||
assert_eq!(ids(&v, "selected").len(), 6, "{v}");
|
||||
let anchors = xy(&v["anchors"]);
|
||||
assert_eq!(anchors.len(), 5, "four corners shared by fill and sides, and the line's far end: {anchors:?}");
|
||||
for p in [(0.0, 0.0), (100.0, 0.0), (100.0, 80.0), (0.0, 80.0), (160.0, 140.0)] {
|
||||
assert!(has(&anchors, p), "{p:?} in {anchors:?}");
|
||||
}
|
||||
// The clicked edge's ends (whose handles show).
|
||||
let ends = xy(&v["ends"]);
|
||||
assert!(has(&ends, (0.0, 0.0)) && has(&ends, (100.0, 0.0)), "{ends:?}");
|
||||
// Straight edges have no handles.
|
||||
assert!(v["handles"].as_array().is_some_and(Vec::is_empty));
|
||||
// Inside the fill: the same set, no edge.
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40}));
|
||||
assert_eq!(ids(&v, "selected").len(), 6);
|
||||
assert!(xy(&v["ends"]).is_empty());
|
||||
// The far line alone.
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 350, "y": 0}));
|
||||
assert_eq!(ids(&v, "selected").len(), 1);
|
||||
assert_eq!(xy(&v["anchors"]).len(), 2);
|
||||
// Shift adds; empty space clears.
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40, "add": true}));
|
||||
assert_eq!(ids(&v, "selected").len(), 7);
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 700, "y": 700}));
|
||||
assert!(ids(&v, "selected").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_that_meet_along_an_edge_and_lines_ending_on_an_edge_are_connected() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null}));
|
||||
// A line standing on the blue square's top edge (a T-junction, not a corner).
|
||||
run(&mut s, "draw.line", json!({"x0": 150, "y0": 0, "x1": 150, "y1": -50, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(ids(&v, "selected").len(), 3, "red, blue and the line: {v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_a_handle_changes_the_curve_in_both_shapes_that_share_it() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.ellipse", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 50}));
|
||||
let handles = v["handles"].as_array().cloned().unwrap_or_default();
|
||||
// A circle of four arcs: two handles per arc, each listed once although the fill and the
|
||||
// outline both have it.
|
||||
assert_eq!(handles.len(), 8, "{v}");
|
||||
let h = &handles[0];
|
||||
let (id, cmd, slot) = (h["id"].as_u64().unwrap(), h["cmd"].as_u64().unwrap(), h["slot"].as_u64().unwrap());
|
||||
let before: Vec<Arc<Element>> = raw(&s);
|
||||
s.begin_gesture("Move Handle");
|
||||
let r = run(&mut s, "raw.move_handle", json!({"id": id, "cmd": cmd, "slot": slot, "dx": 20, "dy": -15, "merge": false}));
|
||||
assert_eq!(ids(&r, "changed").len(), 2, "the fill and its outline: {r}");
|
||||
// The edge moved the same way in both: the outline still runs along the fill's edge (to
|
||||
// within the flattening `distance_to_edge` measures with).
|
||||
let changed: Vec<Arc<Element>> = raw(&s).into_iter().filter(|e| ids(&r, "changed").contains(&e.id.0)).collect();
|
||||
let (fill, line) = match (changed.iter().find(|e| fill_color(e).is_some()), changed.iter().find(|e| fill_color(e).is_none())) {
|
||||
(Some(f), Some(l)) => (f.clone(), l.clone()),
|
||||
_ => panic!("a fill and a line changed"),
|
||||
};
|
||||
let ElementKind::Shape(ls) = &line.kind else { panic!() };
|
||||
let ElementKind::Shape(fs) = &fill.kind else { panic!() };
|
||||
for pl in ls.path.flatten(&line.transform, 0.05) {
|
||||
for p in pl.points {
|
||||
assert!(fs.path.distance_to_edge(p, &fill.transform) < 0.3, "{p:?} off the fill's edge");
|
||||
}
|
||||
}
|
||||
assert!(area(&fill) != area(before.iter().find(|e| fill_color(e).is_some()).unwrap()));
|
||||
// Release: they merge again, still joined, in one undo step.
|
||||
run(&mut s, "raw.merge", json!({"ids": ids(&r, "changed")}));
|
||||
s.end_gesture();
|
||||
assert_eq!(fills(&s).len(), 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(raw(&s).iter().map(|e| e.id).collect::<Vec<_>>(), before.iter().map(|e| e.id).collect::<Vec<_>>());
|
||||
// Straight segments have no handles to move.
|
||||
let mut t = raw_session();
|
||||
run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 10, "h": 10, "fill": "#ff0000", "stroke": null}));
|
||||
let id = raw(&t)[0].id.0;
|
||||
assert!(t.execute("raw.move_handle", &json!({"id": id, "cmd": 1, "slot": 1, "dx": 1, "dy": 1})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_anchors_move_together_with_every_shape_that_shares_them() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
// The top edge's two corners, 10 px up (the arrow keys, Shift: one step, merged).
|
||||
run(&mut s, "raw.move_point", json!({"x": 0, "y": 0, "to_x": 0, "to_y": -10, "with": [[100, 0]]}));
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 1);
|
||||
assert!((area(&f[0]) - 100.0 * 90.0).abs() < 0.5, "{}", area(&f[0]));
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 50, "y": 40}));
|
||||
let anchors = xy(&v["anchors"]);
|
||||
assert!(has(&anchors, (0.0, -10.0)) && has(&anchors, (100.0, -10.0)) && anchors.len() == 4, "{anchors:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_marquee_takes_whole_connected_shapes_on_the_active_layer_and_selects_the_anchors_inside() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": "#000000"}));
|
||||
run(&mut s, "draw.line", json!({"x0": 300, "y0": 0, "x1": 400, "y1": 0, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
// Over the bottom-right corner only.
|
||||
let v = run(&mut s, "raw.subselect_rect", json!({"x0": 90, "y0": 70, "x1": 120, "y1": 100}));
|
||||
assert_eq!(ids(&v, "selected").len(), 5, "the fill and its four sides: {v}");
|
||||
let inside = xy(&v["anchors"]);
|
||||
assert_eq!(inside.len(), 1);
|
||||
assert!(has(&inside, (100.0, 80.0)));
|
||||
// Through the middle of the fill, no anchors inside: the shapes, no anchors.
|
||||
let v = run(&mut s, "raw.subselect_rect", json!({"x0": 40, "y0": 30, "x1": 60, "y1": 50}));
|
||||
assert_eq!(ids(&v, "selected").len(), 5);
|
||||
assert!(xy(&v["anchors"]).is_empty());
|
||||
// Another layer is not reached.
|
||||
run(&mut s, "layer.new", json!({}));
|
||||
let v = run(&mut s, "raw.subselect_rect", json!({"x0": -10, "y0": -10, "x1": 500, "y1": 100}));
|
||||
assert!(ids(&v, "selected").is_empty(), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapping_off_disables_snapping_for_both_tools() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 80, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.line", json!({"x0": 200, "y0": 0, "x1": 300, "y1": 0, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let drag_point = |s: &mut Session| run(s, "raw.move_point", json!({"x": 200, "y": 0, "to_x": 104, "to_y": 3, "snap": 10, "merge": false}));
|
||||
// On: the line's end goes onto the rectangle's corner.
|
||||
s.begin_gesture("t");
|
||||
let v = drag_point(&mut s);
|
||||
assert_eq!(v["snapped"]["to"], json!("point"), "{v}");
|
||||
assert!((v["x"].as_f64().unwrap() - 100.0).abs() < 1e-3);
|
||||
s.end_gesture();
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
// Off: it goes where the pointer took it.
|
||||
assert_eq!(run(&mut s, "draw.snap_to_objects", json!({}))["snap_to_objects"], json!(false));
|
||||
let v = drag_point(&mut s);
|
||||
assert!(v["snapped"].is_null(), "{v}");
|
||||
assert!((v["x"].as_f64().unwrap() - 104.0).abs() < 1e-3);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
// A selection move (the Selection tool's, and Subselection's on connected shapes) too.
|
||||
run(&mut s, "raw.subselect", json!({"x": 250, "y": 0}));
|
||||
let v = run(&mut s, "element.translate", json!({"dx": -96, "dy": 3, "snap": 10, "from": [200, 0]}));
|
||||
assert!(v["snapped"].is_null() && (v["dx"].as_f64().unwrap() + 96.0).abs() < 1e-3, "{v}");
|
||||
run(&mut s, "draw.snap_to_objects", json!({"on": true}));
|
||||
let v = run(&mut s, "element.translate", json!({"dx": 1, "dy": -1, "snap": 10, "from": [105, 3]}));
|
||||
assert!(!v["snapped"].is_null(), "{v}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paint_bucket_fill_merges_with_an_adjacent_fill_of_its_colour() {
|
||||
let mut s = raw_session();
|
||||
// A red square, and lines that close an area against its right edge.
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.path", json!({"d": "M100 0 L200 0 L200 100 L100 100", "fill": null, "stroke": "#000000"}));
|
||||
let v = run(&mut s, "paint.bucket", json!({"x": 150, "y": 50, "color": "#ff0000"}));
|
||||
assert_eq!(v["merged"], json!(true));
|
||||
assert_eq!(v["exact"], json!(true), "closed by raw lines and a fill edge: filled exactly");
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 1, "one red fill");
|
||||
assert!((area(&f[0]) - 20_000.0).abs() < 1.0, "{}", area(&f[0]));
|
||||
// Another colour stays its own fill, up to the lines exactly.
|
||||
let mut t = raw_session();
|
||||
run(&mut t, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000"}));
|
||||
run(&mut t, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null}));
|
||||
run(&mut t, "paint.bucket", json!({"x": 50, "y": 50, "color": "#00ff00"}));
|
||||
let f = fills(&t);
|
||||
assert_eq!(f.len(), 2);
|
||||
let green = f.iter().find(|e| fill_color(e) == Rgba::parse_hex("#00ff00")).unwrap();
|
||||
assert!((area(green) - 10_000.0).abs() < 1.0, "{}", area(green));
|
||||
// Recolouring the blue square green joins the two greens (no line between them? there is
|
||||
// one: the square's right side stays, so they stay two).
|
||||
run(&mut t, "paint.bucket", json!({"x": 150, "y": 50, "color": "#00ff00"}));
|
||||
assert_eq!(fills(&t).len(), 2, "the outline's right side divides them");
|
||||
// An open area: nothing is filled.
|
||||
let mut u = raw_session();
|
||||
run(&mut u, "draw.path", json!({"d": "M0 0 L100 0 L100 100", "fill": null, "stroke": "#000000"}));
|
||||
assert!(u.execute("paint.bucket", &json!({"x": 60, "y": 30})).is_err());
|
||||
// Headless sessions (Object Drawing on) keep making an object.
|
||||
let mut o = Session::new(anicraft_doc::Document::default());
|
||||
run(&mut o, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": null, "stroke": "#000000"}));
|
||||
let v = run(&mut o, "paint.bucket", json!({"x": 50, "y": 50}));
|
||||
assert!(v.get("merged").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recolouring_a_raw_fill_joins_the_fills_of_its_new_colour() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 100, "y": 0, "w": 100, "h": 100, "fill": "#0000ff", "stroke": null}));
|
||||
assert_eq!(fills(&s).len(), 2);
|
||||
let v = run(&mut s, "paint.bucket", json!({"x": 150, "y": 50, "color": "#ff0000"}));
|
||||
assert_eq!(v["merged"], json!(true));
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 1);
|
||||
assert!((area(&f[0]) - 20_000.0).abs() < 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pasted_raw_shape_cuts_what_it_lands_on() {
|
||||
let mut s = raw_session();
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null}));
|
||||
run(&mut s, "draw.rect", json!({"x": 300, "y": 0, "w": 50, "h": 50, "fill": "#0000ff", "stroke": null}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let v = run(&mut s, "edit.paste", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(v["merged"], json!(true));
|
||||
let red = fills(&s).into_iter().find(|e| fill_color(e) == Rgba::parse_hex("#ff0000")).unwrap();
|
||||
assert!((area(&red) - (10_000.0 - 2_500.0)).abs() < 1.0, "the blue square cut a hole: {}", area(&red));
|
||||
assert_eq!(fills(&s).len(), 3);
|
||||
// The pasted piece is selected.
|
||||
assert_eq!(ids(&v, "pasted").len(), 1);
|
||||
// Paste in Place over itself: one blue square there, not two.
|
||||
run(&mut s, "edit.paste_in_place", json!({}));
|
||||
assert_eq!(fills(&s).len(), 3);
|
||||
// Objects on the clipboard still go on top, whole.
|
||||
run(&mut s, "draw.object_drawing", json!({"on": true}));
|
||||
run(&mut s, "draw.rect", json!({"x": 500, "y": 0, "w": 10, "h": 10, "fill": "#00ff00", "stroke": null}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
let v = run(&mut s, "edit.paste", json!({"x": 50, "y": 50}));
|
||||
assert_eq!(v["merged"], json!(false));
|
||||
assert_eq!(fills(&s).len(), 3);
|
||||
}
|
||||
|
||||
fn linear() -> Paint {
|
||||
Paint::Linear { start: Vec2::new(0.0, 0.0), end: Vec2::new(200.0, 0.0), stops: vec![GradientStop { offset: 0.0, color: Rgba::hex(0xff0000) }, GradientStop { offset: 1.0, color: Rgba::hex(0x0000ff) }] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_fills_take_part_in_the_merge() {
|
||||
let mut s = raw_session();
|
||||
s.style.fill_paint = Some(linear());
|
||||
run(&mut s, "draw.rect", json!({"x": 0, "y": 0, "w": 200, "h": 100, "stroke": null}));
|
||||
assert_eq!(fills(&s).len(), 1, "raw, not an object");
|
||||
// A line across cuts it in two; each half shows its part of the gradient where it was.
|
||||
run(&mut s, "draw.line", json!({"x0": 100, "y0": -20, "x1": 100, "y1": 120, "stroke": "#000000"}));
|
||||
let f = fills(&s);
|
||||
assert_eq!(f.len(), 2);
|
||||
for e in &f {
|
||||
let ElementKind::Shape(sh) = &e.kind else { panic!() };
|
||||
let Some(Paint::Linear { start, end, .. }) = sh.fill.as_ref().map(|p| p.transformed(&e.transform)) else { panic!("{:?}", sh.fill) };
|
||||
assert!(start.distance(Vec2::ZERO) < 1e-3 && end.distance(Vec2::new(200.0, 0.0)) < 1e-3, "{start:?} {end:?}");
|
||||
}
|
||||
// Deleting the line joins the halves again: one gradient fill.
|
||||
let line = raw(&s).into_iter().find(|e| fill_color(e).is_none() && matches!(&e.kind, ElementKind::Shape(sh) if sh.stroke.is_some())).unwrap();
|
||||
s.selection = vec![line.id];
|
||||
run(&mut s, "edit.delete", json!({}));
|
||||
let halves: Vec<u64> = fills(&s).iter().map(|e| e.id.0).collect();
|
||||
run(&mut s, "raw.merge", json!({"ids": halves}));
|
||||
assert_eq!(fills(&s).len(), 1);
|
||||
assert!((area(&fills(&s)[0]) - 20_000.0).abs() < 1.0);
|
||||
// A solid fill drawn over it cuts into the gradient as into any fill.
|
||||
run(&mut s, "draw.rect", json!({"x": 50, "y": 25, "w": 50, "h": 50, "fill": "#00ff00", "stroke": null}));
|
||||
let g = fills(&s).into_iter().find(|e| fill_color(e).is_none()).unwrap();
|
||||
assert!((area(&g) - (20_000.0 - 2_500.0)).abs() < 1.0);
|
||||
// A width profile still makes an object.
|
||||
let mut t = raw_session();
|
||||
t.style.set_profile(anicraft_doc::ProfilePreset::TaperBoth);
|
||||
run(&mut t, "draw.line", json!({"x0": 0, "y0": 0, "x1": 100, "y1": 0}));
|
||||
assert!(raw(&t).is_empty());
|
||||
let _ = Affine::IDENTITY;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subselection_timings() {
|
||||
// 12 × 12 outlined squares and lines across every row (ADR 0041's test drawing).
|
||||
let mut s = raw_session();
|
||||
for i in 0..12 {
|
||||
for j in 0..12 {
|
||||
run(&mut s, "draw.rect", json!({"x": i * 50, "y": j * 50, "w": 40, "h": 40, "fill": "#ff0000", "stroke": "#000000", "radius": 6}));
|
||||
}
|
||||
run(&mut s, "draw.line", json!({"x0": -10, "y0": i * 50 + 20, "x1": 610, "y1": i * 50 + 20, "stroke": "#0000ff"}));
|
||||
}
|
||||
// An empty outlined square for the Paint Bucket.
|
||||
run(&mut s, "draw.rect", json!({"x": 700, "y": 0, "w": 40, "h": 40, "fill": null, "stroke": "#000000"}));
|
||||
run(&mut s, "edit.deselect", json!({}));
|
||||
let n = s.visible_elements().len();
|
||||
let t = std::time::Instant::now();
|
||||
let v = run(&mut s, "raw.subselect", json!({"x": 320, "y": 320}));
|
||||
let click = t.elapsed();
|
||||
let sel: Vec<anicraft_doc::ElementId> = s.selection.clone();
|
||||
let t = std::time::Instant::now();
|
||||
let pts = s.raw_points(&sel);
|
||||
let list = t.elapsed();
|
||||
let h = pts.handles.first().copied().unwrap();
|
||||
s.begin_gesture("Move Handle");
|
||||
let t = std::time::Instant::now();
|
||||
let r = run(&mut s, "raw.move_handle", json!({"id": h.id.0, "cmd": h.cmd, "slot": h.slot, "dx": 1, "dy": 1, "merge": false}));
|
||||
let frame = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
run(&mut s, "raw.merge", json!({"ids": ids(&r, "changed")}));
|
||||
let merge = t.elapsed();
|
||||
s.end_gesture();
|
||||
let t = std::time::Instant::now();
|
||||
assert_eq!(run(&mut s, "paint.bucket", json!({"x": 720, "y": 20, "color": "#00ff00"}))["exact"], json!(true));
|
||||
let bucket = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
let _ = s.execute("paint.bucket", &json!({"x": 45, "y": 45, "color": "#00ff00"}));
|
||||
let open = t.elapsed();
|
||||
eprintln!(
|
||||
"{n} raw shapes; connected set {} shapes, {} anchors, {} handles; click {:.2} ms, list {:.2} ms, handle frame {:.2} ms, merge {:.2} ms, bucket {:.2} ms (open area {:.2} ms)",
|
||||
ids(&v, "selected").len(),
|
||||
pts.anchors.len(),
|
||||
pts.handles.len(),
|
||||
click.as_secs_f64() * 1e3,
|
||||
list.as_secs_f64() * 1e3,
|
||||
frame.as_secs_f64() * 1e3,
|
||||
merge.as_secs_f64() * 1e3,
|
||||
bucket.as_secs_f64() * 1e3,
|
||||
open.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
@@ -588,6 +588,11 @@ fn panic_hunt_every_command() {
|
||||
json!({"x0": 10, "y0": 10, "x1": 45, "y1": 75, "add": true, "from": [1, 2, 3], "snap": 3}),
|
||||
json!({"x0": -1e7, "y0": 1e7, "x1": 1e7, "y1": -1e7, "add": false, "from": [45, 45], "snap": 0.2}),
|
||||
json!({"x0": 30, "y0": 30, "x1": 30, "y1": 30, "point_slop": -5, "ids": [u64::MAX], "points": "x"}),
|
||||
// Subselection on raw shapes (ADR 0042): handles that aren't there or move too far,
|
||||
// anchors to move along that are hostile, connected sets of anything.
|
||||
json!({"id": 3, "cmd": 1, "slot": 2, "dx": 1e30, "dy": 0, "x": 30, "y": 30, "to_x": 31, "to_y": 30, "with": [[30, 30], [1e30, 0]]}),
|
||||
json!({"id": 5, "cmd": u64::MAX, "slot": 9, "dx": 1, "dy": 1, "with": "x", "x0": 0, "y0": 0, "x1": 1e9, "y1": 1e9}),
|
||||
json!({"id": 4, "cmd": 2, "slot": 1, "dx": -3, "dy": 2, "x": 60, "y": 60, "to_x": 61, "to_y": 61, "with": [[60, 60], [30, 90], [90, 30]], "merge": false}),
|
||||
// Kept scripts (ADR 0013 tier 1): odd text, unknown languages, class names that aren't.
|
||||
json!({"text": "\u{0}\r\n]]>\u{202e}stop();", "language": "other", "class": "a.b", "base": "c", "symbol": 1}),
|
||||
json!({"text": "x".repeat(1 << 20), "language": 3, "class": "not a class", "base": ""}),
|
||||
|
||||
@@ -62,8 +62,9 @@ pub fn check(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], to
|
||||
compare(golden, name, width, height, rgba, tol)
|
||||
}
|
||||
|
||||
/// The comparison [`check`] makes when it isn't updating.
|
||||
fn compare(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], tol: Tolerance) -> Result<(), String> {
|
||||
/// The comparison [`check`] makes when it isn't updating (a test whose renders must match
|
||||
/// another test's goldens compares only, never writing them).
|
||||
pub fn compare(golden: &Path, name: &str, width: u32, height: u32, rgba: &[u8], tol: Tolerance) -> Result<(), String> {
|
||||
assert_eq!(rgba.len(), (width * height * 4) as usize);
|
||||
let keep = |why: String| -> String {
|
||||
let actual = out_dir().join(format!("{name}.actual.png"));
|
||||
|
||||
@@ -172,3 +172,31 @@ fn every_package_opens_with_file_open_and_round_trips_through_the_file_format()
|
||||
assert!(s.doc == t.doc, "{case}: the saved document opens differently");
|
||||
}
|
||||
}
|
||||
|
||||
/// Animate's raw shapes open as raw shapes, each keyframe's merged into one drawing (ADR 0042),
|
||||
/// and look as they did: the goldens still match. A raw outline is one stroke per side (ADR
|
||||
/// 0031), so at a corner two round caps overlap where one round join was and their antialiased
|
||||
/// edges add up: a few corner pixels may be darker (47 of the shapes frame's 14,400).
|
||||
#[test]
|
||||
fn raw_shapes_open_raw_merged_and_unchanged_to_the_eye() {
|
||||
let mut failures = Vec::new();
|
||||
let (mut raw_total, mut merged_total) = (0, 0);
|
||||
for (case, frames) in FRAMES.iter().filter(|(c, _)| !matches!(*c, "text")) {
|
||||
let mut s = Session::default();
|
||||
let info = s.execute("file.open", &json!({"path": corpus().join(case).display().to_string()})).unwrap_or_else(|e| panic!("{case}: {e}"));
|
||||
let raw = s.doc.scenes.iter().flat_map(|sc| sc.timeline.layers.iter()).chain(s.doc.library.iter().flat_map(|sym| sym.timeline.layers.iter())).flat_map(|l| l.keyframes.iter()).flat_map(|k| k.elements.iter()).filter(|e| matches!(&e.kind, anicraft_engine::doc::ElementKind::Shape(sh) if sh.merge)).count();
|
||||
raw_total += raw;
|
||||
// (Keyframes a tween joins keep their shapes as they came.)
|
||||
merged_total += info["merged_keyframes"].as_u64().unwrap_or(0);
|
||||
for &f in *frames {
|
||||
let (w, h, rgba) = render(&s.doc, f);
|
||||
let golden = corpus().join(case).join("golden").join(format!("frame-{f:03}.png"));
|
||||
let corners = golden::Tolerance { pixels: 0.005, ..golden::DEFAULT };
|
||||
if let Err(e) = golden::compare(&golden, &format!("{case}-merged-frame-{f:03}"), w, h, &rgba, corners) {
|
||||
failures.push(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(raw_total > 0 && merged_total > 0, "the corpus has raw shapes, merged: {raw_total} shapes, {merged_total} keyframes");
|
||||
assert!(failures.is_empty(), "merged raw shapes look different:\n{}", failures.join("\n"));
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub mod walk;
|
||||
|
||||
pub use affine::{Affine, Decomposed};
|
||||
pub use fit::fit_curve;
|
||||
pub use path::{FillRule, Path, PathCmd, Polyline};
|
||||
pub use path::{FillRule, Path, PathCmd, Polyline, segment_distance};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::{Add, Mul, Neg, Sub};
|
||||
|
||||
@@ -247,9 +247,12 @@ impl<'a> Builder<'a> {
|
||||
}
|
||||
|
||||
/// Shapes for one `DOMShape`: a fill-only shape per fill style (bottom), then a stroke-only
|
||||
/// shape per stroke style, as Animate draws them.
|
||||
fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>) {
|
||||
/// shape per stroke style, as Animate draws them. A shape loose on a frame (not in a group,
|
||||
/// not a drawing object) is raw artwork: its shapes are marked to merge (ADR 0042), and the
|
||||
/// engine merges each keyframe's raw shapes into one drawing when it opens the file.
|
||||
fn shape(&mut self, el: &X, parent: &Affine, out: &mut Vec<Arc<Element>>, loose: bool) {
|
||||
let m = parent.mul(&matrix(el));
|
||||
let merge = loose && !el.bool("isDrawingObject").unwrap_or(false);
|
||||
let fills: Vec<(u32, Option<Paint>)> = el.list("fills").iter().map(|f| (f.u32("index").unwrap_or(0), f.children.first().and_then(|d| paint(d, &self.bitmaps, &mut self.report)))).collect();
|
||||
let strokes: Vec<(u32, Option<Stroke>)> = el.list("strokes").iter().map(|s| (s.u32("index").unwrap_or(0), s.children.first().and_then(|d| stroke(d, &self.bitmaps, &mut self.report)))).collect();
|
||||
let edges: Vec<Edge> = el
|
||||
@@ -262,14 +265,14 @@ impl<'a> Builder<'a> {
|
||||
let (Some(p), true) = (p, index > 0) else { continue };
|
||||
let path = edges::fill_path(&edges, index);
|
||||
if !path.is_empty() {
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge: false }), m, ColorEffect::default()));
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: Some(p), stroke: None, fill_rule: FillRule::EvenOdd, merge }), m, ColorEffect::default()));
|
||||
}
|
||||
}
|
||||
for (index, s) in strokes {
|
||||
let (Some(s), true) = (s, index > 0) else { continue };
|
||||
let path = edges::stroke_path(&edges, index);
|
||||
if !path.is_empty() {
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero, merge: false }), m, ColorEffect::default()));
|
||||
out.push(self.element(ElementKind::Shape(Shape { path: Arc::new(path), fill: None, stroke: Some(s), fill_rule: FillRule::NonZero, merge }), m, ColorEffect::default()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -443,7 +446,7 @@ impl<'a> Builder<'a> {
|
||||
}
|
||||
for el in list {
|
||||
match el.name.as_str() {
|
||||
"DOMShape" => self.shape(el, parent, out),
|
||||
"DOMShape" => self.shape(el, parent, out, depth == 0),
|
||||
"DOMGroup" => {
|
||||
let m = parent.mul(&matrix(el));
|
||||
self.elements(el.list("members"), &m, out, depth + 1);
|
||||
|
||||
@@ -435,3 +435,28 @@ trace(n);]]></script></Actionscript><elements><DOMSymbolInstance libraryItemName
|
||||
assert!(d.document_class.is_empty() && !report.kept.contains_key("document class"));
|
||||
assert!(report.kept.contains_key("frame scripts in ActionScript 3.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loose_shapes_come_in_raw_and_drawing_objects_and_groups_as_objects() {
|
||||
// Animate's raw shapes (merge drawing) are loose `DOMShape`s; a drawing object says so, and
|
||||
// a group is an object whatever it holds (ADR 0042).
|
||||
let square = |attrs: &str, x: u32| {
|
||||
format!(
|
||||
r##"<DOMShape {attrs}><fills><FillStyle index="1"><SolidColor color="#FF0000"/></FillStyle></fills><strokes><StrokeStyle index="1"><SolidStroke weight="2"><fill><SolidColor/></fill></SolidStroke></StrokeStyle></strokes>
|
||||
<edges><Edge fillStyle1="1" strokeStyle="1" edges="!{x} 0|{} 0|{} 2000|{x} 2000|{x} 0"/></edges></DOMShape>"##,
|
||||
x + 2000,
|
||||
x + 2000
|
||||
)
|
||||
};
|
||||
let doc = format!(
|
||||
r#"<DOMDocument width="400" height="100"><timelines><DOMTimeline name="Scene 1"><layers><DOMLayer name="Art"><frames><DOMFrame index="0"><elements>{}{}<DOMGroup><members>{}</members></DOMGroup></elements></DOMFrame></frames></DOMLayer></layers></DOMTimeline></timelines></DOMDocument>"#,
|
||||
square("", 0),
|
||||
square(r#"isDrawingObject="true""#, 4000),
|
||||
square("", 8000),
|
||||
);
|
||||
let doc: &'static str = Box::leak(doc.into_boxed_str());
|
||||
let (d, _) = import(&HashMap::from([("DOMDocument.xml", doc)])).unwrap();
|
||||
let merge: Vec<bool> = d.timeline(0).layers[0].keyframes[0].elements.iter().map(|e| matches!(&e.kind, ElementKind::Shape(s) if s.merge)).collect();
|
||||
// Each square is a fill and a stroke.
|
||||
assert_eq!(merge, [true, true, false, false, false, false]);
|
||||
}
|
||||
Reference in new issue
Block a user